最近项目要做充币内容,其实是充币中的监控,不过我连监控也没有做.监控在我之前同事已经写好了.我只是定时查数据库内容,发现有新数据把它拿出来上传给java.但是双方数据交互用rsa与aes加密.我python学了多久,网上找点例子.果然找到了,就是导包时遇到问题.其它的包都还好,只有个crypto一直导入后不能引入编译器一直报错.运行时也包找不到Crypto模块.我搞了好久终于弄好,上次写过解决Crypto导包问题了
python版本不兼容很烦人,python2的不少语法到python3完全是错误的.网上很多python文章都是py2的,我的环境是python3,一开始很不习惯.加密时我找了例子主要是AEsCipher.py与RSACipher.py两个文件
AEsCipher.py
import base64
import json
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
class AESCipher:
"""
AES加密、解密工具类
"""
def __init__(self, key):
self.key = key
# 这里直接用key充当iv
self.iv = key
def encrypt(self, raw):
"""
加密方法
:param raw: 需要加密的密文 str
:return: base64编码的密文 str
"""
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return base64.b64encode(cipher.encrypt(self.__pad(raw).encode())).decode()
def decrypt(self, enc):
"""
解密方法
:param enc: base64编码的密文 str
:return: 解密后的明文 str
"""
cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
return self.__unpad(cipher.decrypt(base64.b64decode(enc)).decode())
def __pad(self, text):
# 填充方法,加密内容必须为16字节的倍数
text_length = len(text)
amount_to_pad = AES.block_size - (text_length % AES.block_size)
if amount_to_pad == 0:
amount_to_pad = AES.block_size
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
def __unpad(self