如何在Python中使用RSA公钥解密密文?
用Python实现公钥解密(非标准用法)
首先明确:公钥解密违背非对称加密的核心设计(公钥加密、私钥解密),这会导致加密内容完全公开,任何持有公钥的人都能解密,极度不安全,仅为满足特定需求提供方案。
用PyCryptodome实现
PyCryptodome默认限制了公钥的解密操作,但可以通过手动构造密钥对象绕开这个限制——本质是把公钥的e(公钥指数)当作私钥的d(私钥指数)来使用,因为RSA加解密都是模幂运算,只是使用的指数不同。
示例代码:
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 # 加载公钥(假设公钥存储在public.pem文件中) with open("public.pem", "r") as f: public_key = RSA.import_key(f.read()) # 构造一个"伪私钥":用公钥的e作为私钥的d,n保持不变 fake_private_key = RSA.construct( (public_key.n, public_key.e) ) # 要解密的密文(注意:密文必须是用私钥加密后的结果,否则无法用公钥解密) ciphertext = b"..." # 替换为实际密文 # 使用PKCS1_v1_5填充方式解密 cipher = PKCS1_v1_5.new(fake_private_key) # 解密时需要提供一个随机函数(PKCS1_v1_5要求,这里可以用None) plaintext = cipher.decrypt(ciphertext, None) print(plaintext.decode())
其他可选库
1. rsa库(第三方轻量库)
rsa库允许直接使用公钥参数进行解密操作,无需构造伪私钥:
import rsa # 加载公钥 with open("public.pem", "r") as f: public_key = rsa.PublicKey.load_pkcs1(f.read().encode()) # 解密密文(密文是私钥加密的结果) ciphertext = b"..." # 替换为实际密文 plaintext = rsa.decrypt(ciphertext, public_key) print(plaintext.decode())
2. cryptography库
cryptography库同样可以通过底层的模幂运算实现:
from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization from cryptography.hazmat.backends import default_backend # 加载公钥 with open("public.pem", "rb") as f: public_key = serialization.load_pem_public_key( f.read(), backend=default_backend() ) # 获取公钥的n和e n = public_key.public_numbers().n e = public_key.public_numbers().e # 密文是bytes类型,先转换为整数 ciphertext_int = int.from_bytes(ciphertext, byteorder="big") # 执行模幂运算:plaintext_int = ciphertext_int^e mod n plaintext_int = pow(ciphertext_int, e, n) # 转换回bytes plaintext = plaintext_int.to_bytes((plaintext_int.bit_length() + 7) // 8, byteorder="big") print(plaintext.decode())
再次提醒:这种操作完全破坏了非对称加密的安全性,仅在客户强制要求的场景下使用,务必提前告知客户风险。
内容的提问来源于stack exchange,提问作者razieh babaee
相关产品推荐
相关产品推荐

