Skip to content

Commit 5fb9c7e

Browse files
committed
init
1 parent 0e014df commit 5fb9c7e

File tree

4 files changed

+53
-0
lines changed

4 files changed

+53
-0
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

Diff for: atbash_cipher.go

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package atbash_cipher
2+
3+
import "unicode/utf8"
4+
5+
// 因为是对称的,所以只需要做一张映射表就可以了,映射表是固定的
6+
var mappingTable = make(map[rune]rune, 0)
7+
8+
func init() {
9+
for index := 0; index < 26; index++ {
10+
fromCharacter := rune('A' + index)
11+
toCharacter := rune('A' + 25 - index)
12+
// 同时做一个大小写的映射,通过空间换时间避免掉判断大小写
13+
mappingTable[fromCharacter] = toCharacter
14+
mappingTable[fromCharacter+32] = toCharacter + 32
15+
}
16+
}
17+
18+
// Encrypt 对明文进行atbash加密,英文字符会进行映射,其它字符会保持原样
19+
func Encrypt(plaintext string) string {
20+
runeSlice := make([]rune, utf8.RuneCountInString(plaintext))
21+
for index, character := range plaintext {
22+
mappingToCharacter, exists := mappingTable[character]
23+
if exists {
24+
runeSlice[index] = mappingToCharacter
25+
} else {
26+
runeSlice[index] = character
27+
}
28+
}
29+
return string(runeSlice)
30+
}
31+
32+
// Decrypt 解密
33+
func Decrypt(ciphertext string) string {
34+
return Encrypt(ciphertext)
35+
}

Diff for: atbash_cipher_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package atbash_cipher
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func TestDecrypt(t *testing.T) {
9+
plaintext := "abcdefg"
10+
encryptResult := Encrypt(plaintext)
11+
fmt.Println(encryptResult)
12+
decryptResult := Decrypt(encryptResult)
13+
fmt.Println(decryptResult)
14+
}

Diff for: go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/cryptography-research-lab/go-atbash-cipher
2+
3+
go 1.18

0 commit comments

Comments
 (0)