Saturday, July 08, 2006

 

Chaining Cryptography Algorithms

I did a little Symmetric Encryption project some days ago which required me to make a class implementing an interface. One of the methods that needed implementing involved encrypting a file and writing it out base64-encoded. In fact, the encoding requirement came later so I had the encryption bit done easily by reading from the input file and writing to the CryptoStream which in turn wrote to the underlying output file stream, and voila! we had our encrypted file.

After the base64-encoding requirement was communicated to me, it had me in a spin. I mean here I had a neat little method reading and writing to streams working seamlessly. Since CryptoStreams cannot be written to and read from at the same time, this meant I had to re-open the file, base64-encode it and then output it again. Terribly inefficient as I'm sure you'll agree.

Then I came across chaining algorithms (specifically cryptostreams), it was just the thing I was looking for. Maybe, I'm still an intermediate when it comes to dot net because I did not know about this earlier. Here's how it works: (Error-checking and input validation removed for readability).

//Our input and output streams
FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read);

FileStream fsOut = new FileStream(outputFile, FileMode.OpenOrCreate, FileAccess.Write);

//Create two ICryptoTransforms
ICryptoTransform base64 = new ToBase64Transform();
ICryptoTransform enc = alg.CreateEncryptor(); //where alg is the SymmetricAlgorithm object ofcourse

//Create the crypto streams chained together

CryptoStream tobase64 = new CryptoStream(fsOut, base64, CryptoStreamMode.Write);
CryptoStream cs = new CryptoStream(tobase64, enc, CryptoStreamMode.Write);

//So essentially, 'cs' writes to 'tobase64' and 'tobase64' writes to our output stream

// Now, create a buffer to encrypt input file in chunks rather than in one go

byte[] buffer = new byte[8192];

int bytesRead;


do

{

// read a chunk of data from the input file
bytesRead = fsIn.Read(buffer, 0, buffer.Length);

// The input data is written to the crypto stream
// and automatically base64-encoded and written to
// the output stream
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);

cs.Close(); //closes the underlying 'fsOut' and 'tobase64' streams as well

fsIn.Close();


And we're done. Pretty nifty ... eh?

Comments:
you in security??
What do u exactly do? design algorithms?
 
Not really. I did a little encryption project on the side. Helps earn some dough :-)
 

Post a Comment



<< Home