借鉴 https://www.cnblogs.com/sammy1989/p/9583965.html
最近请求一个系统,对方要求加密。折腾了一天,使用pycryptodome库,最终代码如下:
#!/usr/bin/env python3
import json
import base64
from Crypto.PublicKey import RSA
from Crypto.Hash import MD5
from Crypto.Signature import pkcs1_15
from Crypto.Cipher import PKCS1_OAEP
class encrypt_rsa():
def __init__(self, data):
self.message = data.encode()
self.public_key = RSA.import_key(open('encrypt_public.pem').read())
# 分段加密
def encrypt(self):
try:
cipher\_rsa = PKCS1\_OAEP.new(self.public\_key)
res = \[\]
for i in range(0, len(self.message), 117):
print(i)
enc\_tmp = cipher\_rsa.encrypt(self.message\[i:i+117\])
res.append(enc\_tmp)
print(res)
cipher\_text = b''.join(res)
except Exception as e:
print(e)
else:
return base64.b64encode(cipher\_text).decode()
class sign_rsa():
def __init__(self, data):
self.message = data.encode()
self.private_key = RSA.import_key(open('sign_private.pem').read())
# 签名
def sign(self):
h = MD5.new(self.message)
signature = base64.b64encode(pkcs1\_15.new(self.private\_key).sign(h))
return signature.decode()
if __name__ == '__main__':
payload = {'issueCode': issueCode, 'hostGroup': hostGroup,
'title': title, 'Content': content,
'level': level, 'sourceSystem': sourceSystem}
payload\_sign = sign\_rsa(payload).sign()
#print(payload\_sign)
payload\_encrypt = encrypt\_rsa(payload).encrypt()
#print(str(payload\_encrypt))
payload\_res = {'sign': payload\_sign, 'params': payload\_encrypt}
print(payload\_res)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章