문제풀이/cryptopals

[파이썬] cryptopals 1-3 문제풀이 (Single-byte XOR cipher)

코엽 2016. 1. 15. 00:39

주소

http://cryptopals.com/sets/1/challenges/3/

문제

Single-byte XOR cipher

The hex encoded string:

1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736

... has been XOR'd against a single character. Find the key, decrypt the message.

You can do this by hand. But don't: write code to do it for you.

How? Devise some method for "scoring" a piece of English plaintext. Character frequency is a good metric. Evaluate each output and choose the one with the best score.

해석

xor키값을 브루트포싱 하는것 같습니다.
브루트포싱하는 문장들 중에 알파벳이 몇퍼센트나 있는지 문장들에 점수를 매겨서 점수가 가장 높은 문장을 찾으랍니다.

get_score() 함수가 문장의 점수를 리턴해 줍니다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def get_score(line):
    score = 0
    for letter in line:
        if 'a'<=letter<='z' or 'A'<=letter<='Z':
            score += 1
    if score:
        return float(score) / len(line)
    return 0
 
string = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
result = ''
for i in range(0,256):
    line = ''
    for letter in string.decode('hex'):
        line += chr(ord(letter)^i)
    if get_score(result) < get_score(line):
        result = line
print result, get_score(result)
cs

결과