美文网首页
Python 密码学:AES/CBC/PKCS5Padding

Python 密码学:AES/CBC/PKCS5Padding

作者: Anoyi | 来源:发表于2021-06-07 11:23 被阅读0次

    ※ 安装依赖

    pip3 install pycryptodome
    

    ※ Python 源码

    from Crypto.Cipher import AES
    from base64 import b64decode, b64encode
    from config import conf
    
    BLOCK_SIZE = AES.block_size
    
    
    class AESCipher:
    
        def __init__(self, key, iv):
            self.key = key
            self.iv = iv
    
        @staticmethod
        def pad(text):
            return text + (BLOCK_SIZE - len(text.encode()) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(text.encode()) % BLOCK_SIZE)
    
        @staticmethod
        def un_pad(text):
            return text[:-ord(text[len(text) - 1:])]
    
        def encrypt(self, text):
            """
            加密
            """
            text = self.pad(text).encode()
            cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
            encrypted_text = cipher.encrypt(text)
            return b64encode(encrypted_text).decode('utf-8')
    
        def decrypt(self, encrypted_text):
            """
            解密
            """
            encrypted_text = b64decode(encrypted_text)
            cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
            decrypted_text = cipher.decrypt(encrypted_text)
            return self.un_pad(decrypted_text).decode('utf-8')
    

    相关文章

      网友评论

          本文标题:Python 密码学:AES/CBC/PKCS5Padding

          本文链接:https://www.haomeiwen.com/subject/ekdxeltx.html