好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python 爬虫进阶必备 | AES-CBC 的 Pyhon 实现要怎么写?给代码就完事了

终于可以光明正大的水一篇文章了。

还是老规矩,本文重要部分就是文章结尾的代码,路过的大佬不想听咸鱼唠嗑的直接划到结尾拿代码就好了,记得点赞,宝贝。

先讲讲为什么写这篇文章,就是昨天分析了某服务平台的加密数据分析,果不其然炸了不少小白读者,老夫甚是欣慰。

于是,在孤寂的深夜。

有读者找到我想问问关于 AES 加密的 Python 实现应该怎么写,听到这个需求我第一时间是拒绝的

对,就是这么真实,毕竟我是咸鱼,能 BB 绝对不会动手的

但是,毕竟读者爸爸都是磨人的小妖精,所以我屈服了。

之后我就打开了某个不可描述的网站开始找资源

果然,找到了不少关于 AES 加密的文章,不过看文章的日期基本是 2017-2019 的居多。

而且这里一定要提一句,Python 的  PyCrypto  已死,现在用 Python 实现加密常用的是 PyCryptodom

PyCryptodom 可以使用下面这句命令安装

 pip3 install pycryptodome  # pip3 install -i https://pypi.douban.com/simple pycryptodome   

然后不停使用 CV 大法调试网上的代码,不得不吐槽一句,C*DN 网站真的垃圾,十篇文章有九篇文章雷同。

先看下关于 pycryptodome 的用法

 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA256 from Crypto.Cipher import AES  

如果有尝试过用 Python 实现的朋友一定遇到过下面的报错

 TypeError: Object type <class 'str'> cannot be passed to C code  

这个报错的解决办法非常简单,但是昨晚没有找到原因的时候真的和噩梦一样

最后在 stackoverflow 找到了处理办法,大家可以去围观下

 https://stackoverflow.com/questions/50302827  

处理办法也很简单, encode 就行了

 obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CBC, 'This is an IV456'.encode("utf8"))  

解决了这个问题之后,之后就是通畅无阻了

这里直接给出 AES-CBC 两种输出的代码,以下代码的加解密结果与 http://tool.chacuo.net/cryptaes 相同。

AES-CBC  输出  Hash  的示例代码

 from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex   class PrpCrypt(object):     def __init__(self, key):         self.key = key.encode('utf-8')         self.mode = AES.MODE_CBC      # 加密函数,如果text不足16位就用空格补足为16位,     # 如果大于16当时不是16的倍数,那就补足为16的倍数。     def encrypt(self, text):         text = text.encode('utf-8')         cryptor = AES.new(self.key, self.mode, b'0123456789ABCDEF')         # 这里密钥key 长度必须为16(AES-128),         # 24(AES-192),或者32 (AES-256)Bytes 长度         # 目前AES-128 足够目前使用         length = 16         count = len(text)         if count < length:             add = (length - count)             # \0 backspace             # text = text + ('\0' * add)             text = text + ('\0' * add).encode('utf-8')         elif count > length:             add = (length - (count % length))             # text = text + ('\0' * add)             text = text + ('\0' * add).encode('utf-8')         self.ciphertext = cryptor.encrypt(text)         # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题         # 所以这里统一把加密后的字符串转化为16进制字符串         return b2a_hex(self.ciphertext)      # 解密后,去掉补足的空格用strip() 去掉     def decrypt(self, text):         cryptor = AES.new(self.key, self.mode, b'0123456789ABCDEF')         plain_text = cryptor.decrypt(a2b_hex(text))         # return plain_text.rstrip('\0')         return bytes.decode(plain_text).rstrip('\0')   if __name__ == '__main__':     pc = PrpCrypt('jo8j9wGw%6HbxfFn')  # 初始化密钥 key     e = pc.encrypt('{"code":200,"data":{"apts":[]},"message":"","success":true}')  # 加密     d = pc.decrypt("lXgLoJQ3MAUdzLX+ORj5/pJlkRAU423JfyUKVd5IwfCSxw6d1mHwBdHV9p3kmKCYwNRmAIEWeb/9ypLCqTZ1FA==")  # 解密     print("加密:", e)     print("解密:", d)  

AES-CBC  输出  Base64  的示例代码

 from Crypto.Cipher import AES from binascii import b2a_hex, a2b_hex import base64  class PrpCrypt(object):     def __init__(self, key):         self.key = key.encode('utf-8')         self.mode = AES.MODE_CBC      # 加密函数,如果text不足16位就用空格补足为16位,     # 如果大于16当时不是16的倍数,那就补足为16的倍数。     def encrypt(self, text):         text = text.encode('utf-8')         cryptor = AES.new(self.key, self.mode, b'0123456789ABCDEF')         # 这里密钥key 长度必须为16(AES-128),         # 24(AES-192),或者32 (AES-256)Bytes 长度         # 目前AES-128 足够目前使用         length = 16         count = len(text)         if count < length:             add = (length - count)             # \0 backspace             # text = text + ('\0' * add)             text = text + ('\0' * add).encode('utf-8')         elif count > length:             add = (length - (count % length))             # text = text + ('\0' * add)             text = text + ('\0' * add).encode('utf-8')         self.ciphertext = cryptor.encrypt(text)         return base64.b64encode(self.ciphertext).decode()      # 解密后,去掉补足的空格用strip() 去掉     def decrypt(self, text):         cryptor = AES.new(self.key, self.mode, b'0123456789ABCDEF')         decryptByts = base64.b64decode(text)         plain_text = cryptor.decrypt(decryptByts)         return bytes.decode(plain_text).rstrip('\0')   if __name__ == '__main__':     pc = PrpCrypt('jo8j9wGw%6HbxfFn')  # 初始化密钥 key     e = pc.encrypt('{"code":200,"data":{"apts":[]},"message":"","success":true}')  # 加密     d = pc.decrypt("lXgLoJQ3MAUdzLX+ORj5/pJlkRAU423JfyUKVd5IwfCSxw6d1mHwBdHV9p3kmKCYwNRmAIEWeb/9ypLCqTZ1FA==")  # 解密     print("加密:", e)     print("解密:", d)  

这里只给出了代码,关于 AES 的原理讲解之类的信息在夜幕的系列课程已经讲过了,这里不再赘述。

今天的内容就到这里,咱们下次再会~

Love & Share 

[ 完 ]

查看更多关于Python 爬虫进阶必备 | AES-CBC 的 Pyhon 实现要怎么写?给代码就完事了的详细内容...

  阅读:36次