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)
    
    
  • 相关阅读:
    checkbox的问题整理
    通过阅读ASP.NET MVC5 框架解密 路由的一点心得
    用JS实现避免重复加载相同js文件
    如何给一个网站设置子网站
    Linux环境下Python的安装过程
    linux下更新Python版本并修改默认版本
    【引用】如何读技术类书籍
    专业收藏_资格证书
    ASP.NET单元测试配置文件
    面试收集
  • 原文地址:https://www.cnblogs.com/guohewei/p/14945305.html
Copyright © 2011-2022 走看看