SQLite3 数据库本身不提供内置的加密功能,但您可以使用外部加密库来实现数据的加密和解密
- 使用
sqlcipher3
库:
sqlcipher3
是一个基于 SQLite3 的加密扩展,它提供了透明的数据加密和解密功能。要使用它,您需要先安装 sqlcipher3
库。
对于 Ubuntu 或 Debian 系统,可以使用以下命令安装:
sudo apt-get install libsqlcipher3-dev
对于 macOS,可以使用 Homebrew 安装:
brew install sqlcipher3
然后,您需要重新编译 SQLite3 以链接到 sqlcipher3
库。在编译时,使用 --enable-loadable-plugin
选项。例如:
gcc -o sqlite3_encrypted sqlite3.c -lsqlcipher3 -lpthread -ldl
现在,您可以使用加密的 SQLite3 数据库文件。例如:
import sqlite3 conn = sqlite3.connect('encrypted_db.sqlite3') cursor = conn.cursor() # 创建表 cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''') # 插入数据 cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'alice@example.com')) conn.commit() # 读取数据 cursor.execute("SELECT * FROM users") print(cursor.fetchall()) conn.close()
- 使用 Python 的第三方库
pycryptodome
对 SQLite3 数据库进行加密:
首先,安装 pycryptodome
库:
pip install pycryptodome
然后,使用以下代码对 SQLite3 数据库进行加密和解密:
import sqlite3 from Cryptodome.Cipher import AES from Cryptodome.Random import get_random_bytes from Cryptodome.Util.Padding import pad, unpad def encrypt_data(data, key): cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size)) iv = cipher.iv return iv + ct_bytes def decrypt_data(encrypted_data, key): iv = encrypted_data[:AES.block_size] ct = encrypted_data[AES.block_size:] cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8') def encrypt_sqlite_db(db_path, key): conn = sqlite3.connect(db_path) cursor = conn.cursor() # 创建表 cursor.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''') # 插入数据 data = 'https://www.yisu.com/ask/Alice' encrypted_data = https://www.yisu.com/ask/encrypt_data(data, key)"INSERT INTO users (name, email) VALUES (?, ?)", (encrypted_data, b'')) conn.commit() # 读取数据 cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: decrypted_data = https://www.yisu.com/ask/decrypt_data(row[1], key)'encrypted_db.sqlite3', key) decrypt_sqlite_db('encrypted_db.sqlite3', key)
请注意,这些示例仅用于演示目的,实际应用中可能需要更多的安全措施,例如使用更安全的密钥管理方法、处理异常等。