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
This commit is contained in:
Derek McQuay 2016-03-12 23:06:24 -08:00
parent 08a2266d5f
commit 757c1483b4
2 changed files with 94 additions and 2 deletions

17
main.go
View File

@ -106,7 +106,7 @@ func main() {
} }
var vig = &cobra.Command{ var vig = &cobra.Command{
Use: "vig mode -c [cipher] -k [key] -i [input]", Use: "vig",
Short: "vignenere cipher", Short: "vignenere cipher",
Long: `perform vigenere cipher`, Long: `perform vigenere cipher`,
Run: func(cmd *cobra.Command, args []string) { 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{ var random = &cobra.Command{
Use: "random", Use: "random",
Short: "randomly transpose", Short: "randomly transpose",
@ -236,7 +249,7 @@ func main() {
) )
var rootCmd = &cobra.Command{Use: "app"} var rootCmd = &cobra.Command{Use: "app"}
rootCmd.AddCommand(sub, aes, trans, vig) rootCmd.AddCommand(sub, aes, trans, vig, guess)
trans.AddCommand(random, railfence, split) trans.AddCommand(random, railfence, split)
rootCmd.Execute() rootCmd.Execute()
} }

79
psyfer/guess.go Normal file
View File

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