-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc3-4_test.go
74 lines (59 loc) · 1.44 KB
/
c3-4_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"bufio"
"encoding/hex"
"fmt"
"os"
"testing"
)
func TestSingleByteXOR(t *testing.T) {
hexStr := "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
cipherText, err := decodeTestHex(t, hexStr)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
gotStr, gotKey := singleByteXOR(cipherText)
t.Logf("Key: %c", gotKey)
t.Logf("Decoded string: %s", gotStr)
}
// Challenge 4 of Set 1.
func TestSingleByteXORFile(t *testing.T) {
f, err := os.Open("./files/1_4.txt")
if err != nil {
t.Fatalf("opening file: %s", err)
}
defer f.Close()
var (
s = bufio.NewScanner(f)
bestScore float64
plainText string
key byte
)
for s.Scan() {
cipherText, err := decodeTestHex(t, s.Text())
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
gotStr, gotKey := singleByteXOR(cipherText)
score := computeTextScore([]byte(gotStr))
if score > bestScore {
bestScore = score
plainText = gotStr
key = gotKey
}
}
if err := s.Err(); err != nil {
t.Fatalf("parsing file: %s", err)
}
t.Logf("Key: %c", key)
t.Logf("Decoded string: %s", plainText)
}
// decodeTestHex attempts to decode the provided hex string into a byte slice.
func decodeTestHex(t *testing.T, hexStr string) ([]byte, error) {
t.Helper()
decodedHex, err := hex.DecodeString(hexStr)
if err != nil {
return nil, fmt.Errorf("malformed hex string '%s': %s", hexStr, err)
}
return decodedHex, nil
}