利用Python库Crypto.PublicKey.RSA实现RSA加密解密和数字签名
发布时间:2024-01-13 14:16:14
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,常用于数据的加密和数字签名。在Python中,可以使用Crypto库的PublicKey.RSA模块来实现RSA加密、解密和数字签名。
RSA加密和解密:
1. 首先,生成一对RSA密钥,包括公钥和私钥。
from Crypto.PublicKey import RSA # 生成一个RSA密钥对,长度为1024位 key = RSA.generate(1024) # 获取公钥和私钥 public_key = key.publickey() private_key = key.export_key()
2. 使用公钥对数据进行加密。
from Crypto.Cipher import PKCS1_OAEP # 使用公钥加密数据 cipher = PKCS1_OAEP.new(public_key) encrypted_data = cipher.encrypt(b"Hello World")
3. 使用私钥对加密后的数据进行解密。
# 使用私钥解密数据 cipher = PKCS1_OAEP.new(private_key) decrypted_data = cipher.decrypt(encrypted_data)
RSA数字签名:
1. 首先,使用私钥对原始数据进行签名。
from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 # 使用私钥对原始数据进行签名 hash_obj = SHA256.new(b"Hello World") signer = pkcs1_15.new(private_key) signature = signer.sign(hash_obj)
2. 使用公钥对签名后的数据进行验证。
# 使用公钥对签名进行验证
hash_obj = SHA256.new(b"Hello World")
verifier = pkcs1_15.new(public_key)
try:
verifier.verify(hash_obj, signature)
print("签名有效")
except:
print("签名无效")
下面是一个完整的使用例子,演示了RSA加密、解密和数字签名的过程:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# 生成一个RSA密钥对,长度为1024位
key = RSA.generate(1024)
# 获取公钥和私钥
public_key = key.publickey()
private_key = key.export_key()
# 使用公钥加密数据
cipher = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b"Hello World")
# 使用私钥解密数据
cipher = PKCS1_OAEP.new(private_key)
decrypted_data = cipher.decrypt(encrypted_data)
print("解密后的数据:", decrypted_data)
# 使用私钥对原始数据进行签名
hash_obj = SHA256.new(b"Hello World")
signer = pkcs1_15.new(private_key)
signature = signer.sign(hash_obj)
# 使用公钥对签名进行验证
hash_obj = SHA256.new(b"Hello World")
verifier = pkcs1_15.new(public_key)
try:
verifier.verify(hash_obj, signature)
print("签名有效")
except:
print("签名无效")
以上就是利用Python库Crypto.PublicKey.RSA实现RSA加密解密和数字签名的方法和使用例子。
