from Crypto.PublicKey import RSA # 处理秘钥对的.# 生成密钥对# 65537 是rsa的一个标志.# 10001 十六进制的数字 => 65537
key = RSA.generate(2048) # 默认的这个key是私钥# # print(key.exportKey()) # 默认的输出格式是PEM格式withopen("private.pem", mode="wb") as f:
f.write(key.exportKey())
withopen("public.pem", mode="wb") as f:
f.write(key.public_key().export_key())
'''
generate参数说明
"""Create a new RSA key pair.
The algorithm closely follows NIST `FIPS 186-4`_ in its
sections B.3.1 and B.3.3. The modulus is the product of
two non-strong probable primes.
Each prime passes a suitable number of Miller-Rabin tests
with random bases and a single Lucas test.
Args:
bits (integer):
Key length, orsize (in bits) of the RSA modulus.
It must be at least 1024, but **2048 is recommended.**
The FIPS standard only defines 1024, 2048 and 3072.
randfunc (callable):
Function that returns random bytes.
The defaultis :func:`Crypto.Random.get_random_bytes`.
e (integer):
Public RSA exponent. It must be an odd positive integer.
It is typically a small number with very few ones in its
binary representation.
The FIPS standard requires the public exponent to be
at least 65537 (the default).
Returns: an RSA key object (:class:`RsaKey`, withprivate key).
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
"""
'''
2、加密、解密
# 加密
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import base64
ming = "请关注我的博客园".encode("utf-8")
# 需要公钥# 从文件里读出来公钥
f = open("public.pem", mode="rb")
pub_key = RSA.import_key(f.read())
rsa = PKCS1_v1_5.new(key=pub_key)
result = rsa.encrypt(ming)
print(base64.b64encode(result).decode())
#解密
s = "ipFrgSNB+aPDO+wJb0GEdpy6rMRQxCsoiomb75z582KVjFL0l4iqd54BjAvEvmRHrGBVbWWMGvnwauLM/mdAgobxtvpLnY4EbdBCX4mUk1mlpAyjgDI76aNzRYA5Ii/2DrnygctUzgqomWYfNpa6d7GueYHbPfBmYl20sKs1pG41smHp/PP+DMUO3EwQKw4+wmoLQY21v3LB1ZkvjtcLGL3/LaTET8bDZiy67JcQjTc5r+aK/9gAW6YEFVB7L+kvUBU0cCpJ2evMLbUSmIzRXec4e48Dh1Ada0kqyyZxnq70o+b3Rd4bK2qQtuRxhDCRIcFY6mGu741hXtLTgV9VxA=="
mi_bs = base64.b64decode(s)
f = open("private.pem", mode="rb")
pri_key = RSA.import_key(f.read())
rsa = PKCS1_v1_5.new(key=pri_key)
ming_bs = rsa.decrypt(mi_bs, None) # 第二个参数固定空的
print(ming_bs.decode("utf-8"))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构