Can I append to an encrypted text file?

T

Tom Regan

I need to encrypt messages printed to an application event log. I've
copied the approach described in MS "307010 - How To Encrypt and
Decrypt a File by Using Visual C# .NET", but I want to append.

This MS example (and all other examples I've found) assumes one will
read an entire plain text file, encrypt it, then write the entire file
to disk. I only want to append individual lines of encrypted text to
an encrypted file, then read the thing.

Below is a complete console app that shows the code I am using. It
"works" if I only write one line to the file and then decrypt, but
subsequent lines get mangled. I'd appreciate any advice.

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;

namespace CryptoSample
{
public class CryptoSample3
{
private const string Key = "1234abcd";
private const string LogFilePath="C:\\Log.log";
static void LogIt(string Msg)
{
//append encrypted string to the log
using(FileStream LogFile = new
FileStream(LogFilePath,FileMode.Append,FileAccess.Write))
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(Key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(Key);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new
CryptoStream(LogFile,desencrypt,CryptoStreamMode.Write);

byte[] bytearrayinput = new byte[Msg.Length];
bytearrayinput=ASCIIEncoding.ASCII.GetBytes(Msg);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
LogFile.Close();
}
}
static string ViewLog(string DecryptKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(DecryptKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(DecryptKey);

//read the encrypted file back.
using(FileStream LogFile = new
FileStream(LogFilePath,FileMode.Open,FileAccess.Read))
{
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new
CryptoStream(LogFile,desdecrypt,CryptoStreamMode.Read);
return(new StreamReader(cryptostreamDecr).ReadToEnd());
}
}
static void Main()
{
LogIt("This is the Message ");
LogIt(" This is Message Two ");
LogIt(" This is Message Three ");
string s = ViewLog(Key);
Console.Write(s);
Console.WriteLine ("Press Enter to continue...");
Console.ReadLine();
}
}
}
 
T

Tom Regan

Sorry, I posted to the wrong newsgroup, I should have posted this to
microsoft.public.dotnet.security.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top