Backend Development
Python Tutorial
Python cryptography.fernet implements file encryption and decryption tutorial
Python cryptography.fernet implements file encryption and decryption tutorial

This tutorial details how to use the fernet module in Python's cryptography library to implement file encryption and decryption operations. The article will cover the generation, management and reuse of Fernet keys, as well as how to securely perform encryption and decryption processes in files, and emphasize the importance of secure key storage to ensure data confidentiality.
1. Introduction: Introduction to cryptography.fernet
Today, when information security is becoming increasingly important, encrypting sensitive data is a basic means to protect its confidentiality. Python's cryptography library provides a set of powerful and easy-to-use encryption tools, of which the fernet module is ideal for implementing symmetric encryption. Fernet is a symmetric encryption scheme based on the AES algorithm, which ensures message authentication, integrity and confidentiality, and is easy to integrate into applications.
The core principle of Fernet is to use a shared key to encrypt and decrypt data. This means that the key used to encrypt the data must be exactly the same as the key used to decrypt the data. If the key is lost or compromised, the data cannot be recovered or is at risk of unauthorized access.
2. Core concepts: key generation and Fernet examples
Before using Fernet for file encryption and decryption, we need to understand its two key concepts: key generation and creation of Fernet instances.
2.1 Key generation
The Fernet key is a 32-byte URL-safe Base64 encoded string. It is the basis of symmetric encryption and must be kept strictly confidential. A brand new key can be generated through the Fernet.generate_key() method.
from cryptography.fernet import Fernet
# Generate a Fernet key key = Fernet.generate_key()
print(f"Generated Fernet key (Base64 encoded): {key.decode()}")
Important: Each call to Fernet.generate_key() generates a completely new and different key. For data that requires persistent encryption, you must save the generated key and reuse it in subsequent decryption operations.
2.2 Fernet instance creation
Once you have the key, you can use it to create a Fernet instance. This instance will be used to perform the actual encryption and decryption operations.
# Create a Fernet instance using the generated key cipher = Fernet(key)
3. File encryption and decryption operations
Fernet instances provide encrypt() and decrypt() methods to handle byte data. For file operations, we usually need to read the file content in binary mode, encrypt or decrypt it, and then write the processed content to the file.
3.1 Implementation of in-place encryption and decryption
The following code example shows how to implement in-place encryption and decryption of files in a single function. This means that the file contents are directly replaced with encrypted or decrypted data.
import os
from cryptography.fernet import Fernet
from cryptography.fernet import InvalidToken # Used to handle decryption failure exceptions def process_file_in_place(filename: str, cipher: Fernet, action: str, debug: bool = False):
"""
Encrypt or decrypt file contents in-place.
Args:
filename (str): The file path to be processed.
cipher (Fernet): Fernet encryption instance.
action (str): Action type, which can be "encrypt" or "decrypt".
debug (bool): Whether to print the encrypted content after encryption.
"""
# Open the file in binary read and write mode (rb allows reading and writing, the file pointer is initially at the beginning)
with open(filename, "rb ") as data_file:
content = data_file.read() # Read all contents of the file # Perform encryption or decryption according to the specified operation processed_content = b""
if action == "encrypt":
processed_content = cipher.encrypt(content)
if debug:
print(f"Encrypted content (bytes): {processed_content}")
elif action == "decrypt":
try:
processed_content = cipher.decrypt(content)
if debug:
print(f"Decrypted content (bytes): {processed_content}")
exceptInvalidToken:
print(f"Error: Unable to decrypt file '{filename}'. There may be a key mismatch or the data is corrupted.")
return # Decryption failed, exit function else:
raise ValueError("Operation type must be 'encrypt' or 'decrypt'")
# Move the file pointer to the beginning of the file data_file.seek(0)
#Write the processed content data_file.write(processed_content)
# If the new content is shorter than the old content, truncate the file to ensure the file size is correct data_file.truncate()
if __name__ == "__main__":
test_filename = "example_data.txt"
original_text = "Hello, world! This is a secret message that needs to be protected."
# 1. Create a raw plain text file with open(test_filename, "w", encoding="utf-8") as f:
f.write(original_text)
print(f"Original file '{test_filename}' content: {original_text}")
# 2. Generate a Fernet key and create an instance # Note: This key is only used for this run. In actual applications, persistent storage key_for_example = Fernet.generate_key() is required
cipher_for_example = Fernet(key_for_example)
print(f"Generated Fernet key (Base64 encoded): {key_for_example.decode()}")
# 3. Encrypted file print("\n---Perform encryption---")
process_file_in_place(test_filename, cipher_for_example, "encrypt", debug=True)
with open(test_filename, "rb") as f:
print(f"The binary content (part) of the encrypted file '{test_filename}': {f.read()[:50]}...") # Only print the first 50 bytes # 4. Decrypt the file print("\n---Execute decryption---")
process_file_in_place(test_filename, cipher_for_example, "decrypt")
with open(test_filename, "r", encoding="utf-8") as f: # The decrypted content can be read as text decrypted_text = f.read()
print(f"Decrypted file '{test_filename}' content: {decrypted_text}")
# 5. Verify whether the decrypted content matches the original content assert decrypted_text == original_text
print("\nVerification successful: the decrypted content is consistent with the original content.")
# Clean up the test file if os.path.exists(test_filename):
os.remove(test_filename)
Code analysis:
- open(filename, "rb "): Open the file in binary read-write mode. r means read, b means binary, which means writing operations are allowed at the same time. The file pointer is initially located at the beginning of the file.
- data_file.read(): Read the entire contents of the file. For large files, it may be necessary to read and process them in chunks.
- cipher.encrypt(content) / cipher.decrypt(content): Perform encryption or decryption operations. These methods accept and return bytes.
- data_file.seek(0): Reposition the file pointer to the beginning of the file so that new content can be written from the beginning.
- data_file.write(processed_content): Write the encrypted or decrypted content to the file.
- data_file.truncate(): Very important! If the newly written content is shorter than the original content, old data may remain at the end of the file. The truncate() method truncates the file to the current file pointer position, clearing out excess old data.
4. Key management: persistence and reuse
In practical applications, it is not feasible to generate a new key every time the program is run. To be able to encrypt and decrypt data at different points in time or between different program instances, keys must be stored persistently and reused.
4.1 Correct key persistence method
Proper key persistence
The above is the detailed content of Python cryptography.fernet implements file encryption and decryption tutorial. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20521
7
13634
4
Solve the error of multidict build failure when installing Python package
Mar 08, 2026 am 02:51 AM
When installing libraries that depend on multidict in Python, such as aiohttp or discord.py, users may encounter the error "ERROR: Could not build wheels for multidict". This is usually due to the lack of the necessary C/C compiler or build tools, preventing pip from successfully compiling multidict's C extension from source. This article will provide a series of solutions, including installing system build tools, managing Python versions, and using virtual environments, to help developers effectively solve this problem.
How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction
Mar 13, 2026 am 11:54 AM
The essence of zip is zipper pairing, which packs multiple iterable objects into tuples by position and does not automatically unpack the dictionary. When passing in a dictionary, its keys are traversed by default. You need to explicitly use the keys()/values()/items() view to correctly participate in parallel traversal.
How to find the sum of 5 numbers using Python's for loop
Mar 10, 2026 pm 12:48 PM
This article explains in detail how to use a for loop to read 5 integers from user input and add them up, provide a concise and readable standard writing method, and compare efficient alternatives to built-in functions.
How to draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation
Mar 13, 2026 pm 12:18 PM
Multi-dimensional classification histograms need to manually calculate the x position and call plt.bar hierarchically; when stacking, bottom must be used to accumulate height, and xticks and ylim must be explicitly set (bottom=0); avoid mixing stacked=True and seaborn, and colors should be dynamically generated and strictly match the layer sequence.
How Python manages dependencies_Comparison between pip and poetry
Mar 12, 2026 pm 04:21 PM
pip is suitable for simple projects, which only install packages and do not isolate the environment; poetry is a modern tool that automatically manages dependencies, virtual environments and version locking. Use pip requirements.txt for small projects, and poetry is recommended for medium and large projects. The two cannot be mixed in the same project.
Python set intersection optimization_large data volume set operation skills
Mar 13, 2026 pm 12:36 PM
The key to optimizing Python set intersection performance is to use the minimum set as the left operand, avoid implicit conversion, block processing and cache incremental updates. Priority should be given to using min(...,key=len) to select the smallest set, disabling multi-parameter intersection(), using frozenset or bloom filters to reduce memory, and using lru_cache to cache results in high-frequency scenarios.
How to store sparse matrices in Python_Dictionary coordinate storage and use of scipy.sparse
Mar 12, 2026 pm 05:48 PM
Use scipy.sparse.coo_matrix instead of a dictionary because the bottom layer uses row/col/data three-array to efficiently support operations; the structure needs to be deduplicated, converted to csr/csc and then calculated; save_npz is preferred for saving; operations such as slicing must use csr/csc format.
How to run a Python script_Detailed explanation of various ways to run a Python script and command line operations
Apr 03, 2026 pm 01:51 PM
To run a Python script, make sure that Python is installed, the PATH configuration is correct, and the script has no syntax errors; confirm the interpreter path and version through which/where and --version; shebang only takes effect on Linux/macOS and requires chmod x; when reporting module errors, you need to check the working directory, sys.path, piplist, and running mode.





