TripleDES File Encryption/Decryption (6/13/2011 updated)

Here is how I encrypt/decrypt file by using the TripleDES. The inputFilename (and outputFilename) better includes the full path, ex. "C:\Temp\123.pdf".
public string TripleDESforFile(string inputFilename, string outputFilename, string key, string IV, bool toEncrypt)
    using (FileStream fsInput = new FileStream(inputFilename, FileMode.Open, FileAccess.Read))
      using (FileStream fsOutput = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
        PasswordDeriveBytes oPasswordDeriveBytes = new PasswordDeriveBytes(key, Encoding.UTF8.GetBytes(FormatStringLength(IV, 8, '9')));
        TripleDESCryptoServiceProvider oTDES = new TripleDESCryptoServiceProvider();
        oTDES.Mode = CipherMode.CBC;
        oTDES.Padding = PaddingMode.PKCS7;
        //Create the key and set it to the Key property of the TripleDESCryptoServiceProvider object.
        oTDES.Key = oPasswordDeriveBytes.GetBytes(24);  //must 24 bytes
        oTDES.IV = oPasswordDeriveBytes.GetBytes(8);  //must 8 bytes

        // 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, oTDES.CreateEncryptor(), CryptoStreamMode.Write) :
          oCryptoStream = new CryptoStream(fsOutput, oTDES.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;

          // 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);

    return "Success";
  catch (CryptographicException cex)
    return cex.Message;
  catch (IOException ioe)
    return ioe.Message;
  catch (Exception ex)
    return ex.Message;

6/13/2011 updated:
Use the PasswordDeriveBytes class to generate the Key and IV for the 3DES.

1 comment:

  1. The best piece of code in the Web to Encrypt/Decrypt files.