# 导入所需的库
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii
# 生成密钥对
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()
# 将密钥写入文件(可选)
with open("private.pem", "wb") as f:
f.write(private_key)
with open("public.pem", "wb") as f:
f.write(public_key)
# 加载公钥和私钥
public_key = RSA.import_key(open("public.pem").read())
private_key = RSA.import_key(open("private.pem").read())
# 创建加密对象
cipher_rsa_pub = PKCS1_OAEP.new(public_key)
cipher_rsa_priv = PKCS1_OAEP.new(private_key)
# 要加密的数据
data = "Hello, this is a secret message.".encode('utf-8')
# 使用公钥加密数据
encrypted_data = cipher_rsa_pub.encrypt(data)
print("Encrypted:", binascii.hexlify(encrypted_data))
# 使用私钥解密数据
decrypted_data = cipher_rsa_priv.decrypt(encrypted_data)
print("Decrypted:", decrypted_data.decode('utf-8'))
RSA.generate(2048)
生成一个 2048 位的 RSA 密钥对,然后将私钥和公钥分别导出为字符串。PKCS1_OAEP
算法创建加密对象,分别用于公钥加密和私钥解密。这个示例展示了如何使用 Python 的 pycryptodome
库来进行 RSA 加密和解密操作。
上一篇:python for range
下一篇:python 量化交易
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站