1
Reply

Encryption problems

Bill

Bill

Jul 23 2008 7:12 AM
3.3k
I'm trying to write to a file using RijndaelManaged in C#. I've got a Java application which works with the C# one to read and write to a database file. The C# app reads the file flawlessly, but when it comes to writing, the first few bytes of the file always seem to be junk when I come to read it again.

This is the code:
public void WriteDatabase() {
    FileStream fStream = null;
    CryptoStream cStream = null;
    StreamWriter writer = null;
    bool success = true;
    try {
        byte[] iv = new byte[16],
               passwordBytes,
               keyBytes;
        fStream = new FileStream(settings.DatabaseLocation, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
        new RNGCryptoServiceProvider().GetBytes(iv);
        fStream.Write(iv, 0, iv.Length);
        //fStream.Flush();
        
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        passwordBytes = Encoding.UTF8.GetBytes(settings.Password);
        keyBytes = md5.ComputeHash(passwordBytes);
        
        RijndaelManaged rj = new RijndaelManaged();
        rj.Mode = CipherMode.CBC;
        rj.IV = iv;
        rj.Key = keyBytes;
        rj.KeySize = 128;
        rj.BlockSize = 128;
        rj.Padding = PaddingMode.PKCS7;
        
        ICryptoTransform encryptor = rj.CreateEncryptor();
        cStream = new CryptoStream(fStream, encryptor, CryptoStreamMode.Write);
        writer = new StreamWriter(cStream);
        
        writer.WriteLine("CheckString");
        // a few loops which serialize some objects to the database as strings
       // using writer.WriteLine
    } catch(Exception e) {

    } finally {
        if(writer != null) {
            writer.Close();
            writer.Dispose();
        }
        if(cStream != null) {
            cStream.Close();
            cStream.Dispose();
        }
        if(fStream != null) {
            fStream.Close();
            fStream.Dispose();
        }
    }
}
When the data is read again, I get 20-30 characters of unprintable junk, then the text I wanted, correctly decrypted. Sometimes there's a linebreak in the junk, sometimes not (which would seem like the IV is being written to the file). Interestingly though, the IV that's generated during encryption and the IV read during decryption are the same.

I've tried using a BinaryWriter, but get the same results.

I can post the read method as well if necessary, but it reads the file from Java so as far as I can tell the problem is with the writing.

Thanks for any help. :)

Answers (1)