在接口自动化测试过程中,我们会涉及到登录的接口测试,但是登录中的参数是进行了一系列的加密操作的,一般比较常见的是AES加密算法,下面就对AES算法中的ECB和CBC两种模式做一下描述。
一、ECB
ECB比较简单,就是将固定长度的密钥,固定的明文进行加密,生成固定的密文。如果有两个相同的明文块,则它们的加密结果也是相同的。
def __init__(self, key):
self.key = key # 将密钥转换为字符型数据
self.mode = AES.MODE_ECB # 操作模式选择ECB
def encrypt(self, text):
"""加密函数"""
file_aes = AES.new(self.key, self.mode) # 创建AES加密对象
text = text.encode('utf-8') # 明文必须编码成字节流数据,即数据类型为bytes
while len(text) % 16 != 0: # 对字节型数据进行长度判断
text += b'\x00' # 如果字节型数据长度不是16倍整数就进行补充
en_text = file_aes.encrypt(text) # 明文进行加密,返回加密后的字节流数据
return str(base64.b64encode(en_text), encoding='utf-8') # 将加密后得到的字节流数据进行base64编码并再转换为unicode类型
key = '0kojdwjdlgdivm7d' # 可以作为随机加密key使用
key = key.encode('utf-8')
text = '00000000' # 需要加密的内容
aes_test = DoAES(key)
cipher_text = aes_test.encrypt(text)
上述运行结果:加密后:8eNCwWJj3S6S+FtL80Mrmg==
二、CBC
在CBC模式中,明文将按照8个字节一组进行分组得到D1D2…Dn(若数据不是8的整数倍,用指定的PADDING数据补位),每个数据块分别与前一个块的加密结果进行异或运算,然后再进行加密。最后将所有模块加密的密文拼接。CBC模式需要一个初始向量(IV)作为输入,所以如果IV设定不同的话,CBC加密每次都将产生不同的新值。
def encrypt(text, key, iv):
# AES加密
# key = hashlib.sha256(key.encode()).digest() # Derive a 256-bit key using SHA-256
cipher = AES.new(key.encode(), AES.MODE_CBC, iv.encode())
padded_text = pad(text.encode('utf-8'), AES.block_size)
ciphertext = cipher.encrypt(padded_text)
return base64.b64encode(ciphertext).decode('utf-8')
if __name__ == '__main__':
tokenKey = "rt7q18uo3jyva2qi"
password = "00000000"
iv = tokenKey # You can change this to a different IV if needed
encrypted_password = encrypt(password, tokenKey, iv)
print('加密后:', encrypted_password)
上述我将iv设置了固定的数值,这样在实际操作过程中安全性会降低,不建议。
上述运行结果为:加密后: OE8T9Zz/XD1JEQsnt9TOpw==
或者可以自己设置具体的偏移量
key = token_key.encode('utf-8')
iv = token_key.encode('utf-8')
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor()
# 假设你要加密的数据是"00000000!"
plaintext = "00000000".encode('utf-8')
# 进行填充
padder = padding.PKCS7(128).padder()
padded_data = padder.update(plaintext) + padder.finalize()
# 进行加密并输出Base64编码的结果
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
encrypted_result = b64encode(ciphertext).decode('utf-8')