2009/04/13

AES File Encryption/Decryption

public string AESforFile(string inputFilename, string outputFilename, string key, string IV, bool toEncrypt)
{
  try
  {
    using (FileStream fsInput = new FileStream(inputFilename, FileMode.Open, FileAccess.Read))
    {
      using (FileStream fsOutput = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
      {
        RijndaelManaged oAES = new RijndaelManaged();
        Rfc2898DeriveBytes oRfc2898DeriveBytes = new Rfc2898DeriveBytes(key + strSalt, Encoding.UTF8.GetBytes(IV));

        oAES.Padding = PaddingMode.PKCS7;
        oAES.Mode = CipherMode.CBC;
        oAES.KeySize = 256;
        oAES.Key = oRfc2898DeriveBytes.GetBytes(32);
        oAES.BlockSize = 128;
        oAES.IV = oRfc2898DeriveBytes.GetBytes(16);

        // Now create a crypto stream through which we are going
        // to be pumping data.
        // The fsOutput is going to be receiving the encrypted bytes.
        CryptoStream oCryptoStream = toEncrypt ?
          oCryptoStream = new CryptoStream(fsOutput, oAES.CreateEncryptor(), CryptoStreamMode.Write) :
          oCryptoStream = new CryptoStream(fsOutput, oAES.CreateDecryptor(), CryptoStreamMode.Write);

        // Now will will initialize a buffer and will be processing the input file in chunks.
        // This is done to avoid reading the whole file (which can be huge) into memory.
        int bufferLen = 4096;
        byte[] buffer = new byte[bufferLen];
        int bytesRead;

        do
        {
          // read a chunk of data from the input file
          bytesRead = fsInput.Read(buffer, 0, bufferLen);
          // encrypt it
          oCryptoStream.Write(buffer, 0, bytesRead);
        }
        while (bytesRead != 0);

        oCryptoStream.Close();
        oAES.Clear();
      }
    }
    return "Success";
  }
  catch (CryptographicException cex)
  {
    return cex.Message;
  }
  catch (IOException ioe)
  {
    return ioe.Message;
  }
}

No comments:

Post a Comment