python ASE加密
from Cryptodome.Cipher import AES from Cryptodome import Random from binascii import b2a_hex ,a2b_hex def aes_encrypt(data,key=''): # 要加密的明文 #data = '1' # 密钥key 长度必须为16(AES-128),24(AES-192),或32(AES-256)Bytes 长度. # 目前AES-128足够用 #key = b'this22222222225555555555' key = key.encode("utf8") while len(key) % 16 != 0: key += b' ' # 生成长度等于AES块大小的不可重复的密钥向量 iv = Random.new().read(AES.block_size) # 使用key和iv初始化AES对象, 使用MODE_CFB模式 mycipher = AES.new(key, AES.MODE_CFB, iv) # 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数 # 将iv(密钥向量)加到加密的密文开头,一起输出 ciphertext = iv + mycipher.encrypt(data.encode("utf8")) # print('加密后数据为:', b2a_hex(ciphertext)) #字符串 --> 十六进制 return b2a_hex(ciphertext).decode()# decode() bytes转字符串 def aes_decrypt(ciphertext='',key=''): key = key.encode("utf8") while len(key) % 16 != 0: key += b' ' ciphertext=a2b_hex(ciphertext)#十六进制 -> 字符串 # 解密的话要用key和iv生成新的AES对象,前16位是iv mydecrypt = AES.new(key, AES.MODE_CFB,ciphertext[:16]) # 使用新生成的AES对象,将加密的密文解密 decrypttext = mydecrypt.decrypt(ciphertext[16:]) # print('解密后数据为:', decrypttext.decode()) return decrypttext.decode() #测试 a= aes_encrypt(data='正常',key='abcd') b = aes_decrypt(ciphertext=a ,key='abcd') print(a,b)