implemented vigenere cipher and basic test
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
package psyfer
|
||||
|
||||
func VigenereCipher(input string, key string, decrypt bool) string {
|
||||
alphabet := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
chars := []rune(input)
|
||||
k := []rune(key)
|
||||
keyPos := 0
|
||||
output := ""
|
||||
for _, m := range chars {
|
||||
index := int(m - 'A')
|
||||
offset := int(k[keyPos]-'A') % 26
|
||||
if decrypt {
|
||||
index -= offset
|
||||
} else {
|
||||
index += offset
|
||||
}
|
||||
if index >= 26 {
|
||||
index -= 26
|
||||
} else if index < 0 {
|
||||
index += 26
|
||||
}
|
||||
output += string(alphabet[index])
|
||||
keyPos++
|
||||
if keyPos == len(key) {
|
||||
keyPos = 0
|
||||
}
|
||||
}
|
||||
return output
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package psyfer
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVigenereCipher(t *testing.T) {
|
||||
key := "vig"
|
||||
input := "theboyhasthebag"
|
||||
input = strings.ToUpper(strings.Replace(input, " ", "", -1))
|
||||
key = strings.ToUpper(strings.Replace(key, " ", "", -1))
|
||||
expected := "OPKWWECIYOPKWIM"
|
||||
actual := VigenereCipher(input, key, false)
|
||||
if expected != actual {
|
||||
t.Errorf(
|
||||
"failed VigenereCipher:\n\texpected: % q\n\t actual: % q",
|
||||
expected,
|
||||
actual,
|
||||
)
|
||||
}
|
||||
key = "vig"
|
||||
input = "OPKWWECIYOPKWIM"
|
||||
input = strings.ToUpper(strings.Replace(input, " ", "", -1))
|
||||
key = strings.ToUpper(strings.Replace(key, " ", "", -1))
|
||||
expected = "THEBOYHASTHEBAG"
|
||||
actual = VigenereCipher(input, key, true)
|
||||
if expected != actual {
|
||||
t.Errorf(
|
||||
"failed VigenereCipher:\n\texpected: % q\n\t actual: % q",
|
||||
expected,
|
||||
actual,
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user