aes-cbc一例

发布于:2024-06-10 ⋅ 阅读:(56) ⋅ 点赞:(0)
#!/usr/bin/python
from Crypto.Cipher import AES
import binascii
from Crypto.Util.number import bytes_to_long
from flag import flag
import random
import string
import os

def genkey(l):
    return random.getrandbits(l)

iv = flag.strip(b'flag{').strip(b'}')

key = ''.join([random.choice(string.ascii_letters+string.digits) for _ in xrange(16)])
LENGTH = len(key)
assert LENGTH == 16

hint = os.urandom(4) * 8
print(bytes_to_long(hint)^bytes_to_long(key))

msg = b'Welcome, ctfer. Dont try too hard, its no use. Have a good day!!'

def encrypto(message):
    aes = AES.new(key,AES.MODE_CBC,iv)
    return aes.encrypt(message)

print(binascii.hexlify(encrypto(msg))[-32:])

'''
99748265546679089946917295913637945222843938798184123305418691873367322323659
bc03f3ac4ff8064acbcfaf0b0bf2ba7b
'''

本质是倒推出初始向量iv

msg共64byte,分为4组,给出最后一组的密文。key可以求出。

#!/usr/bin/python
from Crypto.Cipher import AES
import binascii
from Crypto.Util.number import *
from Crypto.Util.strxor import strxor as xor


msg = b'Welcome, ctfer. Dont try too hard, its no use. Have a good day!!'

hint=99748265546679089946917295913637945222843938798184123305418691873367322323659
c=0xbc03f3ac4ff8064acbcfaf0b0bf2ba7b
key=(hint>>(16*8))^(hint&((1<<16*8)-1))


key=long_to_bytes(key)
byte_c=long_to_bytes(c)

for msg_i in range(3,-1,-1):
    aes = AES.new(key,AES.MODE_ECB)
    print(msg[msg_i*16:msg_i*16+16])
    byte_c=xor(aes.decrypt(byte_c),msg[msg_i*16:msg_i*16+16])
print(byte_c)