zoukankan      html  css  js  c++  java
  • Python AES加密,解密(ECB、PKCS7Padding、输出 base64)

    # -*- coding=utf8 -*-
    
    import base64
    from Crypto.Cipher import AES
    
    
    def add_to_16(text):
        """ 密码填充 (位数不足时需要填充) """
        length = 16
        count = len(text)
        if count % length != 0:
            add = length - (count % length)
        else:
            add = 0
        text = text + ("" * add)
        return text
    
    
    def get_secret_key(secret):
        """ 密码截取 长度16位 """
        # secret = hashlib.md5(secret_key).hexdigest()
        # secret = base64.b64encode(secret_key)
        key_len = len(secret)
        if key_len == 16:
            return secret
        elif key_len > 16:
            return secret[-16:]
        elif key_len < 16:
            return add_to_16(secret)
    
    
    def encrypt(text, secret):
        """
        AES|ECB|PKCS7Padding|base64(output)
        :param text: 明文
        :param secret: 密码
        :return: 密文
        """
        bs = AES.block_size
        # PKCS7Padding data
        pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs)
        secret = get_secret_key(secret)
        cipher = AES.new(secret, AES.MODE_ECB)
        ret = cipher.encrypt(pad(text))
        return base64.b64encode(ret)
    
    
    def decrypt(text, secret):
        """
        AES|ECB|PKCS7Padding|base64(output)
        :param text: 密文
        :param secret: 密码
        :return: 明文
        """
        text = base64.b64decode(text)
        secret = get_secret_key(secret)
        cipher = AES.new(secret, AES.MODE_ECB)
        res = cipher.decrypt(text)
        # unpad res with PKCS7Padding
        unpad = lambda s: s[0:-ord(s[-1])]
        return unpad(res)
    
    
    if __name__ == "__main__":
        data = "ni hao"
        password = "aesrsasec"  # 16, 24, 32位长的密码
        sk = encrypt(data, password)
        print sk
        print decrypt(sk, password)
    
    
  • 相关阅读:
    win安装Theano
    Photoshop
    Sublime Text与LaTeX的结合
    Python开源库的bug
    Pillow库的学习和使用
    对OpenSSL心脏出血漏洞的试验
    Scrapy的学习和使用
    FreeImage库的学习和使用
    gdal库的学习和使用
    VirtualBox安装Debian
  • 原文地址:https://www.cnblogs.com/guohewei/p/14945305.html
Copyright © 2011-2022 走看看