要使用Python对文件进行非对称加密,可以使用cryptography库。下面是一个简单的示例,演示如何使用RSA算法对文件进行加密和解密:

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes

# 生成RSA密钥对
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
public_key = private_key.public_key()

# 将私钥保存到文件
pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)
with open('private_key.pem', 'wb') as f:
    f.write(pem)

# 将公钥保存到文件
pem = public_key.public_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PublicFormat.SubjectPublicKeyInfo
)
with open('public_key.pem', 'wb') as f:
    f.write(pem)

# 加密文件
def encrypt_file(file_path, public_key_path, output_path):
    with open(file_path, 'rb') as f:
        file_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(
        file_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)

# 解密文件
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('plaintext.txt', 'public_key.pem', 'encrypted_file.bin')
decrypt_file('encrypted_file.bin', 'private_key.pem', 'decrypted_file.txt')

在上述示例中,首先生成RSA密钥对,并将私钥和公钥保存到文件中。然后,定义了两个函数encrypt_filedecrypt_file,用于加密和解密文件。

encrypt_file函数中,首先读取要加密的文件数据和公钥。然后使用公钥对文件数据进行加密。最后将加密后的数据保存到指定文件。

decrypt_file函数中,首先读取要解密的文件数据和私钥。然后使用私钥对文件数据进行解密。最后将解密后的数据保存到指定文件。

使用示例中的encrypt_file函数和decrypt_file函数,可以分别加密和解密文件

用python给文件进行非对称加密

原文地址: http://www.cveoy.top/t/topic/ieNW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录