implemented vigenere cipher and basic test

This commit is contained in:
Derek McQuay 2016-03-12 21:04:59 -08:00
parent 4de75d2080
commit 64c7d7617a
3 changed files with 89 additions and 11 deletions

34
main.go
View File

@ -5,6 +5,7 @@ import (
"log"
"math/rand"
"os"
"strings"
"time"
"s.mcquay.me/dm/psyfer/psyfer"
@ -109,7 +110,15 @@ func main() {
Short: "vignenere cipher",
Long: `perform vigenere cipher`,
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 || key == "" {
fmt.Println("missing input, see -h (--help) for more info")
os.Exit(1)
}
for _, arg := range args {
arg = strings.ToUpper(strings.Replace(arg, " ", "", -1))
key = strings.ToUpper(strings.Replace(key, " ", "", -1))
fmt.Printf("%v\n", psyfer.VigenereCipher(arg, key, decrypt))
}
},
}
@ -165,15 +174,6 @@ func main() {
},
}
var crack = &cobra.Command{
Use: "times [# times] [string to echo]",
Short: "Echo anything to the screen more times",
Long: `echo things multiple times back to the user by providing a count and a string.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("crack")
},
}
//transpose flags
split.Flags().BoolVarP(
&decrypt,
@ -219,10 +219,24 @@ func main() {
false,
"decrypt",
)
//virenere flags
vig.Flags().StringVarP(
&key,
"key",
"k",
"",
"encryption key string",
)
vig.Flags().BoolVarP(
&decrypt,
"decrypt",
"d",
false,
"decrypt",
)
var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(sub, aes, trans, vig)
trans.AddCommand(random, railfence, split)
vig.AddCommand(crack)
rootCmd.Execute()
}

29
psyfer/vigenere.go Normal file
View File

@ -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
}

35
psyfer/vigenere_test.go Normal file
View File

@ -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,
)
}
}