因为参加coursera课程cryptography I课程接触到AES算法,在涉及具体编程实现时,记录下来以便以后查找。
AES.MODE_CBC:
CBC key: 140b41b22a29beb4061bda66b6747e14
CBC Ciphertext 1:
4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee\
2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81
PyCrypto 中 AES算法 密钥、原文、密文都是bit值,因此对于hex格式的数据,需要用decode('hex')解码:
from Crypto.Cipher import AES
key = '140b41b22a29beb4061bda66b6747e14'
ctext = '4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81'
iv = '4ca00ff4c898d61e1edbf1800618fb28'
cipher = AES.new(key.decode('hex') , AES.MODE_CBC , iv.decode('hex') )
text = cipher.decrypt(ctext.decode('hex'))
print text[16:] # only need msg except iv
AES.MODE_CTR:
CTR key: 36f18357be4dbd77f050515c73fcf9f2
CTR Ciphertext 2:
770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa\
0e311bde9d4e01726d3184c34451
from Crypto.Cipher import AES
from Crypto.Util import Counter
key = '36f18357be4dbd77f050515c73fcf9f2'.decode('hex')
ct = 'e46218c0a53cbeca695ae45faa8952aa\
0e311bde9d4e01726d3184c34451'.decode('hex')
iv = '770b80259ec33beb2561358a9f2dc617'
ctr = Counter.new(128,initial_value = int(iv,16))
cipher = AES.new(key , AES.MODE_CTR , counter=ctr)
pt = cipher.decrypt(ct)
print pt
对于CTR模式,使用PyCrypto中的Crypto.Util.Counter进行counter值的初始化,要注意,此时解密不需要将该counter值加入解密密文,这是CTR和CBC加密原理不同造成的。当然,对于更多有关counter的内容,请访问PyCrypto的文档查找,类似的问题在Stack Overflow上也可以看到
[1]PyCrypto problem using AES+CTR
[2]Include nonce and block count in PyCrypto AES MODE_CTR