T
trant
I am trying just to do a basic encryption/decryption example from articles I
am reading on the net and I can't get anything to work.
I am trying the following code which I adapted from online examples:
byte[] inputData = Encoding.ASCII.GetBytes("something to encrypt");
MemoryStream outputStream = new MemoryStream();
SymmetricAlgorithm algorithm = new RijndaelManaged();
algorithm.GenerateKey();
algorithm.GenerateIV();
Console.WriteLine(Encoding.ASCII.GetString(algorithm.Key));
ICryptoTransform encryptor = algorithm.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(outputStream,
encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputData, 0, inputData.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
StringBuilder sb = new StringBuilder();
outputStream.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[1028];
int read;
while ((read = outputStream.Read(buffer, 0, buffer.Length)) > 0)
{
sb.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
Console.WriteLine(sb.ToString());
but it's not working, it fails because the outputStream gets closed by the
cryptography API when I close the cryptoStream object.
If I comment out the lines which close the CryptoStream I get no output
because the outputStream is completely empty. It did not encrypt the text or
anything.
Maybe I am using MemoryStream wrong?
I am trying to avoid using File streams, just want to handle this in memory...
am reading on the net and I can't get anything to work.
I am trying the following code which I adapted from online examples:
byte[] inputData = Encoding.ASCII.GetBytes("something to encrypt");
MemoryStream outputStream = new MemoryStream();
SymmetricAlgorithm algorithm = new RijndaelManaged();
algorithm.GenerateKey();
algorithm.GenerateIV();
Console.WriteLine(Encoding.ASCII.GetString(algorithm.Key));
ICryptoTransform encryptor = algorithm.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(outputStream,
encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputData, 0, inputData.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();
StringBuilder sb = new StringBuilder();
outputStream.Seek(0, SeekOrigin.Begin);
byte[] buffer = new byte[1028];
int read;
while ((read = outputStream.Read(buffer, 0, buffer.Length)) > 0)
{
sb.Append(Encoding.ASCII.GetString(buffer, 0, read));
}
Console.WriteLine(sb.ToString());
but it's not working, it fails because the outputStream gets closed by the
cryptography API when I close the cryptoStream object.
If I comment out the lines which close the CryptoStream I get no output
because the outputStream is completely empty. It did not encrypt the text or
anything.
Maybe I am using MemoryStream wrong?
I am trying to avoid using File streams, just want to handle this in memory...