How to register a global hotkey for your application in C#

How to register a global hotkey for your application in C#

Register a hotkey for your application that can be triggered even if your form is minimized and does not have focus. More »

How to download a file in C# (progressbar and download speed)

How to download a file in C# (progressbar and download speed)

Learn how to download files in C# while displaying the percentage and the download speed. More »

UDP hole punching implementation in C#

UDP hole punching implementation in C#

Learn how to implement UDP hole punching so you can make your clients life a lot easier by not forcing them to open ports on their end. More »

 

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

Our snippet for decrypting the file

 

Usage examples:
Encrypt

Example

Decrypt

Example

 

Parts of the above code can be trimmed out by quite a bit (the while loop as an example) by using:

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.

Share on FacebookTweet about this on TwitterShare on Google+Share on StumbleUponShare on LinkedInShare on RedditPin on PinterestShare on TumblrDigg thisPrint this pageEmail this to someone

18 Responses to How to encrypt and decrypt files in C#

  1. Baris Karakas says:

    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

  2. Bhavana says:

    Hi CooLMinE how can i decrypt 1GB file fastly i,e within 20secs. Please guide me.

    thanks in advance

  3. Parag Vidhate says:

    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/

  4. Manaat says:

    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.

  5. Andy says:

    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.

    • CooLMinE says:

      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

      • Andy says:

        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:

        • Neo says:

          Hello how i can use this with my application that can hide files?
          this my code:

  6. Ali says:

    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…

  7. Ed says:

    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.

    • CooLMinE says:

      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.

  8. Ed says:

    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?

  9. Ed says:

    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?

    • CooLMinE says:

      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:

  10. Olli Warelius says:

    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!

Leave a Reply

Your email address will not be published. Required fields are marked *