How to implement Cryptography using .net?
The science of cryptography has been around for many years, even long before computers. Our history having the proof that this is not a new concept. Earlier emperor using encryption-decryption techniques to send secret messages. They used some symbolic patterns, signals and different way to change the message and only the person having the meaning or we can say that know the way to decrypt that message only understand the message.
In other words, we all know a game named “Jumble Word”. In which we replace a word with another like for “Jumble” we replace j with l, u with w, m with o, b with d, l with n and e with g. If a person understands the logic (shift letter by 2) of replacing the letters only he/she can understand the actual word. This is the way to achieve cryptography. We need to understand cryptography in detail to know how is it work. Let’s move forward…
Cryptography in Detail
Cryptography is a process of encrypting a message from a readable format, referred to as “plaintext”, into an unreadable one, or “ciphertext”. The process of changing it back to a readable format known as decrypting, which is not possible in most of the cases.
For example, sometimes we want to send some information to others without other people knowing what we’re sharing. To secure the information, we encrypt it into ciphertext with the help of an encryption key. When the receiver receives that ciphertext, he/she can decrypt the ciphertext using an encryption key.
Shuffling of meaningful characters into non-meaningful characters so that the person who does not have the access to the data can’t read that message also fall under this process. So, before going for the whole concept of the Cryptography firstly talk about why Cryptography and what are the concerns of the cryptography?
Concerns of the Cryptography
In the digital world, when you share your sensitive data over a network there are chances of data theft or unauthorized access to data. So to secure data from the theft or any unauthorized access we use cryptography. So in this way the major reason to use cryptography is…
- Confidentiality (It means that the information cannot be understood by anyone).
- Integrity (It means that the Information cannot be altered in storage when in transit between sender and the intended receiver without the alteration).
- Non-repudiation (Sender of the information cannot deny at a later stage his or her intentions in the transmission of the information).
- Authentication (The sender and the receiver can confirm each other’s identity and the destination of the information).
In combination, we can say security of data and privacy of data is the main reason to use this concept. Cryptography is the art and science of hiding the messages to introduce confidentiality in information security. The word ‘Cryptography‘ instituted by consolidating two Greek words, ‘Krypto‘ which means hidden and ‘graphene‘ which means writing. Implementation of the cryptography is not a child’s play. It requires strong mathematical concept and algorithms knowledge. It is a complex aspect for the developer. There are some terminologies used in cryptography that are as follows:
- Plain Text (Ordinary text, Cleartext, Readable text)
- Cipher Text (Encrypted text, Unreadable text)
Now comes the process of cryptography…
How does it work?
- Data that can be readable without any special measures or we can say that without any extra efforts called ‘plaintext’ or ‘cleartext’.
- The method of converting plaintext in such a way as to hide its meaning is called ‘Encryption’.
- The encryption of the plaintext (cleartext) into the unreadable/un-understandable form of data called ‘Ciphertext’.
- And the process of converting ciphertext to its original plaintext is called ‘Decryption’.
- A ‘key’ is a string of bits used for encrypting and decrypting the message to be transmitted. It is a randomly generated set of numbers or characters that are used to encrypt/ decrypt information.
So, after the understanding of cryptography and its terminology let’s know about the types of cryptography.
Types of Cryptography
There are two types of cryptography are as follows:
- Private Key Encryption
- Public Key Encryption
Private Key Encryption
Private key encryption also referred as symmetric key encryption. This form of encryption was firstly used by military organizations to convey secret messages. This type of encryption requires sharing a common key between the sender and the receiver of the message. With private-key encryption, a sender encrypts a secret message using a key that is shared by the sender with the receiver to decrypt the data. Private-key cryptography is effective only if the key can be kept as secret.
Here, sender and the receiver are using the same key to encrypt and decrypt data. This is the reason that this type of cryptography also called as a single key or conventional key encryption. Symmetric key encryption uses a different type of algorithms so that cryptography can be achieved. Name of the algorithms are as follows:
- 3DES (Triple DES)
AES algorithm used as a standard algorithm of the symmetric key encryption.
Public Key Encryption
Public key encryption is based on the idea that each sender and the receiver has its own private key. This key was only known to him/her. This key can be known by anyone. Each encryption and decryption process requires at least one public key and one private key.
Each public and private key mathematically connected with each other so that messages encrypted with a public key can only be decrypted with the corresponding private key. Here, the sender of the message uses the public key of the receiver to encrypt the data. This type of encryption is the combination of a public and private key that is why it also called as the asymmetric key encryption. There are different algorithms used to achieve the asymmetric cryptography. So the names of the algorithms are as follows:
- Elliptic Curve
RSA algorithm is the most common algorithm used to implement cryptography. Elliptic Curve appears to be the next standard. So, now the most awaited part of the article came…Do you know what it is? Let me tell you this is the implementation part of the cryptography using .net…
Implementation of Cryptography in .net
.NET framework provides a set of cryptographic objects like hashing, algorithms, encryption, and generating digital signatures with numbers of language. These objects are used by .NET to support internal services. It also provides support to developers to implement a cryptographic application. We are going to use c# language in this implementation.
This walkthrough shows how to encrypt and decrypt the content of a file. We are going to use Windows Forms application for this implementation. It only demonstrates the fundamentals of the encryption and decryption. It does not demonstrate the real world scenario like using smart cards. This practice follows some guidelines including:
- First is RijndaelManaged class. It is a symmetric algorithm that encrypts and decrypt data by using Key and IV which is automatically generated by it.
- Second is RSACryptoServiceProvider. It is an asymmetric algorithm that encrypts and decrypt the key to the data that encrypted by RijndaelManaged class.
This process divided into 9 tasks. So the name of the tasks are as follows:
- Creating a Windows Forms application
- Declaring global objects
- Creating an asymmetric key
- Encrypting a file
- Decrypting a file
- Getting a private key
- Exporting a public key
- Importing a public key
- Testing the application
Namespaces/References we need to add to our application.
So, let’s start with the first task…
Creating a Windows Forms application
Designing part is the most important part of the implementation of any application. So, let’s start with it. I have used sharp developer in this implementation. You can use visual studio as well. In this task, we need a fresh project with an appropriate name as I have used cryptography you can give it accordingly. So, add a solution with some controls like 6 buttons 1 label and 2 openfileDialoge as:
Double click on buttons to generate events.
After adding these controls our window form looks like as shown in figure:
Declaring global objects
In this task, we need to declare global objects in the Form’s constructor. So to do this put this piece of code in the form’s constructor.
Creating an asymmetric key
In this task, an asymmetric key generated that encrypts and decrypts the RijndaelManaged key. This key used to encrypt the content. It also displays the key container name on the label control.
Add code in the event of the button named ButtonCreateAsmKeys as shown in figure:
Encrypting a file
There are two methods involved in this task:
Event Handler Method
This method displays a dialog box for selecting a file and passes the file name to the second method that is Encrypt File method. It uses for the Encrypt File button.
This method performs encryption of a file that passed by the first method named event handler method. All the encrypted content, key, and IV saved to one FilesStream. This FileStream referred to as the encryption package.
This method does the following activities:
- A RijndaelManaged symmetric algorithm created by the method to encrypt the content of the selected file.
- An RSACryptoServiceProvider object also created by the method to encrypt the RijndaelManaged key.
- Uses a CryptoStream object to read and encrypt the FileStream of the source file, in blocks of bytes.
- Determines the lengths of the encrypted key and IV. It also creates byte arrays of their length values.
- It writes the Key, IV, and their length values to the encrypted package (FileStream).
Package (Encryption package) uses the following format:
- Key length, bytes 0 – 3
- IV length, bytes 4 – 7
- Encrypted key
You need to put the code as shown in below figure:
Code for Encrypt File Method:
Decrypting a file
There are two methods involved in this task:
Event Handler Method
A dialog box displayed by this method for selecting a file and passes the file name to the second method that decrypts the file, named Decrypt File method. It used for the decrypt File button.
This method performs decryption of a file that is passed by the first method named event handler method.
This method (decryptFile method) performs the following activities:
- A RijndaelManaged symmetric algorithm created by the method to decrypt the content of the selected file.
- The first eight bytes of the FileStream of the encrypted package read by this method into byte arrays. It obtains the lengths of the encrypted key and the IV from the byte array.
- This method extracts the key and IV from the encryption package (FileStream) into byte arrays.
- An RSACryptoServiceProvider object also created by this method that decrypts the RijndaelManaged key.
- A CryptoStream object used to read and decrypt the ciphertext section of the FileStreamencryption package, in blocks of bytes. Decryption is completed when it finished.
Code for Decrypt File Method:
Exporting a public key
In this task, it saves the key that created by the Create Key button to a file and it exports only the public parameters. We can understand this scenario by comparing it with a popular example of the cryptography that is Alice and Bob example. So let’s compare…
This task matches the scenario of Alice giving Bob her public key. So that Bob can encrypt the file for Alice. Who have that public key will not be able to decrypt the file because they do not have the full key pair with private parameters.
So, you need put the code as shown in the figure:
Importing a public key
In this task, we load key only with the public parameters that created by the Export Public Key button. It also set it as the key container name. Again compare this scenario with Alice and Bob example…
This task matches the scenario where Bob loading Alice’s key with only public parameters so that he can encrypt files for her.
Getting a private key
This task sets the name of the key container as the name of the key created by the Create Keys button. This key container will contain the full key pair with private parameters. Here, we can relate this scenario where Alice using her private key to decrypt the file that decrypted by the Bob.
Testing the application
After completing all the above steps/ task now the time to test the application to check whether it will work appropriately or not. So let’s move forward and start to test it…
This will perform the following testing scenarios.
To create keys, encrypt and decrypt
- Firstly click on the Create Key button. The key name displayed on the label. It also shows that it is a full key pair or not.
- Secondly, you need to click on the Export Public Key button. Exporting the public key parameters does not change the current key.
- After the second step click the Encrypt File button and select a file to perform encryption.
- Click the Decrypt File button and select the file that encrypted in the previous step.
- Check the file that is just decrypted.
- Now close the application and restart it. Now test it for retrieving persisted key containers in the next scenario.
To encrypt using the public key
- Firstly, click the Import Public Key button. The key name displayed on the label. It also shows that it is public only.
- Secondly, click on the Encrypt File button and select a file to encrypt.
- After the second step click the Decrypt File button and select the file that is just encrypted. This action will fail because you must have the private key to decrypt.
To decrypt using the private key
- Firstly, click on the Get private Key button. The name of the key displayed on the label and shows whether it is the full key pair.
- Click on the Decrypt File button and select the file that encrypted by the encrypt file method. This action will be successful because you have the full key pair to decrypt.
So, this was the last step/task of this implementation. Now it is your turn to implement this type of application.
So, in this way, we can see that cryptography is a technique that converts readable text into some symbolic form. We can also say that it converts clear text into an unreadable format. It provides a feature named data security. It helps to secure data when in transit between sender and the receiver.
Cryptography can be achieved with a different type of algorithm but the most commonly used algorithm is RSA also. It can be implemented using different languages. In this blog, we used C# language of the .net framework to implement it. This is a very simple example of a cryptography application.
You can implement your cryptography application and can use it to understand how it will work in both the ways (Private key encryption and Public key encryption)!