views:

170

answers:

1

Hi,

The Rijndael encryption algorithm is implemented in .NET using 3 streams in the following example: Rinjdael.

Can someone explain to me what these streams are doing? How/Why are they used?

// Declare the streams used
// to encrypt to an in memory
// array of bytes.
MemoryStream msEncrypt = null;
CryptoStream csEncrypt = null;
StreamWriter swEncrypt = null;

// Declare the RijndaelManaged object
// used to encrypt the data.
RijndaelManaged aesAlg = null;

try
{
    // Create a RijndaelManaged object
    // with the specified key and IV.
    aesAlg = new RijndaelManaged();
    aesAlg.Key = Key;
    aesAlg.IV = IV;


    // Create a encryptor to perform the stream transform.
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

    // Create the streams used for encryption.
    msEncrypt = new MemoryStream();
    csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
    swEncrypt = new StreamWriter(csEncrypt);

    //Write all data to the stream.
    swEncrypt.Write(plainText);

}
+3  A: 

swEncrypt is a StreamWriter - its job is to convert text into binary data

csEncrypt is a CryptoStream - its job is to convert binary data into encrypted binary data

msEncrypt is a MemoryStream - its job is to store the data it's given in memory, so you can get it out later

When you put them all together, you basically get something where you can write plain text in one end, and get encrypted binary data out (having stored it in memory temporarily) of the other end.

Jon Skeet
should not the built in AES wrapper do all of this internally,and simply return a string? Or is that assuming too much for the method? (I guess so since they built it so generic)
Cryptography is generally applied to streams of binary data. That gives a lot of flexibility. Let the AES part do what it's good at, and let StreamWriter do what *it's* good at, etc :)
Jon Skeet
(But you could write your own convenience wrapper, of course.)
Jon Skeet