How to encrypt and decrypt files in Python
Fernet using the cryptography library can safely implement Python file encryption and decryption. 2. Generate and securely store keys for use in encryption and decryption processes. 3. When encrypting, read the file content and write it into the .enc file, and when decrypting, restore the original file. 4. Pay attention to key security management and avoid hard coding or submitting to version control. 5. Fernet is based on AES and HMAC and is suitable for most scenarios, but streaming processing of large files needs to be considered.

Encrypting and decrypting files in Python can be done securely using the cryptography library, which provides modern encryption methods like Fernet. Fernet guarantees that data encrypted cannot be manipulated or read without the key. Here's how to implement file encryption and decryption step by step.
Install the cryptography library
If you haven't installed the cryptography package yet, use pip to install it:
pip install cryptographyThis library includes Fernet, a symmetric encryption method that's safe and easy to use.
Generate an encryption key
A Fernet key is required to encrypt and decrypt files. Generate and save it securely—never hardcode it in your script for production use.
from cryptography.fernet import Fernet#Generate a key
key = Fernet.generate_key()
# Save the key to a file (keep this safe)
with open("secret.key", "wb") as key_file:
key_file.write(key)
You only need to generate the key once. Reuse it for both encryption and decryption.
Load the key from file
Before encrypting or decrypting, load the saved key:
def load_key():return open("secret.key", "rb").read()
Make sure the key file exists and is accessible when running your script.
Encrypt a file
To encrypt a file, read its contents, encrypt them with Fernet, and write the output to a new file.
def encrypt_file(filename, key):f = Fernet(key)
# Read the original file
with open(filename, "rb") as file:
file_data = file.read()
# Encrypt data
encrypted_data = f.encrypt(file_data)
# Write encrypted data to a new file
with open(filename ".enc", "wb") as file:
file.write(encrypted_data)
Example usage:
key = load_key()encrypt_file("my_secret_document.txt", key)
This creates an encrypted version of the file with a .enc extension.
Decrypt a file
Decryption reverses the process. It requires the same key used for encryption.
def decrypt_file(filename, key):f = Fernet(key)
# Read the encrypted file
with open(filename, "rb") as file:
encrypted_data = file.read()
# Decrypt data
decrypted_data = f.decrypt(encrypted_data)
# Write back the original data
with open(filename.replace(".enc", ""), "wb") as file:
file.write(decrypted_data)
Example usage:
key = load_key()decrypt_file("my_secret_document.txt.enc", key)
The decrypted file will be saved without the .enc extension.
Security considerations
Keep these points in mind:
- Store the encryption key securely—preferably in an environment variable or secure key manager.
- Never commit the key to version control.
- Fernet uses AES in CBC mode with PKCS7 padding and HMAC authentication, making it safe for most use cases.
- Large files are loaded into memory entirely, so consider streaming for very large files.
Basically, with the cryptography library and Fernet, file encryption in Python is straightforward and secure. Just handle the key responsibly.
The above is the detailed content of How to encrypt and decrypt files in Python. 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.





