This is the code:
public void WriteDatabase() {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.
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();
}
}
}
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. :)
Bechir BejaouiPosted Jul 26, 2008, 6:03 PM
I remarked that when I used memory stream object to stock data I have the problem and when I use a file stream object instead I haven't the problem I don't know why? neverthe less this is my article about this you have also the code source I tried It and it works well then try it and send me back your point of view about this