-
Notifications
You must be signed in to change notification settings - Fork 0
/
rot.go
62 lines (48 loc) · 1.71 KB
/
rot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package crsuite
// ROTEncrypt performs a ROTn encryption on [plaintext] using
// [offset] and returns it.
// It is important to note that the ROT encryption performed on
// plaintext is using right-hand rotation of the text.
func ROTEncrypt(plaintext string, offset uint) (res string) {
rotMap, _ := generateRotationMaps(offset)
var ciphertext []rune
for _, c := range plaintext {
if _, ok := rotMap[c]; ok {
ciphertext = append(ciphertext, rotMap[c])
} else {
ciphertext = append(ciphertext, c)
}
}
return string(ciphertext)
}
// ROTDecrypt performs ROTn decryption on plaintext and returns it.
// The offset specified is taken as a negative value by the function, using
// which, ROTn operation is performed.
func ROTDecrypt(ciphertext string, offset uint) string {
_, rotMap := generateRotationMaps(offset)
var plaintext []rune
for _, c := range ciphertext {
if _, ok := rotMap[c]; ok {
plaintext = append(plaintext, rotMap[c])
} else {
plaintext = append(plaintext, c)
}
}
return string(plaintext)
}
// generates rotation maps for encryption and decryption
func generateRotationMaps(offset uint) (map[rune]rune, map[rune]rune) {
var rotMap = make(map[rune]rune)
var revRotMap = make(map[rune]rune)
upperCase := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowerCase := "abcdefghijklmnopqrstuvwxyz"
rotatedUpper := upperCase[offset%26:] + upperCase[:offset%26]
rotatedLower := lowerCase[offset%26:] + lowerCase[:offset%26]
for i := 0; i < len(upperCase); i++ {
rotMap[rune(upperCase[i])] = rune(rotatedUpper[i])
rotMap[rune(lowerCase[i])] = rune(rotatedLower[i])
revRotMap[rune(rotatedLower[i])] = rune(lowerCase[i])
revRotMap[rune(rotatedUpper[i])] = rune(upperCase[i])
}
return rotMap, revRotMap
}