[파이썬] SQLite 데이터베이스 암호화

SQLite is a popular and lightweight relational database management system that is widely used in various applications. Sometimes, it is necessary to keep the data in the SQLite database secure and confidential. One way to achieve this is by encrypting the database itself.

In this blog post, we will explore how to encrypt an SQLite database in Python, using the pysqlcipher3 library.

Installing the library

Before we get started, make sure that you have pysqlcipher3 installed. You can use the following command to install it via pip:

pip install pysqlcipher3

Create a new encrypted database

To create a new encrypted SQLite database, we need to follow a few steps:

  1. Import the necessary modules:
    import sqlite3
    from pysqlcipher3 import dbapi2 as sqlite
    
  2. Establish a connection to the database, specifying the encryption key:
    connection = sqlite.connect("encrypted.db")
    connection.execute("PRAGMA key='myencryptionkey'")
    
  3. Create a cursor object and execute the necessary SQL statements:
    cursor = connection.cursor()
    cursor.execute("CREATE TABLE users (id INT, name TEXT)")
    cursor.execute("INSERT INTO users VALUES (1, 'John')")
    
  4. Finally, commit the changes and close the connection:
    connection.commit()
    connection.close()
    

Now, you have successfully created a new encrypted SQLite database named “encrypted.db” with a table called “users”.

Accessing an existing encrypted database

To access an existing encrypted SQLite database, we need to follow similar steps as above with a slight modification:

  1. Import the necessary modules:
    import sqlite3
    from pysqlcipher3 import dbapi2 as sqlite
    
  2. Establish a connection to the encrypted database, specifying the encryption key:
    connection = sqlite.connect("encrypted.db")
    connection.execute("PRAGMA key='myencryptionkey'")
    
  3. Create a cursor object and execute the necessary SQL statements:
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM users")
    rows = cursor.fetchall()
    for row in rows:
     print(row)
    
  4. Finally, close the connection:
    connection.close()
    

By following the steps above, you should be able to access the data from the encrypted SQLite database.

Conclusion

Encrypting an SQLite database adds an extra layer of security to your data. By utilizing the pysqlcipher3 library in Python, you can easily create and access encrypted SQLite databases. Remember to choose a strong encryption key for better security.

I hope this blog post has given you a good introduction to SQLite database encryption in Python. If you have any questions or suggestions, feel free to leave a comment below.

Happy coding!