How to encrypt and decrypt files in C#
The following snippets will allow you to encrypt and decrypt files in C#.
Needless to say there are numerous methods that this can be achieved but for the reasons I will explain at the end I came about using this one in my projects.
Also keep in mind that assuming you want to implement something like this in your project you should extend the error catching to detect invalid key lengths, file locations and so on.
Our snippet for encrypting the file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | private static void EncryptFile(string inputFile, string outputFile, string skey) { try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = ASCIIEncoding.UTF8.GetBytes(skey); /* This is for demostrating purposes only. * Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/ byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey); using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create)) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(inputFile, FileMode.Open)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } } } catch (Exception ex) { // failed to encrypt file } } |
Our snippet for decrypting the file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | private static void DecryptFile(string inputFile, string outputFile, string skey) { try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = ASCIIEncoding.UTF8.GetBytes(skey); /* This is for demostrating purposes only. * Ideally you will want the IV key to be different from your key and you should always generate a new one for each encryption in other to achieve maximum security*/ byte[] IV = ASCIIEncoding.UTF8.GetBytes(skey); using (FileStream fsCrypt = new FileStream(inputFile, FileMode.Open)) { using (FileStream fsOut = new FileStream(outputFile, FileMode.Create)) { using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV)) { using (CryptoStream cs = new CryptoStream(fsCrypt, decryptor, CryptoStreamMode.Read)) { int data; while ((data = cs.ReadByte()) != -1) { fsOut.WriteByte((byte)data); } } } } } } } catch (Exception ex) { // failed to decrypt file } } |
Usage examples:
Encrypt
1 | EncryptFile("Location to the file we want to encrypt", "Location of the encrypted file we want to create", "Password of 16 letters/digits"); |
Example
1 | EncryptFile("C:\\myfile.rar", "c:\\myfileEncrypted.rar", "1234512345678976"); |
Decrypt
1 | DecryptFile("Location of the encrypted file we want to decrypt", "Location of the decrypted file we want to create", "The password we used to encrypt the file"); |
Example
1 | DecryptFile("C:\\myfileEncrypted.rar", "c:\\myfileDecrypted.rar", "1234512345678976"); |
Parts of the above code can be trimmed out by quite a bit (the while loop as an example) by using:
1 2 | byte[] file = File.ReadAllBytes(inputFile); cs.Write(file, 0, file.Length); |
The reason I choose not to do that is because using a while loop allows you to track the progress of the task, in other words, it makes it easier to implement different features like tracking the percentage for task completion or implementing a time left to complete feature.
Hello CoolMine
Thank you so much for the code. I am using this in BluePrism automation software and i have a slight problem. Whenever i use any key other than your test key (namely:1234512345678976) i am having the following error –>”Specified initialization vector (IV) does not match the block size for this algorithm.” This happens when i use shorter or longer key than yours. Your key works perfect though. What can i do to solve this?
Thanks in advance
Hi CooLMinE how can i decrypt 1GB file fastly i,e within 20secs. Please guide me.
thanks in advance
Get a better PC lol
I came across this Program for Converting PlainText into Encrypted Cipher Text. It makes use of Caesar Cipher Technique which is quite simple to understand. In fact, this program is self-explanatory. To understand more about Caesar Cipher Mechanism and to get an overview of the program, visit this link: http://www.codingalpha.com/file-handling-program-to-encrypt-and-decrypt-in-c-programming/
Any chance of decrypting without saving ,I have to decrypt but i don’t want to save file instead i have to decrypt and pass bytes to another process.
Yes, just use MemoryStream instead FileStream.
Hi there, it’s a good example, but very very slow. This is caused by ReadByte() and WriteByte().
It runs at least 10 times faster when you use a buffer with multiple of 16 Byte in size. For example buffer[65536]. Then use Read() and Write() Method instead.
Hello Andy,
Thanks for the feedback.
If I am not mistaken FileStream has an internal buffer of 4096 bytes by default which you can change yourself by simply passing a different value when initializing the object. No need to create separate buffer logic for it.
Source: http://msdn.microsoft.com/en-us/library/47ek66wy%28v=vs.110%29.aspx
Yes, but while benchmarking, I found a bigger buffersize is faster.
At least till 80KB. As soon as it gets bigger there was no improvement and it got even slower with bigger sizes.
You should also consider to use AesCryptoServiceProvider, which is faster than rijndaelManaged and AESManaged. In the example below, I’m using a fixed IV, for simplification. IV should always be random and can be stored along with the ciphertext.
Example decryptor:
Hello how i can use this with my application that can hide files?
this my code:
Hi CooLMinE can you provide me the complete source code that. I cant understand how to design that apllication e.g buttons textbox etc…So Please help me…
If you are not familiar as to how to use methods in general, take a look at http://msdn.microsoft.com/en-us/library/ms173114.aspx. Hopefully that should give you all the basic knowledge you will need to use the above methods.
Ah! … Thank you for your time CooLMinE – I was so busy analyzing the methods, that I didn’t realize I was looking in my temp directory, where I was storing the undecrypted file.
Hey Ed,
I’m glad you managed to find the problem :)
As for your previous question, even a key such as “7)&awhRzu*ZLobP[&:4~39@+`u?HkKZas0d=p7{>N8-{If4}/H1Lq+dY4Xm[+” should work without any issues.
Hmm. I couldn’t find any restrictions on key complexity, so I used 7)&awhRzu*ZLobP[&:4~39@+`u?HkKZas0d=p7{>N8-{If4}/H1Lq+dY4Xm[+ as my key. Too much?
This has been very helpful – it is the most straightforward tutorial on symmetric encryption of a file in C# on the internet. Unfortunately, I can’t get the decryptor to do anything. It seems to be passing through the encrypted file unchanged (viewing the result in notepad is the same as opening the raw encrypted file). I thought, I must be missing something, so I more or less copied your code line for line. What am I missing here?
Hello Ed,
I can’t duplicate your problem. How are you calling the methods ? Do you have any exceptions thrown ?
By using your methods I set a class variable to
I create a test file called “test.txt” with “This is a test message to test the output of the methods.” as the content of the file and call the methods as follows:
It took me time to learn all the comments, but I honestly loved the blog. It proved to be very advantageous to me and I’m positive to all of the followers here!