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],
		fStream = new FileStream(settings.DatabaseLocation, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
		new RNGCryptoServiceProvider().GetBytes(iv);
		fStream.Write(iv, 0, iv.Length);
		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);
		// a few loops which serialize some objects to the database as strings using writer.WriteLine
	} catch(Exception e) {

	} finally {
		if(writer != null) {
		if(cStream != null) {
		if(fStream != null) {

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. :)


This kind of error usually arise because you overlook the size of the file you are encrypting. In my opinion i suggest that if you could check the size of the file you are encrypting... it should be a multiple of 128bits. If it isnt then you will have to pad it and then encrypt. At the other end you will also have to take care of the padding bits/bytes. I hope this should sort your problem.
(I had this problem when i was coding in Codeblocks using simple C)