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

通过Cryptography.Fernet模块在Python中实现AES加密

发布时间:2024-01-20 16:56:35

在Python中,可以使用Cryptography.Fernet模块来实现AES加密。Fernet是一个对称加密工具,可以使用AES加密算法来加密和解密数据。下面是一个使用Cryptography.Fernet模块实现AES加密的例子:

首先,需要安装Cryptography库。可以使用pip命令来安装:

pip install cryptography

然后,引入cryptography.fernet模块:

from cryptography.fernet import Fernet

生成一个密钥,可以使用Fernet.generate_key()方法来生成一个随机的密钥:

# 生成一个随机密钥
key = Fernet.generate_key()

将生成的密钥保存到文件中,以便在加密和解密时使用。

# 将密钥保存到文件中
with open('key.txt', 'wb') as key_file:
    key_file.write(key)

从文件中读取密钥:

# 从文件中读取密钥
with open('key.txt', 'rb') as key_file:
    key = key_file.read()

使用读取的密钥创建一个Fernet对象:

# 创建一个Fernet对象
cipher_suite = Fernet(key)

使用Fernet对象来加密数据,可以使用Fernet.encrypt()方法:

# 加密数据
data = b'Hello, World!'
cipher_text = cipher_suite.encrypt(data)

将加密后的数据保存到文件中:

# 将加密后的数据保存到文件中
with open('cipher_text.txt', 'wb') as cipher_file:
    cipher_file.write(cipher_text)

使用Fernet对象来解密数据,可以使用Fernet.decrypt()方法:

# 从文件中读取密文
with open('cipher_text.txt', 'rb') as cipher_file:
    cipher_text = cipher_file.read()

# 解密数据
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text)

运行上述代码,可以看到解密后的数据和原始数据相同。

值得注意的是,Fernet对象使用的密钥需要保密。如果密钥泄露,那么数据也就不再安全。因此,在实际使用中,密钥的保密非常重要。

这就是使用Cryptography.Fernet模块在Python中实现AES加密的简单示例。希望对你有所帮助!