AES加密解密

AES加密解密:

python3.6首先需安装pycryptodome模块

不使用函数:

from Crypto.Cipher import AES
import base64

def add_to_16(s):
    while len(s)%16 != 0:
        s += '\0'
    return str.encode(s)

key = '1234567890123456'# 密钥长度必须为16、24或32位,分别对应AES-128、AES-192和AES-256
text = 'hello,world'
aes = AES.new(str.encode(key),AES.MODE_ECB)# 初始化加密器,本例采用ECB加密模式
encrypt = str(base64.encodebytes(aes.encrypt(add_to_16(text))),encoding='utf-8').replace('\n','')#加密
decrypt = str(aes.decrypt(base64.decodebytes(bytes(encrypt,encoding='utf-8'))).rstrip(b'\0').decode('utf8'))#解密

print(encrypt)
print(decrypt)

运行结果:

使用函数:

from Crypto.Cipher import AES
import base64

class testAES:
    def __init__(self,key):
        self.key = key
        self.aes = AES.new(str.encode(key), AES.MODE_ECB)

    def add_to_16(self,s):
        while len(s) % 16 != 0:
            s += '\0'
        return str.encode(s)
#加密方法
    def Encrypt(self,text):
        encryption = str(base64.encodebytes(self.aes.encrypt(self.add_to_16(text))), encoding='utf-8').replace('\n', '')
        return encryption
#解密方法
    def Decrypt(self,text):
        decryption = str(self.aes.decrypt(base64.decodebytes(bytes(text,encoding='utf-8'))).rstrip(b'\0').decode('utf8'))
        return decryption

if __name__ == '__main__':
    key = '1234567890123456'#初始化秘钥为16位
    passwd = 'hello,python'
    encrypt_text = testAES(key).Encrypt(passwd)
    decrypt_text = testAES(key).Decrypt(encrypt_text)
    print(encrypt_text)
    print(decrypt_text)

运行结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值