使用数字形式公钥进行RSA加密:Python示例与代码讲解
字符串形式的公钥能加密吗?答案是:不能!
在之前的回答中,我们错误地使用了字符串形式的公钥进行加密。实际上,公钥加密需要使用数字形式的公钥。
使用数字形式公钥进行RSA加密的正确方法
以下是使用 Python 和 Crypto 库进行 RSA 加密的正确代码示例:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 生成 RSA 密钥对
key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey()
# 使用公钥加密
def rsa_encrypt(plaintext, public_key):
cipher_rsa = PKCS1_OAEP.new(public_key)
ciphertext = cipher_rsa.encrypt(plaintext)
return ciphertext
# 使用私钥解密
def rsa_decrypt(ciphertext, private_key):
rsa_key = RSA.import_key(private_key)
cipher_rsa = PKCS1_OAEP.new(rsa_key)
plaintext = cipher_rsa.decrypt(ciphertext)
return plaintext
# 明文
message = b'Hello, World!'
# 使用公钥加密
encrypted_message = rsa_encrypt(message, public_key)
print('Encrypted Message:', encrypted_message)
# 使用私钥解密
decrypted_message = rsa_decrypt(encrypted_message, private_key)
print('Decrypted Message:', decrypted_message.decode('utf-8'))
代码讲解:
- 导入必要的库: 首先,我们需要导入
Crypto.PublicKey和Crypto.Cipher库,它们分别用于处理 RSA 密钥和执行加密操作。 - 生成 RSA 密钥对: 使用
RSA.generate(2048)生成一个 2048 位的 RSA 密钥对。 - 导出私钥和公钥: 分别使用
key.export_key()和key.publickey()将私钥和公钥导出为可用的格式。 - 定义加密函数
rsa_encrypt:- 使用
PKCS1_OAEP.new(public_key)创建一个PKCS1_OAEP密码对象,该对象使用公钥进行加密。 - 使用
cipher_rsa.encrypt(plaintext)加密明文并返回密文。
- 使用
- 定义解密函数
rsa_decrypt:- 使用
RSA.import_key(private_key)从导出的私钥字符串导入 RSA 密钥对象。 - 使用
PKCS1_OAEP.new(rsa_key)创建一个PKCS1_OAEP密码对象,该对象使用私钥进行解密。 - 使用
cipher_rsa.decrypt(ciphertext)解密密文并返回明文。
- 使用
- 加密和解密消息:
- 定义要加密的明文消息。
- 使用
rsa_encrypt函数加密消息。 - 使用
rsa_decrypt函数解密消息。
总结:
RSA 加密需要使用数字形式的公钥,而不是字符串形式。使用 Crypto 库可以方便地在 Python 中进行 RSA 加密和解密操作,确保数据的安全传输。
原文地址: https://www.cveoy.top/t/topic/cfxU 著作权归作者所有。请勿转载和采集!