欢迎访问宙启技术站
智能推送

Python中使用RsaKey()对象进行文件加密和解密的示例代码

发布时间:2023-12-26 06:02:33

RSA(Rivest-Shamir-Adleman)是一种非对称加密算法,可以用于对文件进行加密和解密。Python中,可以使用RsaKey()对象来生成RSA密钥,然后使用该密钥对文件进行加密和解密。

以下是一个使用RsaKey()对象进行文件加密和解密的示例代码:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import os

def encrypt_file(file_path, public_key_path):
    # 读取公钥文件
    public_key = RSA.import_key(open(public_key_path).read())

    # 创建加密器
    cipher = PKCS1_OAEP.new(public_key)

    # 读取文件内容
    with open(file_path, 'rb') as file:
        plain_text = file.read()

    # 加密文件内容
    encrypted_text = cipher.encrypt(plain_text)

    # 写入加密后的文件内容
    encrypted_file = os.path.splitext(file_path)[0] + '.enc'
    with open(encrypted_file, 'wb') as file:
        file.write(encrypted_text)

    print('Encryption done. Encrypted file saved as:', encrypted_file)

def decrypt_file(encrypted_file_path, private_key_path):
    # 读取私钥文件
    private_key = RSA.import_key(open(private_key_path).read())

    # 创建解密器
    cipher = PKCS1_OAEP.new(private_key)

    # 读取加密文件内容
    with open(encrypted_file_path, 'rb') as file:
        encrypted_text = file.read()

    # 解密文件内容
    decrypted_text = cipher.decrypt(encrypted_text)

    # 写入解密后的文件内容
    decrypted_file_path = os.path.splitext(encrypted_file_path)[0] + '.txt'
    with open(decrypted_file_path, 'wb') as file:
        file.write(decrypted_text)

    print('Decryption done. Decrypted file saved as:', decrypted_file_path)

使用例子:

# 生成RSA密钥对
key = RSA.generate(2048)

# 保存公钥为文件
with open('public_key.pem', 'wb') as file:
    file.write(key.publickey().export_key())

# 保存私钥为文件
with open('private_key.pem', 'wb') as file:
    file.write(key.export_key())

# 要加密的文件路径
file_path = 'plaintext.txt'

# 加密文件
encrypt_file(file_path, 'public_key.pem')

# 解密文件
decrypt_file('plaintext.enc', 'private_key.pem')

以上代码通过使用RsaKey()对象生成RSA密钥对,并保存为文件。然后,使用公钥对文件进行加密,生成加密后的文件。最后,使用私钥对加密后的文件进行解密,生成解密后的文件。

请注意,为了运行上述代码,您需要安装pycryptodome库。可以通过运行以下命令来安装该库:

pip install pycryptodome

希望以上示例代码对您有所帮助!