cryptopals

https://cryptopals.com/
Log | Files | Refs

ctr_bitflipping_attacks.py (823B)


      1 import re
      2 from Crypto.Cipher import AES
      3 from Crypto import Random
      4 from Crypto.Util import Counter
      5 
      6 key = Random.new().read(AES.block_size)
      7 
      8 def encrypt(plaintext):
      9     return AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(plaintext)
     10 
     11 def decrypt_and_parse(cipher):
     12     return ";admin=true;" in encrypt(cipher)
     13 
     14 def encryption_oracle(m):
     15     return encrypt("comment1=cooking%20MCs;userdata=" + re.sub("[;|=]", '', m) + ";comment2=%20like%20a%20pound%20of%20bacon")
     16 
     17 plaintext = "hello-admin-true"
     18 ciphertext = list(encryption_oracle(plaintext))
     19 
     20 ciphertext[(2 * AES.block_size) + 5] = chr(ord('-') ^ ord(';') ^ ord(ciphertext[(2 * AES.block_size) + 5]))
     21 ciphertext[(2 * AES.block_size) + 11] = chr(ord('-') ^ ord('=') ^ ord(ciphertext[(2 * AES.block_size) + 11]))
     22 
     23 print decrypt_and_parse(''.join(ciphertext))