compare of the CBC and CTR mode in PyCrypto AES

因为参加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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值