From 757c1483b44bb06b5e04a263f78c5f5317067eb0 Mon Sep 17 00:00:00 2001 From: derek mcquay Date: Sat, 12 Mar 2016 23:06:24 -0800 Subject: [PATCH] got guess function to work for example from book it calculates (hard coded) the example from the book. Next step is making it take any string, calculate the character frequency and then do the same calculation and print out top answers --- main.go | 17 +++++++++-- psyfer/guess.go | 79 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 psyfer/guess.go diff --git a/main.go b/main.go index eeeb865..4a08bc9 100644 --- a/main.go +++ b/main.go @@ -106,7 +106,7 @@ func main() { } var vig = &cobra.Command{ - Use: "vig mode -c [cipher] -k [key] -i [input]", + Use: "vig", Short: "vignenere cipher", Long: `perform vigenere cipher`, Run: func(cmd *cobra.Command, args []string) { @@ -122,6 +122,19 @@ func main() { }, } + var guess = &cobra.Command{ + Use: "guess", + Short: "guess cipher", + Long: `will try to guess ceasar cipher`, + Run: func(cmd *cobra.Command, args []string) { + if len(args) < 1 { + fmt.Println("missing input, see -h (--help) for more info") + os.Exit(1) + } + psyfer.Guess() + }, + } + var random = &cobra.Command{ Use: "random", Short: "randomly transpose", @@ -236,7 +249,7 @@ func main() { ) var rootCmd = &cobra.Command{Use: "app"} - rootCmd.AddCommand(sub, aes, trans, vig) + rootCmd.AddCommand(sub, aes, trans, vig, guess) trans.AddCommand(random, railfence, split) rootCmd.Execute() } diff --git a/psyfer/guess.go b/psyfer/guess.go new file mode 100644 index 0000000..2eb1738 --- /dev/null +++ b/psyfer/guess.go @@ -0,0 +1,79 @@ +package psyfer + +import ( + "fmt" + "math" + "sort" +) + +var charFreq = []float64{ + 0.080, + 0.015, + 0.030, + 0.040, + 0.130, + 0.020, + 0.015, + 0.060, + 0.065, + 0.005, + 0.005, + 0.035, + 0.030, + 0.070, + 0.080, + 0.020, + 0.002, + 0.065, + 0.060, + 0.090, + 0.030, + 0.010, + 0.015, + 0.005, + 0.020, + 0.002, +} + +func pc(position, i int) int { + if position-i < 0 { + return 26 - (int(math.Abs(float64((position - i) % 26)))) + } else { + return int(math.Abs(float64((position - i) % 26))) + } +} + +func (p phi) String() string { + return fmt.Sprintf("%d %f\n", p.position, p.value) +} + +type phi struct { + position int + value float64 +} + +type allPhi []phi + +func (p allPhi) Len() int { return len(p) } +func (p allPhi) Swap(i, j int) { p[i], p[j] = p[j], p[i] } +func (p allPhi) Less(i, j int) bool { return p[i].value < p[j].value } + +func Guess() { + fmt.Println((6 - 7) % 26) + total := []phi{} + for i := 0; i < 26; i++ { + a := 0.0 + a += 0.1 * charFreq[pc(6, i)] + a += 0.1 * charFreq[pc(7, i)] + a += 0.1 * charFreq[pc(10, i)] + a += 0.3 * charFreq[pc(14, i)] + a += 0.2 * charFreq[pc(17, i)] + a += 0.1 * charFreq[pc(20, i)] + a += 0.1 * charFreq[pc(25, i)] + p := phi{i, a} + total = append(total, p) + } + fmt.Println(total) + sort.Sort(allPhi(total)) + fmt.Println(total) +}