用python语言实现rsa算法
时间: 2024-10-19 20:03:09 浏览: 25
python实现签名RSA算法工程文件
5星 · 资源好评率100%
RSA算法是一种非对称加密技术,Python中可以使用内置库`cryptography`来实现RSA。以下是简单的步骤:
1. **安装库**:
首先需要安装`cryptography`库,可以使用pip命令:
```
pip install cryptography
```
2. **生成密钥对**:
```python
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
def generate_keys(key_size=2048):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)
public_key = private_key.public_key()
return private_key, public_key
# 使用默认大小生成密钥对
private_key, public_key = generate_keys()
```
3. **加密**:
```python
def encrypt(plaintext, public_key):
ciphertext = public_key.encrypt(plaintext.encode(), padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
))
return ciphertext
plaintext = "Hello, RSA!"
ciphertext = encrypt(plaintext, public_key)
```
4. **解密**:
```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()
decrypted_text = decrypt(ciphertext, private_key)
```
5. **保存和加载密钥**:
```python
def save_key(key_path, key):
with open(key_path, 'wb') as f:
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption())
f.write(pem)
load_key_path = "path/to/private_key.pem"
save_key(load_key_path, private_key)
# 加载私钥
loaded_private_key = serialization.load_pem_private_key(open(load_key_path, 'rb').read(), password=None)
```
阅读全文