-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
53 lines (44 loc) · 935 Bytes
/
main.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
package main
import (
"encoding/hex"
"fmt"
"math"
"os"
"github.com/doc-smith/cryptopals/util/inp"
"github.com/doc-smith/cryptopals/util/lang"
)
func decrypt(dst, src []byte, key byte) {
for i := range src {
dst[i] = src[i] ^ key
}
}
func cloneBytes(src []byte) []byte {
dst := make([]byte, len(src))
copy(dst, src)
return dst
}
func crackSingleByteXor(ct []byte) []byte {
var bestPt []byte
var bestScore float64
pt := make([]byte, len(ct))
for key := 0; key <= math.MaxUint8; key++ {
decrypt(pt, ct, byte(key))
score := lang.ScoreEnglishText(pt)
if score > bestScore {
bestScore = score
bestPt = cloneBytes(pt)
}
}
return bestPt
}
func solve(hexCiphertext string) string {
ct, err := hex.DecodeString(hexCiphertext)
if err != nil {
panic("input is not a valid hex string")
}
return string(crackSingleByteXor(ct))
}
func main() {
inp := inp.ReadLine(os.Stdin)
fmt.Println(solve(inp))
}