欢迎访问宙启技术站
智能推送

使用Python的Crypto.Cipher.PKCS1_OAEP进行公钥加密和私钥解密

发布时间:2023-12-11 01:44:05

Python中的Crypto.Cipher.PKCS1_OAEP模块可用于使用公钥加密和私钥解密数据。以下是一个使用示例:

首先,安装所需的库:

pip install pycryptodome

然后,导入必要的模块:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

接下来,生成公钥和私钥:

# 使用RSA算法生成一个新的密钥对
key = RSA.generate(2048)

# 获取公钥和私钥
public_key = key.publickey()
private_key = key.exportKey()

现在我们有了公钥和私钥,我们可以使用公钥加密数据,私钥解密数据:

# 创建一个PKCS1_OAEP对象并使用公钥进行加密
cipher = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b"Hello, World!")

# 创建一个PKCS1_OAEP对象并使用私钥进行解密
cipher = PKCS1_OAEP.new(key)
decrypted_data = cipher.decrypt(encrypted_data)

完整的示例代码如下:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# 使用RSA算法生成一个新的密钥对
key = RSA.generate(2048)

# 获取公钥和私钥
public_key = key.publickey()
private_key = key.exportKey()

# 创建一个PKCS1_OAEP对象并使用公钥进行加密
cipher = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b"Hello, World!")

# 创建一个PKCS1_OAEP对象并使用私钥进行解密
cipher = PKCS1_OAEP.new(key)
decrypted_data = cipher.decrypt(encrypted_data)

print("Original Data:", b"Hello, World!")
print("Encrypted Data:", encrypted_data)
print("Decrypted Data:", decrypted_data)

运行上述代码将输出以下结果:

Original Data: b'Hello, World!'
Encrypted Data: b'\xebY\xf3J\x8d}\xca4\x8a\xfa\x83u\x83-\x0e.\x8e,\x04v\xb6y\xcf\x85(\xaf\x1f\xaf?\xd7c\xf9\...'
Decrypted Data: b'Hello, World!'

如上所示,我们首先生成了一个新的RSA密钥对,然后使用公钥加密了原始数据,并使用私钥解密了加密后的数据,最后确保解密后的数据与原始数据匹配。