如何用Python编程语言来实现RSA公钥加密和私钥解密的步骤?
时间: 2025-02-14 08:21:26 浏览: 72
在Python中,你可以使用`cryptography`库来实现RSA(Rivest-Shamir-Adleman)公钥加密和私钥解密的过程。以下是基本步骤:
**安装 cryptography 库 (如果未安装):**
```bash
pip install cryptography
```
**导入必要的模块:**
```python
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
from cryptography.hazmat.backends import default_backend
```
**生成 RSA 密钥对:**
```python
private_key = RSAPrivateKey.generate(2048, backend=default_backend())
public_key = private_key.public_key()
```
这里的 `2048` 表示密钥长度,可以根据需要调整。
**加密数据(使用公钥):**
```python
def encrypt(message, public_key):
message_bytes = message.encode('utf-8')
ciphertext = public_key.encrypt(
message_bytes,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return ciphertext
encrypted_message = encrypt("Hello, RSA!", public_key)
```
**解密数据(使用私钥):**
```python
def decrypt(ciphertext, private_key):
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
return plaintext.decode('utf-8')
decrypted_message = decrypt(encrypted_message, private_key)
print(f"Decrypted message: {decrypted_message}")
```
**相关问题--:**
1. 使用 RSA 加密时为什么要用 `padding.OAEP`?
2. 如果丢失了私钥,如何从公钥恢复信息?
3. 这种加密方式的安全性如何?有哪些潜在的风险?
阅读全文
相关推荐


















