summaryrefslogtreecommitdiffstats
path: root/lib/brute.go
diff options
context:
space:
mode:
authorrsiddharth <s@ricketyspace.net>2020-08-29 20:00:53 -0400
committerrsiddharth <s@ricketyspace.net>2020-08-29 20:00:53 -0400
commit3b0fb163cbac08a36b01f186b72e2a9cee4b7a2d (patch)
tree5c33a9744c675edb87e29e771b90ed2dfc9a2779 /lib/brute.go
parented26b39e82cee901c785c13e3d1b669fbb502e14 (diff)
challenge: do challenge 3
* challenge/c03.go: Implement challenge 3 * cryptopals.go (main): Add handling to run challenge 3 * lib/brute.go (XORCrackSingleKey): New function. * lib/hex.go (HexStrToAsciiStr, ByteToHexStr): New functions. * lib/str.go (FillStr): New function.
Diffstat (limited to 'lib/brute.go')
-rw-r--r--lib/brute.go56
1 files changed, 56 insertions, 0 deletions
diff --git a/lib/brute.go b/lib/brute.go
new file mode 100644
index 0000000..54be06b
--- /dev/null
+++ b/lib/brute.go
@@ -0,0 +1,56 @@
+// Copyright © 2020 rsiddharth <s@ricketyspace.net>
+// SPDX-License-Identifier: ISC
+
+package lib
+
+// Average Word Length (English).
+const awl float64 = 4.7
+
+// 'hs' must be a hex encoded string.
+func XORCrackSingleKey(hs string) (byte, string, float64) {
+ l := len(hs) / 2
+
+ var k byte = 0
+ var ds string = ""
+ var scr float64 = 100.0
+
+ i := byte(0)
+ for i < 255 {
+ ks := FillStr(ByteToHexStr(i), l)
+ xs := FixedXOR(hs, ks)
+ as := HexStrToAsciiStr(xs)
+
+ s := phraseScore(as)
+ if s < scr {
+ k = i
+ ds = as
+ scr = s
+ }
+ i += 1
+ }
+ return k, ds, scr
+}
+
+func phraseScore(phrase string) float64 {
+ pl := len(phrase)
+
+ // Expected number of words.
+ ew := float64(pl) / awl
+
+ // Number of words in phrase.
+ ws := 0.0
+
+ for i := 0; i < pl; i++ {
+ if phrase[i] == ' ' {
+ ws += 1.0
+ }
+ }
+ ws += 1.0
+
+ // Compute score.
+ score := 1.0 - (ws / ew)
+ if score < 0 {
+ score *= -1
+ }
+ return score
+}