Here is how I do it:
RijndaelManaged rm = new RijndaelManaged();
byte[] data = Encoding.UTF8.GetBytes("Hello");
ICryptoTransform encryptor = rm.CreateEncryptor();
ICryptoTransform decryptor = rm.CreateDecryptor();
byte[] encData = RijndaelEncrypt(encryptor, data);
byte[] clearData = RijndaelDecrypt(decryptor, encData);
Console.WriteLine("Data:" + Encoding.UTF8.GetString(clearData));
private static byte[] RijndaelDecrypt(ICryptoTransform decryptor,
byte[] encrypted)
{
if ( decryptor == null )
throw new ArgumentNullException("decryptor");
if ( encrypted == null )
throw new ArgumentNullException("encrypted");
using ( MemoryStream msDecrypt = new MemoryStream(encrypted) )
using ( CryptoStream csDecrypt = new CryptoStream(msDecrypt,
decryptor, CryptoStreamMode.Read) )
{
byte[] fromEncrypt = new byte[encrypted.Length];
int read = csDecrypt.Read(fromEncrypt, 0,
fromEncrypt.Length);
if ( read < fromEncrypt.Length )
{
byte[] clearBytes = new byte[read];
Buffer.BlockCopy(fromEncrypt, 0, clearBytes, 0, read);
return clearBytes;
}
return fromEncrypt;
}
}
private static byte[] RijndaelEncrypt(ICryptoTransform encryptor,
byte[] data)
{
if ( encryptor == null )
throw new ArgumentNullException("encryptor");
if ( data == null )
throw new ArgumentNullException("data");
//Encrypt the data.
using ( MemoryStream msEncrypt = new MemoryStream() )
using ( CryptoStream csEncrypt = new CryptoStream(msEncrypt,
encryptor, CryptoStreamMode.Write) )
{
//Write all data to the crypto stream and flush it.
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
//Get encrypted array of bytes.
byte[] encrypted = msEncrypt.ToArray();
return encrypted;
}
}
--
William Stacey [MVP]
[quoted text, click to view] "rajbharati" <rajbharati@discussions.microsoft.com> wrote in message
news:DFBD7A48-4482-4892-A799-9ACC740742D3@microsoft.com...
> Because memeorystream cannot support read/write at the same time, i copied
> the encrypted buffer to byte array and re-instantiate another memorystream
> passing that byte array which in tern is used to intantiate cryptostream.
> I
> think i could not use seek method to reposition this cryptostream object.
> But
> i call seek method from memorystream object before passing to
> cryptostream.
> But no difference!
>
> "William Stacey [MVP]" wrote:
>
>> hmm. Are you resetting the current Position back to 0 after filling the
>> memorystream?
>>
>> --
>> William Stacey [MVP]
>>
>> "rajkumar" <rajkumar@discussions.microsoft.com> wrote in message
>> news:A9BAE700-E511-4D75-8260-9D8941B90E29@microsoft.com...
>> >I tried to implement cryptographic using memorystream instead of other
>> >stream
>> > like file stream etc. Encryption is ok but could not get original data
>> > on
>> > decryption.
>> > Same logic works if i use filestream for cryptostream!
>> >
>> >
>>
>>
>>