如何使用XML格式RSA私钥在Python中实现加密数据解密?
实现方案
首先需要安装Python密码学工具库pycryptodome,安装命令如下:
pip install pycryptodome
完整实现代码
import base64 import xml.etree.ElementTree as ET from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 def base64url_decode(input_str: str) -> bytes: # 对齐C#的SafeBase64Url.DecodeBase64Url方法,处理base64url的填充补位 padding_need = 4 - len(input_str) % 4 if padding_need: input_str += "=" * padding_need return base64.urlsafe_b64decode(input_str) def decrypt_rsa_to_byte(data_decrypt: str, xml_private_key: str) -> bytes: # 解析XML格式RSA私钥,对齐C#的FromXmlString方法逻辑 root = ET.fromstring(xml_private_key) def get_bigint(tag: str) -> int: b64_val = root.find(tag).text.strip() return int.from_bytes(base64.b64decode(b64_val), byteorder='big') n = get_bigint('Modulus') e = get_bigint('Exponent') p = get_bigint('P') q = get_bigint('Q') d = get_bigint('D') # 构造RSA私钥对象 rsa_key = RSA.construct((n, e, d, p, q), consistency_check=True) # 解码base64url格式的密文 cipher_bytes = base64url_decode(data_decrypt) # 使用PKCS#1 v1.5填充解密,对齐C# Decrypt方法第二个参数为false的逻辑 cipher = PKCS1_v1_5.new(rsa_key) decrypted = cipher.decrypt(cipher_bytes, None) if decrypted is None: raise ValueError("解密失败,请检查密文或私钥是否有效") return decrypted
注意事项
- 实现完全对齐C#代码逻辑:支持XML格式RSA私钥解析、base64url密文解码、PKCS#1 v1.5填充解密,未使用OAEP填充。
- 若导入Crypto模块报错,确认安装的是
pycryptodome而非停止维护的旧版pycrypto库。 - 若实际XML私钥带命名空间,需要调整XML解析逻辑匹配标签路径。
内容的提问来源于stack exchange,提问作者a programer
相关产品推荐
相关产品推荐

