**Using the Cryptography APIs in .NET**

Pages: 1, 2, **3**

The following code snippet shows how to use the `SymmetricEncryption()`

and `SymmetricDecryption()`

functions to encrypt and decrypt a string:

```
'---encrypt the string---
Dim cipherText As String = _
SymmetricEncryption("This is a string", key, IV)
Console.WriteLine("Ciphertext: " & cipherText)
'---decrypt the string---
Console.WriteLine("Original string: " & _
SymmetricDecryption(cipherText, key, IV))
```

Figure 2 shows the output.

*Figure 2. Symmetric encryption and decryption in action*

### Asymmetric Encryption

Private key encryption requires the key used in the encryption process to be kept a secret. A more effective way to transport secret messages to your intended recipient is to use asymmetric encryption (also known as *public key encryption*). In public key encryption, there is a pair of keys involved. This pair, consisting of a private and a public key, is related mathematically such that messages encrypted with the public key can only be decrypted with the corresponding private key. The contrary is true; messages encrypted with the private key can only be decrypted with the public key. Let's see an example for each scenario.

Before you send a message to Susan, Susan needs to generate the key pair containing the private key and the public key. Susan then freely distributes the public key to you (and all her other friends) but keeps the private key to herself. When you want to send a message to Susan, you use her public key to encrypt the message and then send it to her. Upon receiving the encrypted message, Susan proceeds to decrypt it with her private key. In this case, Susan is the only one who can decrypt the message, since the key pair works in such a way that only messages encrypted with the public key can be decrypted with the private key. Also, there is no need to exchange secret keys, thus eliminating the risk of compromising the secrecy of the key.

The reverse can happen. Suppose Susan now sends a message encrypted with her private key to you. To decrypt the message, you need the public key. The scenario may seem redundant, since the public key is not a secret; everyone knows it. But using this method guarantees that the message has not been tampered with and it indeed comes from Susan. If the message had been modified, you would not be able to decrypt it. The fact that you can decrypt the message using the public key proves that the message has not been modified.

In computing, public key cryptography is a secure way to encrypt information. However, it is computationally expensive, as it is time-consuming to generate the key pairs and to perform encryption and decryption. It is usually used for encrypting a small amount of sensitive information.

For public key (asymmetric) encryptions, the .NET framework supports the DSA and RSA algorithms. To demonstrate asymmetric encryption, I will use the RSA algorithm. To do so, I have created the following `AsymmetricEncryption()`

function. This function takes in two parameters: the string to be encrypted and the public key:

```
Private Function AsymmetricEncryption( _
ByVal str As String, _
ByVal publicKey As String) _
As String
'---Creates a new instance of RSACryptoServiceProvider---
Try
Dim RSA As New RSACryptoServiceProvider
'---Loads the public key---
RSA.FromXmlString(publicKey)
Dim EncryptedStr() As Byte
'---Encrypts the string---
EncryptedStr = RSA.Encrypt(ASCII.GetBytes(str), _
False)
'---Converts the encrypted byte array to string---
Return System.Convert.ToBase64String(EncryptedStr)
Catch err As Exception
Console.WriteLine(err.ToString)
Return String.Empty
End Try
End Function
```

The encrypted string is returned in the Base64 encoding. To decrypt a string encrypted with the public key, define the following `AsymmetricDecryption()`

function. This function takes in two parameters: the encrypted string and the private key. It returns the decrypted string.

```
Private Function AsymmetricDecryption( _
ByVal str As String, _
ByVal privateKey As String) As String
Try
'---Creates a new instance of RSACryptoServiceProvider---
Dim RSA As New RSACryptoServiceProvider
'---Loads the private key---
RSA.FromXmlString(privateKey)
'---Decrypts the string---
Dim DecryptedStr As Byte() = _
RSA.Decrypt(System.Convert.FromBase64String(str), False)
'---Converts the decrypted byte array to string---
Return ASCII.GetString(DecryptedStr)
Catch err As Exception
Console.WriteLine(err.ToString)
Return String.Empty
End Try
End Function
```

The following code snippet shows how to use the `AsymmetricEncryption()`

and `AsymmetricDecryption()`

functions to encrypt and decrypt a string:

```
Dim publicKey, privateKey As String
Dim RSA As New RSACryptoServiceProvider()
'---get public key---
publicKey = RSA.ToXmlString(False)
Console.WriteLine("Public key: " & publicKey)
Console.WriteLine()
'---get private and public key---
privateKey = RSA.ToXmlString(True)
Console.WriteLine("Private key: " & privateKey)
Console.WriteLine()
'---encrypt the string---
Dim cipherText As String = _
AsymmetricEncryption("This is a string", publicKey)
Console.WriteLine("Ciphertext: " & cipherText)
Console.WriteLine()
'---decrypt the string---
Console.WriteLine("Original string: " & _
AsymmetricDecryption(cipherText, privateKey))
Console.WriteLine()
```

You can obtain the public and private keys generated by the RSA algorithm by using the `ToXmlString()`

method from the `RSACryptoServiceProvider`

class. This method takes in a Boolean variable, and returns a public key if the value `False`

is supplied. If the value `True`

is supplied, it returns both the private and public keys.

Figure 3 shows the output.

*Figure 3. Asymmetric encryption and decryption in action*

### Summary

In this article, I have covered some of the common functions that you will perform when you are securing your .NET applications. As the .NET framework provides implementation for all the major cryptography algorithms, there is no reason why you should not spend some time incorporating these security features into your .NET applications.

*
Wei-Meng Lee
(Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
*

Return to Windows DevCenter.