- CBC(Cipher Block Chaining,加密块链)模式
- 为了克服ECB模式的安全缺陷,设计了密码分组链接模式,它使得当同一个明文分组重复出现时产生不同的密文分组。对每个分组使用相同的密钥,加密函数的输入是当前的明文分组和前一个密文分组的异或。从效果上看,将明文分组序列的处理连接起来了。
- 为了产生第一个密文分组,要使用一个初始向量IV,IV必须被发送方和接收方都知道,为了做到最大程度的安全性,IV应该和密钥一样受到保护。
- CBC加密需要三个参数,原文、密钥、偏移量才可完成,安全性更高,更不容易主动攻击,安全性好于ECB,适合传输长度长的报文,是SSL、IPSec的标准。
- 这里,我采用NoPadding方式补齐原文的方式进行举例,具体代码如下:
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import hashlib
from crcmod import *
from binascii import *
import binascii
def PKCS_zero(text):
newbytes = '00'
if len(text) % 32:
add = 32 - (len(text) % 32)
add = add >> 1
else:
add = 0
text = text + newbytes * add
return text
def AES_CBC_encrypt(text,key,iv):
print("AES_CBC_encrypt")
print(" key :", key, type(key))
print(" iv :", iv, type(iv))
print("plain :", text, type(text))
mode = AES.MODE_CBC
text = PKCS_zero(text)
text = bytes.fromhex(text)
print("plain :", bytes.hex(text),type(text))
key = bytes.fromhex(key)
iv = bytes.fromhex(iv)
cryptos = AES.new(key, mode, iv)
cipher_text = bytes.hex(cryptos.encrypt(text))
print("cipher:", cipher_text, type(cipher_text))
print("************************************************")
return cipher_text
def AES_CBC_decrypt(text,key,iv):
print("AES_CBC_decrypt")
print(" key :", key, type(key))
print(" iv :", iv, type(iv))
print("plain :", text, type(text))
text = bytes.fromhex(text)
key = bytes.fromhex(key)
iv = bytes.fromhex(iv)
mode = AES.MODE_CBC
cryptos = AES.new(key, mode, iv)
plain_text = bytes.hex(cryptos.decrypt(text))
print("cipher:", plain_text, type(plain_text))
print("************************************************")
return plain_text
AES_CBC_encrypt
key : 387348525268714e4164586e53767041 <class 'str'>
iv : 387348525268714e4164586e53767041 <class 'str'>
plain : 74757961343933363861343862373436 <class 'str'>
plain : 74757961343933363861343862373436 <class 'str'>
cipher: 51506024af73925e15da8873afb08f9d <class 'str'>
************************************************
AES_CBC_decrypt
key : 387348525268714e4164586e53767041 <class 'str'>
iv : 387348525268714e4164586e53767041 <class 'str'>
plain : 51506024af73925e15da8873afb08f9d <class 'str'>
cipher: 74757961343933363861343862373436 <class 'str'>
************************************************