python实现openssl
EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), NULL, pass, passlen, 1, key, iv);
并实现AES 256 CBC加解密.
python
# encoding:utf-8
import base64
from Crypto.Cipher import AES
from Crypto import Random
from hashlib import md5
def EVP_BytesToKey(password, salt, key_len, iv_len):
"""
实现openssl
EVP_BytesToKey(EVP_aes_256_cbc(), EVP_md5(), NULL, pass, passlen, 1, key, iv);
"""
pass_salt = (password + salt).encode(encoding='utf-8') #传给hashlib.md5前要先转成bytes
dtot = md5(pass_salt).digest() # 返回bytes,不要转成十六进制字符串
d = [ dtot ]
while len(dtot) != (key_len + iv_len):
d.append(md5(d[-1] + pass_salt).digest()) # 在一维列表中,下标为-1表示该元素为列表的最后一项
dtot += d[-1]
return dtot[:key_len], dtot[key_len:key_len+iv_len]
def encryt(string, key, iv):
"""
加密文本
:param string: 待加密文本
:param key: 密钥
:param iv: 偏移量/初始向量
:return: 密文
"""
cipher = AES.new(key, AES.MODE_CBC, iv)
x = AES.block_size - (len(string) % AES.block_size)
# 长度不整除16时,需要进行补全, 比如少了3个,就填充3个3
if x != 0:
string = string + chr(x)*x
msg = cipher.encrypt(string.encode('utf-8'))
return msg
def decrypt(en_str, key, iv):
"""
解密文本
:param en_str: 待解密文本
:param key: 密钥
:param iv: 偏移量/初始向量
:return: 解密后的文本
"""
cipher = AES.new(key, AES.MODE_CBC, iv)
msg = cipher.decrypt(en_str)
padding_len = msg[len(msg)-1]
return msg[0:-padding_len]
if __name__ == '__main__':
with open('res.json', 'r') as fp:
content = fp.readlines() #list
text_16str = ''.join(content) # list to str
text_byte = bytes.fromhex(text_16str) #get bytes
password = "%^%xxxxxx"
key, iv = EVP_BytesToKey(password, '', 32, 16)
#out = encryt('world', key, iv)
print(out.hex())
out = decrypt(text_byte, key, iv)
print(out.decode('utf-8'))
作者:帅得不敢出门 csdn原创谢绝转载收录