python实现AES加解密

AES加解密理论去百度吧,直接上代码,python实现,拿来就能用

from Crypto.Cipher import AES
import base64
import string
import random

class AESCrypto(object):

    """AES加密算法"""

    def __init__(self):

        self.aes_mode = AES.MODE_ECB
        self.aes_bs = 16
        self.AES_PAD = lambda s: s + (self.aes_bs - len(s) % self.aes_bs) * chr(self.aes_bs - len(s) % self.aes_bs)
        self.AES_UN_PAD = lambda s: s[0:-s[-1]]

    def aes_decryption(self, data, key):
        """
        aes解密
        解密后,将补足的空格用strip() 去掉
        :param data: 接收到的密文数据集合
        :param key: 服务端返回的随机生成的AESKey,二进制形式
        :return: aes解密后的明文数据
        """
        generator = AES.new(key, self.aes_mode)  # ECB模式无需向量iv
        data += (len(data) % 4) * '='
        decrypt_bytes = base64.b64decode(data)
        result = generator.decrypt(decrypt_bytes)
        result = self
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Python实现AES加密解密算法程序的示例代码: ```python import base64 from Crypto.Cipher import AES # 定义加密函数 def aes_encrypt(key, data): # 将密钥和数据分别进行base64编码 key = base64.b64encode(key.encode('utf-8')).decode('utf-8') data = base64.b64encode(data.encode('utf-8')).decode('utf-8') # 使用CBC模式加密 cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, b'0000000000000000') # 加密数据 encrypted_data = cipher.encrypt(data.encode('utf-8')) # 将加密后的数据进行base64编码 encrypted_data = base64.b64encode(encrypted_data).decode('utf-8') return encrypted_data # 定义解密函数 def aes_decrypt(key, encrypted_data): # 将密钥进行base64编码 key = base64.b64encode(key.encode('utf-8')).decode('utf-8') # 将加密后的数据进行base64解码 encrypted_data = base64.b64decode(encrypted_data) # 使用CBC模式解密 cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, b'0000000000000000') # 解密数据 decrypted_data = cipher.decrypt(encrypted_data).decode('utf-8') # 将解密后的数据进行base64解码 decrypted_data = base64.b64decode(decrypted_data).decode('utf-8') return decrypted_data # 测试加密解密函数 if __name__ == '__main__': key = '1234567890abcdef' # 密钥长度必须为16、24或32个字符 data = '这是一条测试数据' encrypted_data = aes_encrypt(key, data) print('加密后的数据:', encrypted_data) decrypted_data = aes_decrypt(key, encrypted_data) print('解密后的数据:', decrypted_data) ``` 需要注意的是,上述示例代码中使用的是AES加密算法中的CBC模式,密钥长度必须为16、24或32个字符。如果需要使用其他模式或密钥长度,需要根据具体情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值