在Python中使用RSA算法对文件进行加密和解密的实例代码
发布时间:2023-12-24 10:03:47
RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,它使用两个密钥(公钥和私钥)进行加密和解密。公钥用于加密数据,而私钥用于解密数据。在Python中,使用cryptography库可以方便地实现RSA算法的加密和解密。
以下是一个示例代码,演示了如何使用RSA算法对文件进行加密和解密。
1. 首先,确保已安装cryptography库,可以使用以下命令安装它:
pip install cryptography
2. 导入所需的模块和类:
from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import padding
3. 生成RSA密钥对。密钥对一般只需要生成一次,并保存在文件中以供后续使用:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
# 将私钥保存到文件中
with open("private_key.pem", "wb") as f:
f.write(private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
))
# 将公钥保存到文件中
with open("public_key.pem", "wb") as f:
f.write(public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
))
4. 加密文件:
def encrypt_file(file_path, public_key_path, output_path):
with open(file_path, "rb") as f:
data = f.read()
with open(public_key_path, "rb") as f:
public_key = serialization.load_pem_public_key(
f.read(),
backend=default_backend()
)
encrypted_data = public_key.encrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
with open(output_path, "wb") as f:
f.write(encrypted_data)
5. 解密文件:
def decrypt_file(file_path, private_key_path, output_path):
with open(file_path, "rb") as f:
encrypted_data = f.read()
with open(private_key_path, "rb") as f:
private_key = serialization.load_pem_private_key(
f.read(),
password=None,
backend=default_backend()
)
decrypted_data = private_key.decrypt(
encrypted_data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
with open(output_path, "wb") as f:
f.write(decrypted_data)
通过调用encrypt_file和decrypt_file函数,可以对文件进行加密和解密操作。
使用例子:
# 生成RSA密钥对并保存到文件中
generate_rsa_keys()
# 加密文件
encrypt_file("plain.txt", "public_key.pem", "encrypted.txt")
# 解密文件
decrypt_file("encrypted.txt", "private_key.pem", "decrypted.txt")
以上代码中的plain.txt是待加密的文件,public_key.pem是公钥文件,encrypted.txt是加密后的文件,private_key.pem是私钥文件,decrypted.txt是解密后的文件。
需要注意的是,在实际使用中,需要确保私钥的保密性,只有持有私钥的人可以解密加密后的文件。
