BUUCTF [AFCTF2018]MyOwnCBC
题目给的CBC:
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto.Random import random
from Crypto.Util.number import long_to_bytes
def MyOwnCBC(key, plain):
if len(key)!=32:
return "error!"
cipher_txt = b""
cipher_arr = []
cipher = AES.new(key, AES.MODE_ECB, "")
plain = [plain[i:i+32] for i in range(0, len(plain), 32)]
print (plain)
cipher_arr.append(cipher.encrypt(plain[0]))
cipher_txt += cipher_arr[0]
for i in range(1, len(plain)):
cipher = AES.new(cipher_arr[i-1], AES.MODE_ECB, "")
cipher_arr.append(cipher.encrypt(plain[i]))
cipher_txt += cipher_arr[i]
return cipher_txt
key = random.getrandbits(256)
key = long_to_bytes(key)
s = ""
with open("flag.txt","r") as f:
s = f.read()
f.close()
with open("flag_cipher","wb") as f:
f.write(MyOwnCBC(key, s))
f.close()
主要是这里的 AES.new(cipher_arr[i-1], AES.MODE_ECB, "")
要注意到IV向量被置为空 然后每次的key都是前一次的cipher
所以直接逆着求解
1.由cpher[0:32]得到初始key
2.然后同样的分组 从1~end每次new一个AES后decrypt即可
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
from Crypto.Cipher import AES
from Crypto.Random import random
from Crypto.Util.number import long_to_bytes
def decode(key,cipher):
plain_txt = b""
cipher = [cipher[i:i+32] for i in range(0, len(cipher), 32)]
plain_txt += cipher[0]
for i in range(1,len(cipher)):
plain = AES.new(key,AES.MODE_ECB)
plain_txt += plain.decrypt(cipher[i])
key = cipher[i]
return plain_txt
if __name__ == '__main__':
with open(r'.\flag_cipher','rb') as f:
cipher = f.read()
key = cipher[0:32]
print(decode(key,cipher))