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

如何使用 Python 函数来加密/解密文件?

发布时间:2023-06-30 16:53:59

使用 Python 函数来加密/解密文件是一种常见的文件保护方式。下面我们将讨论如何使用 Python 中的 cryptography 模块来实现文件的加密和解密,对文件进行安全的存储和传输。

加密文件的步骤如下:

步骤1:安装 cryptography 模块,可以使用 pip install cryptography 命令进行安装。

步骤2:导入所需的库和模块,在 Python 中,我们需要导入 cryptography 中的 Fernet 类。

from cryptography.fernet import Fernet

步骤3:生成密钥,密钥是用于加密和解密文件的。可以使用 Fernet 类的 generate_key() 方法生成一个新的密钥。

key = Fernet.generate_key()

步骤4:创建 Fernet 对象,使用步骤3中生成的密钥创建一个 Fernet 对象。

cipher_suite = Fernet(key)

步骤5:读取要加密的文件内容。

with open('input.txt', 'rb') as file:
    file_data = file.read()

步骤6:使用 Fernet 对象的 encrypt() 方法对文件数据进行加密。

encrypted_data = cipher_suite.encrypt(file_data)

步骤7:将加密的数据保存到新的文件中。

with open('encrypted_file.txt', 'wb') as file:
    file.write(encrypted_data)

解密文件的步骤如下:

步骤1:导入所需的库和模块。

from cryptography.fernet import Fernet

步骤2:读取加密的文件内容。

with open('encrypted_file.txt', 'rb') as file:
    encrypted_data = file.read()

步骤3:创建 Fernet 对象。

cipher_suite = Fernet(key)

步骤4:使用 Fernet 对象的 decrypt() 方法对加密数据进行解密。

decrypted_data = cipher_suite.decrypt(encrypted_data)

步骤5:将解密的数据保存到新的文件中。

with open('decrypted_file.txt', 'wb') as file:
    file.write(decrypted_data)

以上就是使用 Python 函数来加密/解密文件的步骤。通过使用 cryptography 模块中的 Fernet 类,我们可以轻松地保护文件的安全性。