如何用Python连接经SQLCipher加密的SQLite3数据库及替代方案
Hey there, let's tackle your issues one by one with practical solutions tailored for Python 3:
You're right that pysqlcipher is only for Python 2.7, but there's a drop-in replacement built for Python 3: pysqlcipher3. It’s maintained to work with modern Python versions and fully supports SQLCipher’s encryption format.
Step 1: Install the library
First, grab it via pip:
pip install pysqlcipher3
Step 2: Connect to your encrypted database
Here’s a working snippet to connect using your password "test":
import pysqlcipher3.dbapi2 as sqlite3 # Initialize connection to your encrypted database conn = sqlite3.connect("your_encrypted_db.db") cursor = conn.cursor() # Set the encryption key (matches the password you used in DB Browser) cursor.execute("PRAGMA key='test';") # Verify the connection works by listing tables (optional check) cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print("Tables found:", cursor.fetchall()) # Proceed with your database operations... conn.close()
This should fix the file is encrypted or is not a database error, as pysqlcipher3 understands SQLCipher’s encryption scheme.
If you’re open to alternatives beyond SQLCipher, here are reliable options:
pysqlcipher3+ SQLite: Still the top pick for portability and SQL familiarity—no major syntax changes needed if you’re already used to SQLite.- SQLite with Built-in Encryption (Python 3.13+): Starting from Python 3.13, the standard
sqlite3module can leverage SQLCipher if your system’s SQLite library is compiled with it. This avoids extra dependencies but requires a newer Python version and properly configured SQLite. - Berkeley DB: A lightweight key-value store with Python bindings (
bsddb3) that supports AES encryption. It’s portable, though it uses a different query model than SQL. - SQLite Encryption Extension (SEE): The official paid encryption add-on for SQLite. If you’re working on a commercial project, this offers enterprise-grade security and integrates directly with Python’s
sqlite3module (requires compiling SQLite with SEE enabled).
Using zipfile to encrypt an unencrypted SQLite database is technically possible, but it comes with significant tradeoffs:
Pros:
- No extra libraries required—uses Python’s standard
zipfilemodule. - Quick to implement for one-off or low-frequency access scenarios.
Cons:
- Poor performance: You have to fully unzip the database every time you need to access it, then re-zip it afterward. This is slow for apps with frequent reads/writes.
- Data consistency risks: If your app crashes mid-operation, you could end up with a corrupted zip file or an inconsistent database state.
- Weak security:
zipfileuses outdated ZipCrypto encryption, which is vulnerable to brute-force attacks. It’s not suitable for sensitive data that needs strong protection.
Example Code
If you still want to go this route, here’s how to implement it:
Encrypt the database:
import zipfile def encrypt_db_with_zip(db_path, output_zip, password): with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zip_ref: zip_ref.setpassword(password.encode('utf-8')) zip_ref.write(db_path, arcname=db_path.split("/")[-1])
Access the encrypted database:
import zipfile import sqlite3 import os def access_zipped_db(zip_path, password, temp_db_path): # Extract the database to a temporary location with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.setpassword(password.encode('utf-8')) zip_ref.extractall() # Connect to the unzipped database conn = sqlite3.connect(temp_db_path) # Perform your operations here... # Clean up: delete the temporary database file after use conn.close() os.remove(temp_db_path)
Just remember to handle temporary files carefully to avoid leaving sensitive data behind on your system.
内容的提问来源于stack exchange,提问作者H. Dave




