+/Cryptopals
git clone https://git.julia.blue/+/Cryptopals
6d42c13
master
1from Crypto .Cipher import AES 2from Crypto .Util .Padding import pad 3import random 4 5encryptECB = lambda s ,k :AES .new (k ,AES .MODE_ECB ).encrypt (s ) 6 7fixedXor = lambda a ,b :bytes ([a [i ]^ b [i ]for i in range (len (a ))]) 8 9 10def encryptCBC (s ,k ,iv ): 11s = pad (s ,16 ) 12cipher = [iv ] 13plain = [s [i :i + 16 ]for i in range (0 ,len (s ),16 )] 14for p in plain : 15cipher .append (encryptECB (fixedXor (p ,cipher [- 1 ]),k )) 16result = [] 17for i in cipher [1 :]: 18result += i 19return result 20 21 22def detectCipher (s ): 23temp = [s [i :i + 16 ]for i in range (0 ,len (s ),16 )] 24for i in temp : 25if temp .count (i )> 1 : 26return "ECB" 27return "CBC" 28 29 30key = random .randbytes (16 ) 31data = b"this is a test to see how well encryption works" * 20 32enc = "" 33 34data = ( 35random .randbytes (random .randint (5 ,10 )) 36+ data 37+ random .randbytes (random .randint (5 ,10 )) 38) 39 40if random .random ()< 0.5 : 41enc = encryptECB (pad (data ,16 ),key ) 42"Actual: ECB" ) 43else : 44enc = encryptCBC (data ,key ,random .randbytes (16 )) 45"Actual: CBC" ) 46 47"Guess:" ,detectCipher (enc ))