写一个对小文件加密的RSA算法
时间: 2024-04-06 12:35:08 浏览: 13
以下是一个使用Python实现的对小文件加密的RSA算法的示例代码:
```python
import os
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()
# 将密钥保存到文件
with open('private_key.pem', 'wb') as f:
f.write(private_key)
with open('public_key.pem', 'wb') as f:
f.write(public_key)
# 加载公钥和私钥
private_key = RSA.import_key(open('private_key.pem').read())
public_key = RSA.import_key(open('public_key.pem').read())
# 加密文件
def encrypt_file(input_file, output_file):
with open(input_file, 'rb') as f:
message = f.read()
cipher = PKCS1_OAEP.new(public_key)
ciphertext = cipher.encrypt(message)
with open(output_file, 'wb') as f:
f.write(ciphertext)
# 解密文件
def decrypt_file(input_file, output_file):
with open(input_file, 'rb') as f:
ciphertext = f.read()
cipher = PKCS1_OAEP.new(private_key)
message = cipher.decrypt(ciphertext)
with open(output_file, 'wb') as f:
f.write(message)
# 测试加密和解密
input_file = 'test.txt'
encrypted_file = 'encrypted_test.txt'
decrypted_file = 'decrypted_test.txt'
with open(input_file, 'wb') as f:
f.write(os.urandom(1024)) # 随机生成1024字节的测试文件
encrypt_file(input_file, encrypted_file)
decrypt_file(encrypted_file, decrypted_file)
```
在上面的代码中,我们首先使用`Crypto.PublicKey.RSA`模块中的`generate`方法生成了一个2048位的RSA密钥对,并将公钥和私钥保存到了文件中。然后,我们定义了`encrypt_file`和`decrypt_file`两个函数分别用于加密和解密文件,其中加密使用公钥进行加密,解密使用私钥进行解密。最后,我们使用`os.urandom`方法生成了一个1024字节的随机测试文件,并对其进行加密和解密的测试。
需要注意的是,上面的代码只适用于小文件的加密和解密,如果需要对大文件进行加密和解密,需要对其进行分块处理。