码迷,mamicode.com
首页 > 编程语言 > 详细

python aes 加密

时间:2021-05-24 02:53:36      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ref   method   aes   __name__   encrypt   encode   block   mod   targe   

文档: https://www.pycryptodome.org/en/latest/

# pip install pycryptodome

from Crypto.Cipher import AES
import base64


class Encrypt:
    def __init__(self, key, iv):
        self.key = key.encode(‘utf-8‘)
        self.iv = iv.encode(‘utf-8‘)

    # @staticmethod
    def pkcs7padding(self, text):
        """明文使用PKCS7填充 """
        bs = 16
        length = len(text)
        bytes_length = len(text.encode(‘utf-8‘))
        padding_size = length if (bytes_length == length) else bytes_length
        padding = bs - padding_size % bs
        padding_text = chr(padding) * padding
        self.coding = chr(padding)
        return text + padding_text

    def aes_encrypt(self, content):
        """ AES加密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        # 处理明文
        content_padding = self.pkcs7padding(content)
        # 加密
        encrypt_bytes = cipher.encrypt(content_padding.encode(‘utf-8‘))
        # 重新编码
        result = str(base64.b64encode(encrypt_bytes), encoding=‘utf-8‘)
        return result

    def aes_decrypt(self, content):
        """AES解密 """
        cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
        content = base64.b64decode(content)
        text = cipher.decrypt(content).decode(‘utf-8‘)
        return text.rstrip(self.coding)


if __name__ == ‘__main__‘:
    key = ‘ONxYDyNaCoyTzsp83JoQ3YYuMPHxk3j7‘
    iv = ‘yNaCoyTzsp83JoQ3‘
    a = Encrypt(key=key, iv=iv)
    text = "asdf234!@#sdfe"
    print("待加密:", text)
    e = a.aes_encrypt(text)
    print("加密:", e)
    d = a.aes_decrypt(e)
    print("解密:", d)

python aes 加密

标签:ref   method   aes   __name__   encrypt   encode   block   mod   targe   

原文地址:https://www.cnblogs.com/namejmj/p/14747491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!