Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite file containing garbage characters

I'm currently using MonoTouch and SQLite in order to determine whether using a database with encryption is better than a standard .txt file with encryption.

I am attempting to use RijndaelManaged and other System.Security.Cryptography methods to encrypt my SQLite DB, but the DB becomes corrupt.

I have found the problem, but have no idea why it's happening or how to fix it. This is a basic SQLite file with a single table:

SQLite format 3@  -‚

øø?gtablenewnewCREATE TABLE new (id int(5), name vchar(255))

After using an example online, and encrypting this database, I get this:

SQLite format 3@  -�

��?gtablenewnewCREATE TABLE new (id int(5), name vchar(255))

This leaves the DB corrupt and unusable. Does anyone have any idea why this happens? Can anyone help me to encrypt this DB WITHOUT using SQLCipher?

EDIT: I have tried reading the raw DB in as bytes, and tried converting the bytes to a string, but no matter what encoding I use, I get \0 after the first line.

like image 378
Nathan White Avatar asked Jul 30 '12 14:07

Nathan White


2 Answers

Without seeing your encrypt/decrypt routines I can only guess. Since you are using Rijndael, you need to ensure that you are setting the same Padding on the class for encrypt and decrypt. Also, make sure you call FlushFinalBlock when encrypting the data. That call is not listed in the sample (although they are calling Close which should call FlushFinalBlock, so if you are calling Close on the CryptoStream then you should be okay there).

Edit
I was thinking more about this. I think it may be related to the padding (again, without seeing your code its hard to say). Depending on the padding mode you choose, you will need to strip the padded bytes back off of the plain text after decrypting.

like image 166
pstrjds Avatar answered Nov 09 '22 05:11

pstrjds


The most likely places for your problem to live is when you're reading in the unencrypted database prior to encryption, or opening a new file to write out the freshly decrypted database.

As troubleshooting steps, you might consider reading in the raw database file as bytes and then writing it out, without any intervening encryption/decryption. If it still gets corrupted, the first thing I'd check is the encoding with which you're opening your output file.

like image 32
sblom Avatar answered Nov 09 '22 05:11

sblom