Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypting/Decrypting large files (.NET)

I have to encrypt, store and then later decrypt large files. What is the best way of doing that? I heard RSA encryption is expensive and was advised to use RSA to encrypt an AES key and then use the AES key to encrypt the large files. Any suggestions with example will be great.

like image 938
kalrashi Avatar asked Feb 11 '12 02:02

kalrashi


People also ask

Can AES 128 be decrypted?

As shown above, even with a supercomputer, it would take 1 billion billion years to crack the 128-bit AES key using brute force attack. This is more than the age of the universe (13.75 billion years).

Which encryption is best in C#?

AES Encryption offers good performance and a good level of security. AES Encryption is a symmetric cipher and uses the same key for encryption and decryption.

How do I encrypt and decrypt request data in .NET core?

Encryption and decryption of query stringsThe protect method inputs a byte or string and encrypts it. The encrypted data can then be viewed in the web application. The 'Unprotect' method is used to decrypt the encrypted ID and display the content of the data. The below code snippet is used to decrypt data.


2 Answers

One organism's large is another's petite, though we all know expensive when we see it. Wink, wink.

Try benchmarking something like the following in your environment and see where you're at:

EDIT 2/13/2012: The code has been updated as I've become (imperceptibly) smarter and also noticed a few cut'n'paste errors that had crept in. Mea culpa.

using System; using System.IO; using System.Security.Cryptography; using System.Text;  ...      // Rfc2898DeriveBytes constants:     public readonly byte[] salt = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Must be at least eight bytes.  MAKE THIS SALTIER!     public const int iterations = 1042; // Recommendation is >= 1000.      /// <summary>Decrypt a file.</summary>     /// <remarks>NB: "Padding is invalid and cannot be removed." is the Universal CryptoServices error.  Make sure the password, salt and iterations are correct before getting nervous.</remarks>     /// <param name="sourceFilename">The full path and name of the file to be decrypted.</param>     /// <param name="destinationFilename">The full path and name of the file to be output.</param>     /// <param name="password">The password for the decryption.</param>     /// <param name="salt">The salt to be applied to the password.</param>     /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>     public void DecryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)     {         AesManaged aes = new AesManaged();         aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;         aes.KeySize = aes.LegalKeySizes[0].MaxSize;         // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.         Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);         aes.Key = key.GetBytes(aes.KeySize / 8);         aes.IV = key.GetBytes(aes.BlockSize / 8);         aes.Mode = CipherMode.CBC;         ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);          using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))         {             using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))             {                 try                 {                     using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))                     {                         source.CopyTo(cryptoStream);                     }                 }                 catch (CryptographicException exception)                 {                     if (exception.Message == "Padding is invalid and cannot be removed.")                         throw new ApplicationException("Universal Microsoft Cryptographic Exception (Not to be believed!)", exception);                     else                         throw;                 }             }         }     }      /// <summary>Encrypt a file.</summary>     /// <param name="sourceFilename">The full path and name of the file to be encrypted.</param>     /// <param name="destinationFilename">The full path and name of the file to be output.</param>     /// <param name="password">The password for the encryption.</param>     /// <param name="salt">The salt to be applied to the password.</param>     /// <param name="iterations">The number of iterations Rfc2898DeriveBytes should use before generating the key and initialization vector for the decryption.</param>     public void EncryptFile(string sourceFilename, string destinationFilename, string password, byte[] salt, int iterations)     {         AesManaged aes = new AesManaged();         aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;         aes.KeySize = aes.LegalKeySizes[0].MaxSize;         // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.         Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);         aes.Key = key.GetBytes(aes.KeySize / 8);         aes.IV = key.GetBytes(aes.BlockSize / 8);         aes.Mode = CipherMode.CBC;         ICryptoTransform transform = aes.CreateEncryptor(aes.Key, aes.IV);          using (FileStream destination = new FileStream(destinationFilename, FileMode.CreateNew, FileAccess.Write, FileShare.None))         {             using (CryptoStream cryptoStream = new CryptoStream(destination, transform, CryptoStreamMode.Write))             {                 using (FileStream source = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.Read))                 {                     source.CopyTo(cryptoStream);                 }             }         }     } 
like image 82
HABO Avatar answered Sep 21 '22 14:09

HABO


This may help

/// Encrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> private void EncryptFile(string inputFile, string outputFile) {      try     {         string password = @"myKey123"; // Your Key Here         UnicodeEncoding UE = new UnicodeEncoding();         byte[] key = UE.GetBytes(password);          string cryptFile = outputFile;         FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);          RijndaelManaged RMCrypto = new RijndaelManaged();          CryptoStream cs = new CryptoStream(fsCrypt,             RMCrypto.CreateEncryptor(key, key),             CryptoStreamMode.Write);          FileStream fsIn = new FileStream(inputFile, FileMode.Open);          int data;         while ((data = fsIn.ReadByte()) != -1)             cs.WriteByte((byte)data);           fsIn.Close();         cs.Close();         fsCrypt.Close();     }     catch     {         MessageBox.Show("Encryption failed!", "Error");     } }  /// /// Decrypts a file using Rijndael algorithm. ///</summary> ///<param name="inputFile"></param> ///<param name="outputFile"></param> private void DecryptFile(string inputFile, string outputFile) {      {         string password = @"myKey123"; // Your Key Here          UnicodeEncoding UE = new UnicodeEncoding();         byte[] key = UE.GetBytes(password);          FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);          RijndaelManaged RMCrypto = new RijndaelManaged();          CryptoStream cs = new CryptoStream(fsCrypt,             RMCrypto.CreateDecryptor(key, key),             CryptoStreamMode.Read);          FileStream fsOut = new FileStream(outputFile, FileMode.Create);          int data;         while ((data = cs.ReadByte()) != -1)             fsOut.WriteByte((byte)data);          fsOut.Close();         cs.Close();         fsCrypt.Close();      } } 

source: http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C

like image 30
Muhammad Alaa Avatar answered Sep 20 '22 14:09

Muhammad Alaa