To create a password-protected SQLite database, you can use SQLCipher
, an encryption extension for SQLite that allows you to create encrypted databases with a password.
Here’s how to create a password-protected SQLite database using SQLCipher:
1. Install SQLCipher
First, you need to install SQLCipher. Based on your operating system, use the following commands:
- macOS:
brew install sqlcipher
- Linux (Ubuntu):
sudo apt-get install sqlcipher
- Windows:
Download and install SQLCipher or use its Windows binaries.
2. Create a Password-Protected SQLite Database
Use the following command in the terminal to create an encrypted SQLite database:
sqlcipher my_secure_database.db
Once inside SQLCipher, set an encryption key (password) and create the database:
PRAGMA key = 'your_password_here';
CREATE TABLE test (id INTEGER PRIMARY KEY, name TEXT);
This creates an encrypted database called my_secure_database.db
and sets the password to your_password_here
.
3. Access the Encrypted Database
Each time you want to access the encrypted database, you need to input the password to decrypt the file. For example:
sqlcipher my_secure_database.db
Then, inside the SQLCipher prompt, decrypt the database by running:
PRAGMA key = 'your_password_here';
You can now operate the database like a normal SQLite database.
4. Access Encrypted Database Using Python
If you need to access the encrypted SQLite database from Python, you can use the pysqlcipher3
library.
- Install
pysqlcipher3
:
pip install pysqlcipher3
- Access the encrypted database with Python:
import pysqlcipher3.dbapi2 as sqlite
# Connect to the encrypted database
conn = sqlite.connect('my_secure_database.db')
# Set the encryption key
conn.execute("PRAGMA key = 'your_password_here';")
# Create a cursor
cursor = conn.cursor()
# Execute an SQL statement
cursor.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT)')
conn.commit()
# Close the connection
conn.close()
These steps allow you to create and manage a password-protected SQLite database.