Skip to content

Instantly share code, notes, and snippets.

@zhexuany
Last active March 29, 2017 14:01
Show Gist options
  • Save zhexuany/a3472941545aaad9b6233595e5543cc1 to your computer and use it in GitHub Desktop.
Save zhexuany/a3472941545aaad9b6233595e5543cc1 to your computer and use it in GitHub Desktop.
The Vigenère Cipher: A modified version.
package main
import "fmt"
func main() {
key := "BADboy"
msg := "This is fun!"
cm, cmr := initMap()
fmt.Println(encode(msg, key, cm, cmr))
fmt.Println(decode(encode(msg, key, cm, cmr), key, cm, cmr))
}
func initMap() (map[rune]int, map[int]rune) {
str := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,!?$&;:"
cipherMap := make(map[rune]int, len(str))
cipherReverseMap := make(map[int]rune, len(str))
for i, ch := range str {
cipherMap[ch] = i
cipherReverseMap[i] = ch
}
return cipherMap, cipherReverseMap
}
func encode(msg, key string, cm map[rune]int, cmr map[int]rune) string {
size := len(cm)
runes := make([]rune, len(msg))
krunes := []rune(key)
for i, ch := range msg {
msgIdx := cm[ch]
keyIdx := cm[krunes[i%len(key)]]
idx := (msgIdx + keyIdx) % size
runes[i] = cmr[idx]
}
return string(runes)
}
func abs(i int) int {
if i < 0 {
return -i
}
return i
}
func decode(msg, key string, cm map[rune]int, cmr map[int]rune) string {
size := len(cm)
runes := make([]rune, len(msg))
krunes := []rune(key)
for i, ch := range msg {
msgIdx := cm[ch]
keyIdx := cm[krunes[i%len(key)]]
var idx int
diff := msgIdx - keyIdx
if diff < 0 {
idx = (diff + size) % size
} else {
idx = diff % size
}
runes[i] = cmr[idx]
}
return string(runes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment