#!/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()
ecb模式下的aes加密,cipher = AES.new(key, AES.MODE_ECB, "")这样写在python3里不支持,ecb模式里没有初始化向量IV。分析加密过程,就是把上一次的密文作为下一次加密的密钥,初始密钥为密文前32位,故解密只需把过程逆过来就行:
import random
from Crypto.Cipher import AES
from gmpy2 import *
from Crypto.Util.number import *
cipher = open('C://Users//Public//Desktop//flag_cipher', 'rb').read()
key = cipher[0:32]
def MyOwnCBC(key, cipher):
cipher = [cipher[i:i + 32] for i in range(0, len(cipher), 32)]
flag = b''
for i in range(1, len(cipher)):
dic_cipher = AES.new(key, AES.MODE_ECB)
flag += dic_cipher.decrypt(cipher[i])
key = cipher[i]
return flag
print(MyOwnCBC(key, cipher))
#afctf{Don't_be_fooled_by_yourself}