search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Install the cryptography library
Generate an encryption key
Load the key from file
Encrypt a file
Decrypt a file
Security considerations
Home Backend Development Python Tutorial How to encrypt and decrypt files in Python

How to encrypt and decrypt files in Python

Nov 26, 2025 am 12:53 AM

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.

How to encrypt and decrypt files in Python

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 cryptography

This 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use the Python zip function_Parallel traversal of multiple sequences and dictionary construction 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 draw a histogram in Python_Multi-dimensional classification data comparison and stacked histogram color mapping implementation 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 to find the sum of 5 numbers using Python's for loop 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 Python manages dependencies_Comparison between pip and poetry 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 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 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.

Python Flask project structure design_following MVC principles to achieve high code cohesion Python Flask project structure design_following MVC principles to achieve high code cohesion Mar 31, 2026 pm 12:24 PM

Model in Flask refers to entity classes and data logic defined by ORM such as SQLAlchemy. It should be independent of views and HTTP contexts, concentrated in the models/ directory, and encapsulate fields, queries and business verification.

How to call the pre-trained model in Python_HuggingFace library model download and fine-tuning How to call the pre-trained model in Python_HuggingFace library model download and fine-tuning Mar 31, 2026 pm 12:42 PM

The main reason for model download failure is network failure or lack of HuggingFace authentication; fine-tuning OOM is because float32 weights are loaded by default, so device_map="auto" should be used first for inference; mixed precision error reporting requires checking the data type and properly configuring fp16/bf16.

Related articles