每天进步一点点-加密与解密

发布时间 2023-04-04 16:30:24作者: Alive_2020
import config
from Utils.ParseXmlUtil import check_string, check_open_ability_sign
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64

request_body = {'orderId': '836211012110000410412', 'orderStatus': '20102', 'operation': 'P205022601', 'originalCode': 'EC1029'}

# 平铺字符串及url编码按指定格式排列
ret = check_string(request_body, '/order/status/up')
print(ret)

# # 签名:私钥加密
# hash_obj = SHA256.new(ret.encode("utf-8"))
# PRIVATE_KEY = config.CURRENT_CONFIG["PRIVATE_KEY"]
# pri_rsa_key = RSA.importKey(PRIVATE_KEY)
# signer = Signature_pkcs1_v1_5.new(pri_rsa_key).sign(hash_obj)
# signature = base64.b64encode(signer)
# print(signature)
# signature_string = signature.decode()  # 请求带来的签名串
# print(signature)
# # 公钥延签
# PUBLIC_KEY = config.CURRENT_CONFIG["PUBLIC_KEY"]
# ssss = check_open_ability_sign(ret, signature)
# print(ssss)


# 加密解密:公钥加密,私钥解密
# 1. 生成 private key and pulic key
# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)
# 秘钥对的生成
private_pem = rsa.exportKey()
print(private_pem)
public_pem = rsa.publickey().exportKey()
print(public_pem)

# 2. 加密
PUBLIC_KEY = config.CURRENT_CONFIG["PUBLIC_KEY"]
rsakey = RSA.importKey(PUBLIC_KEY)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(ret))
print(cipher_text)

# 3. 解密还原加密字符串
PRIVATE_KEY = config.CURRENT_CONFIG["PRIVATE_KEY"]
cipher = Cipher_pkcs1_v1_5.new(PRIVATE_KEY)
text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)