用python实现rsa加密算法
时间: 2024-09-20 13:00:55 浏览: 92
在Python中,RSA是一种非对称加密算法,它由三个主要步骤组成:密钥生成、数据加密和数据解密。以下是简单的RSA加密算法实现:
```python
import math
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 密钥生成函数
def generate_rsa_keys(key_size=2048):
key = RSA.generate(key_size)
private_key = key.export_key()
public_key = key.publickey().export_key()
return private_key, public_key
# 加密函数(使用公钥)
def rsa_encrypt(message, public_key):
rsa_public_key = RSA.import_key(public_key)
cipher = PKCS1_OAEP.new(rsa_public_key)
encrypted_text = cipher.encrypt(message.encode())
return encrypted_text
# 解密函数(使用私钥)
def rsa_decrypt(encrypted_message, private_key):
rsa_private_key = RSA.import_key(private_key)
cipher = PKCS1_OAEP.new(rsa_private_key)
decrypted_text = cipher.decrypt(encrypted_message).decode()
return decrypted_text
# 示例
private_key, public_key = generate_rsa_keys()
message = "Hello, world!"
encrypted_text = rsa_encrypt(message, public_key)
print("Encrypted message:", encrypted_text)
decrypted_text = rsa_decrypt(encrypted_text, private_key)
print("Decrypted message:", decrypted_text)
```
阅读全文