python aes加密

分享一个python的aes加密代码

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。---百度百科

本科的时候弄过DES加密算法加密计算机文件,而DES加密算法现在基本处于被废弃的状态,所以现在想试试更高级一点的。

DES加密算法可发展为3DES加密算法,后来又被升级为AES加密算法,加长了密钥长度,也就增加了暴力破解的难度。

本次使用Python进行AES的加密解密

import hashlib
from Crypto.Cipher import AES
import base64

class prpcrypt():
    def __init__(self,key):
        self.key = key  # 因为在python3中AES传入参数的参数类型存在问题,需要更换为 bytearray , 所以使用encode编码格式将其转为字节格式(linux系统可不用指定编码)
        IV = 16 * '\x00'
        self.iv=IV.encode("utf-8")
        self.mode = AES.MODE_CBC
        self.BS = AES.block_size
        self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
        self.unpad = lambda s: s[0:-ord(s[-1])]

    # 加密
    def encrypt(self, text):
        text = self.pad(text).encode("utf-8")
        cryptor = AES.new(self.key, self.mode, self.iv)
        # 目前AES-128 足够目前使用(CBC加密)
        ciphertext = cryptor.encrypt(text)
        # base64加密
        return base64.b64encode(bytes(ciphertext))

    # 解密
    def decrypt(self, text):
        # base64解密
        text = base64.b64decode(text)
        cryptor = AES.new(self.key, self.mode, self.iv)
        # CBC解密
        plain_text = cryptor.decrypt(text)
        # 去掉补足的空格用strip() 去掉
        return self.unpad(bytes.decode(plain_text).rstrip('\0'))    # 解密字节???


def gen_binsha(data):
    shavalue = hashlib.sha256()
    shavalue.update(data)
    return shavalue.digest()

if __name__ == '__main__':
    key='78f40cecf89'
    key=gen_binsha(key.encode('utf-8'))
    pc = prpcrypt(key=key)  # 初始化密钥 和 iv

    text='qwerqwerkkk12345'
    e = pc.encrypt(text)  # 加密
    d = pc.decrypt(e)  # 解密
    print("加密:%s" % e)
    print("解密:%s"% d)
    print("长度:%s"% len(d))

https://baobao.baidu.com/question/a62f1eed8bcb0e2c9fdba453357df03b.html

posted on 2020-12-22 15:21  零零幺  阅读(590)  评论(0编辑  收藏  举报