Python Data Encryption & Decryption Guide
In Python, you can use the cryptography library to perform data encryption and decryption operations. Here is a simple example:
from cryptography.fernet import Fernet
# 生成密钥
def generate_key():
key = Fernet.generate_key()
with open('key.key', 'wb') as key_file:
key_file.write(key)
# 读取密钥
def load_key():
return open('key.key', 'rb').read()
# 加密数据
def encrypt_data(data, key):
f = Fernet(key)
encrypted_data = f.encrypt(data.encode())
return encrypted_data
# 解密数据
def decrypt_data(data, key):
f = Fernet(key)
decrypted_data = f.decrypt(data).decode()
return decrypted_data
# 生成密钥
generate_key()
# 读取密钥
key = load_key()
# 加密数据
encrypted_data = encrypt_data("Hello, world!", key)
print("加密后的数据:", encrypted_data)
# 解密数据
decrypted_data = decrypt_data(encrypted_data, key)
print("解密后的数据:", decrypted_data)
In the example above, we first generate a key using the generate_key function and save it to the file key.key. Then we use the load_key function to read this key.
encrypt_data function encrypts data using a key and returns the encrypted data. decrypt_data function decrypts the encrypted data using the key and returns the decrypted data.
Finally, we use the generated key to encrypt and decrypt the string “Hello, world!” and output the results.
Please note that in practical applications, the storage and management of keys is crucial. The leakage of keys could result in data disclosure or malicious tampering by attackers. Therefore, appropriate security measures should be implemented to protect the security of keys.