python实现rsa算法
时间: 2023-07-26 13:03:33 浏览: 54
RSA是一种非对称加密算法,常用于数据加密和数字签名。下面是一个简单的 Python 示例代码,演示了如何使用 RSA 加密和解密字符串。需要安装PyCrypto库。
```python
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().export_key()
# 加密字符串
plain_text = b"Hello, RSA!"
rsakey = RSA.import_key(public_key)
cipher = PKCS1_OAEP.new(rsakey)
cipher_text = cipher.encrypt(plain_text)
print("Cipher text:", cipher_text)
# 解密字符串
rsakey = RSA.import_key(private_key)
cipher = PKCS1_OAEP.new(rsakey)
decrypted_text = cipher.decrypt(cipher_text)
print("Decrypted text:", decrypted_text.decode('utf-8'))
```
需要注意的是,PyCrypto已经停止更新,请使用PyCryptodome或cryptography库进行加密操作。