借鑑 https://www.cnblogs.com/sammy1989/p/9583965.htmlhtml
最近請求一個系統,對方要求加密。折騰了一天,使用pycryptodome庫,最終代碼以下:python
#!/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)