func Test4(t *testing.T) { ciphertexts := make([][]byte, len(input4)) for i, input := range input4 { // Decode ciphertext ciphertext, err := encoding.DecodeHex([]byte(input)) if err != nil { t.Error("Decoding", input, "failed") } ciphertexts[i] = ciphertext } // Attempt to find ciphertext most likely xor'd with a key of the same byte ciphertext, closestByte := xorbyte.FindCiphertext(ciphertexts, xorbyte.EnglishScorer) // Construct key from most likely byte key := make([]byte, len(ciphertext)) for i := 0; i < len(key); i++ { key[i] = closestByte } // Decrypt ciphertext plaintext, _ := bits.Xor(ciphertext, key) // output plaintext if string(plaintext) != output4 { t.Error(string(plaintext), "!=", output4) } }
func bytesAndScores(ciphertext []byte, scorer Scorer) chan byteAndScore { ch := make(chan byteAndScore) go func() { key := make([]byte, len(ciphertext)) // Test each possible value of byte for byteValue := 0; byteValue < 256; byteValue++ { // Fill key with byteValue for i := 0; i < len(key); i++ { key[i] = byte(byteValue) } // Xor ciphertext with key (p == (p xor k) xor k) plaintext, _ := bits.Xor(ciphertext, key) // Frequency count ch <- byteAndScore{ byte(byteValue), scorer.Score(plaintext), } } close(ch) }() return ch }
func Test2(t *testing.T) { raw1, err := encoding.DecodeHex([]byte(input2a)) if err != nil { t.Error("Decoding", input2a, "failed") } raw2, err := encoding.DecodeHex([]byte(input2b)) if err != nil { t.Error("Decoding", input2b, "failed") } result, err := bits.Xor(raw1, raw2) if err != nil { } resultEncoded := encoding.EncodeHex(result) if string(resultEncoded) != output2 { t.Error(string(resultEncoded), "!=", output2) } }
func Test3(t *testing.T) { // Decode ciphertext ciphertext, err := encoding.DecodeHex([]byte(input3)) if err != nil { t.Error("Decoding", input3, "failed") } // Attempt to find byte most likely xor'd with ciphertext closestByte := xorbyte.FindByte(ciphertext, xorbyte.EnglishScorer) // Construct key from most likely byte key := make([]byte, len(ciphertext)) for i := 0; i < len(key); i++ { key[i] = closestByte } // Decrypt ciphertext plaintext, _ := bits.Xor(ciphertext, key) // output plaintext if string(plaintext) != output3 { t.Error("Incorrect key chosen:", string(closestByte), string(plaintext)) } }