+/Cryptopals
git clone https://git.julia.blue/+/Cryptopals
6d42c13
master
1import binascii 2 3b2hex = lambda b :binascii .hexlify (b ) 4 5hex2b = lambda s :bytes ([int (s [i :i + 2 ],16 )for i in range (0 ,len (s ),2 )]) 6 7singleCharXor = lambda s ,c :bytes ([s [i ]^ c for i in range (len (s ))]) 8 9printable = lambda s :not (False in [31 < i < 127 or i == 10 or i == 13 for i in s ]) 10 11 12def xorCipher (s ): 13# fmt: off 14englishLetters = [ 158.167 ,1.492 ,2.782 ,4.253 ,12.702 ,2.228 ,2.015 ,6.094 ,6.966 , 160.153 ,0.772 ,4.025 ,2.406 ,6.749 ,7.507 ,1.929 ,0.095 ,5.987 , 176.327 ,9.056 ,2.758 ,0.978 ,2.360 ,0.150 ,1.975 ,0.074 , 18 ]# fmt: on 19space = 18.31 20b = hex2b (s ) 21bestMatch = "" 22bestScore = 0 23key = 0 24for i in range (255 ): 25currentStr = binascii .unhexlify (b2hex (singleCharXor (b ,i ))) 26if printable (currentStr ): 27score = 0 28temp = currentStr .lower () 29for c in temp : 30if 96 < c < 123 : 31score += englishLetters [c - 97 ] 32elif c == 32 : 33score += space 34if score > bestScore : 35bestScore = score 36bestMatch = currentStr 37key = i 38return bestMatch ,bestScore ,key 39 40 41f = open ("input_data/4.txt" ) 42lines = f .read ().splitlines () 43f .close () 44best = "" 45bestScore = 0 46 47for i in lines : 48temp = xorCipher (i ) 49if temp [1 ]> bestScore : 50best = temp [0 ] 51bestScore = temp [1 ] 52 53best )