Search code examples
javadatabaseencryptionembedded-database

Embedded Database and Encryption


I want to create an open-source application where the user-specific data is stored in an embedded database (e.g. SQLite, H2, HSQLDB). Additionally there would be a Login-Screen where the user has to enter the password of the encrypted database. But I'm not sure yet how to handle the encryption: Only handled by the database and/or by e.g. BouncyCastle with a whole file encryption?

I would prefer file-based encryption: If I would use file encryption would it be possible to work with an embedded database without storing the decrypted file physically on the hard disk? Does this request even make sense? I mean if my computer was compromised by an attacker the data stored in the database is somehow or other readable, right? On the other side it would be nice if there isn't the need to create a decrypted copy of the database (think about the space on the hard disk or performance).

Many thanks in advance for your help! :)


Solution

  • Ok, I solved my problem for now with the following process:

    I use HSQLDB now and its built-in encryption with AES-128 (and others like Blowfish). HSQLDB creates different files while an open connection exists.

    If the encryption mechanismen of HSQLDB is used, the files are encrypted with a generated private key. The generation creates a individual 32-character-wide key on each running.

    To secure this key and additionally the files, I pack the whole folder with the database files into a zip-File first. In the next step I encrypt this file with a password the user entered on the login screen. This password will not be saved physically. For the en-/decryption I use the AES-implementation of the Bouncy Castle Java Cryptography API.

    The encryption in detail: 1. Create random Initialization Vector (IV; 16 Byte), Salt (8 Byte) with the SecureRandom-Class and Data Encryption Key (DEK; 16 Byte) with KeyGenerator for AES. 2. Create 32 Byte-long PBKDF2-Key with entered password and salt and split it into Verification Key (VK; 16 Byte) and Key Encryption Key (KEK; 16 Byte). 3. Pack the folder which holds the database files into a zip-file and encrypt the bytes of this file with the DEK and by the AES-Provider. 4. Encrypt the DEK with KEK and IV by the AES-Provider. 5. Store IV, Salt, DEK and VK at the beginning of the encrypted zip-File. If you work additionally with database internal encryption you get a CRYPT_KEY which is also stored in the zip-file.

    In the end I delete the database files on every shutdown of the application.

    If you've any suggestions to make this process less vulnerable please don't hestitate to write. I would be very greatful to get ideas how to improve the security aspects of the described process!