700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python实现AES加密与解密

Python实现AES加密与解密

时间:2023-06-08 08:02:14

相关推荐

Python实现AES加密与解密

文章目录

前言一、AES是什么?二、运行过程安装库代码总结

前言

数据在对接过程中,一般不会简单的明文传输,而是会进行加密后传输。

这篇文章主要介绍了Python实现AES加密与解密方法,帮助大家更好的使用python加解密解密文件。


一、AES是什么?

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。AES有几个模式,其中CBC模式是公认的安全性最好的模式,被TLS所采用。

二、运行过程

安装库

pip3 install cryptopip3 install pycryptodomex

虚拟环境\Lib\site-packages,找到这个路径,下面有一个文件夹叫做crypto,将小写c改成大写C就ok了

代码如果跑不通,再pip3 install pycryptodome

代码

import Crypto.Cipher.AESimport Crypto.Randomimport base64import binasciiclass Cipher_AES:cipher = getattr(Crypto.Cipher, "AES")pad = {"default": lambda x, y: x + (y - len(x) % y) * " ".encode("utf-8"),"PKCS5Padding": lambda x, y: x + (y - len(x) % y) * chr(y - len(x) % y).encode("utf-8")}unpad = {"default": lambda x: x.rstrip(),"PKCS5Padding": lambda x: x[:-ord(x[-1])]}encode = {"base64": base64.encodebytes,"hex": binascii.b2a_hex}decode = {"base64": base64.decodebytes,"hex": binascii.a2b_hex}def __init__(self, key=None, iv=None, cipher_method=None, pad_method="default", code_method=None):self.__key = key if key else "abcdefgh12345678" # 密钥(长度必须为16、24、32)self.__iv = iv if iv else Crypto.Random.new().read(Cipher_AES.cipher.block_size) # 向量(长度与密钥一致,ECB模式不需要)self.__cipher_method = cipher_method.upper() if cipher_method and isinstance(cipher_method,str) else "MODE_ECB" # 加密方式,["MODE_ECB"|"MODE_CBC"|"MODE_CFB"]等self.__pad_method = pad_method # 填充方式,解决 Java 问题选用"PKCS5Padding"self.__code_method = code_method # 编码方式,目前只有"base64"、"hex"两种if self.__cipher_method == "MODE_CBC":self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_CBC,self.__iv.encode("utf-8"))else:self.__cipher = Cipher_AES.cipher.new(self.__key.encode("utf-8"), Cipher_AES.cipher.MODE_ECB)def __getitem__(self, item):def get3value(item):return item.start, item.stop, item.steptype_, method, _ = get3value(item)dict_ = getattr(Cipher_AES, type_)return dict_[method] if method in dict_ else dict_["default"]def encrypt(self, text):cipher_text = b"".join([self.__cipher.encrypt(i) for i in self.text_verify(text.encode("utf-8"))])encode_func = Cipher_AES.encode.get(self.__code_method)if encode_func:cipher_text = encode_func(cipher_text)return cipher_text.decode("utf-8").rstrip()def decrypt(self, cipher_text):cipher_text = cipher_text.encode("utf-8")decode_func = Cipher_AES.decode.get(self.__code_method)if decode_func:cipher_text = decode_func(cipher_text)return self.pad_or_unpad("unpad", self.__cipher.decrypt(cipher_text).decode("utf-8"))def text_verify(self, text):while len(text) > len(self.__key):text_slice = text[:len(self.__key)]text = text[len(self.__key):]yield text_sliceelse:if len(text) == len(self.__key):yield textelse:yield self.pad_or_unpad("pad", text)def pad_or_unpad(self, type_, contents):lambda_func = self[type_: self.__pad_method]return lambda_func(contents, len(self.__key)) if type_ == "pad" else lambda_func(contents)if __name__ == '__main__':key = "abcdefgh12345678"iv = "12345678abcdefgh"text = "123456" # 待加密的字符串cipher_method = "MODE_CBC"pad_method = "PKCS5Padding"code_method = "base64"# 加密cipher_text = Cipher_AES(key, iv, cipher_method, pad_method, code_method).encrypt(text)print(cipher_text)# 解密text = Cipher_AES(key, iv, cipher_method, pad_method, code_method).decrypt(cipher_text)print(text)

总结

AES在数据传输过程中是一项很实用的技术,这也是我第一次在项目中接触到,希望对同学们有所帮助。

如果阅读本文对你有用,欢迎一键三连呀!!!

12月16日09:56:46

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。