用Python,调用程序库中的RSA算法,实现公钥和私钥的生成及加解密。
时间: 2024-10-17 14:15:45 浏览: 17
在Python中,你可以使用`cryptography`库来实现RSA算法,它包含丰富的加密工具,包括公钥和私钥的生成以及数据的加解密。以下是基本步骤:
1. 安装必要的库:
```bash
pip install cryptography
```
2. 导入所需模块并生成密钥对:
```python
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# 生成一个2048位的RSA密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
```
3. 将密钥保存到文件:
```python
# 私钥序列化并保存为PEM格式
with open('private.pem', 'wb') as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
))
# 公钥序列化并保存为PEM格式
with open('public.pem', 'wb') as f:
f.write(public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
```
4. 加密和解密数据:
```python
def encrypt(message, public_key):
ciphertext = public_key.encrypt(message.encode(), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
return ciphertext
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()
# 示例:加密和解密消息
message = "Hello, RSA!"
encrypted_msg = encrypt(message, public_key)
print("Encrypted message:", encrypted_msg)
decrypted_msg = decrypt(encrypted_msg, private_key)
print("Decrypted message:", decrypted_msg)
```
阅读全文