Protecting Confidential Data with Symmetric Encryption

 Apr 01, 2016

A common requirement of many business applications is the protection of confidential data. In today's blog I will introduce you to some of the cryptography features provided by the .NET Framework. In particular we are going to see how to implement symmetric encryption. In subsequent blogs we will consider other techniques.

If you need to store or transmit confidential data you should first encrypt it. Then even if the encrypted data is stolen it would be useless without a key to decrypt it. Of course we must be very protective of the key!

One of the established mathematical algorithms to encrypt/decrypt data is the Symmetric Encryption. It's called symmetric because the same secret key is used to encrypt and decrypt the data. You can measure the strength of an encryption algorithm by the size of the key. The several algorithms provided by the .NET Framework have secret keys varying from 40 to 256 bits.

A well-known symmetric encryption algorithm is the Advanced Encryption Standard (AES). AES has been adopted by the US government in 2002 and is now used worldwide. AES can have keys of 128, 192 or 256 bits. Let's see how to use AES in the .NET Framework.

AES breaks the input text in blocks of the same size and encrypts each block separately. The secret key is used together with a binary sequence known as the initialization vector (IV). The IV ensures that if the same plain text is encrypted many times with the same secret key the encrypted text, known as the cypher text, is always distinct.

The first step is to add a reference to the namespace where the required classes are defined

using System.Security.Cryptography;

Now we need to do some preparation to generate a Secret Key and the Initialisation Vector (IV) as shown next:

string password = "Pa$$w0rd123";
string salt = "s@alt01";
Rfc2898DeriveBytes rgb = new
Rfc2898DeriveBytes(password,
Encoding.Unicode.GetBytes(salt));

The class Rfc2898DeriveBytes is a utility class that generates the secret key and the IV based on the key size and the size of the blocks. In the following code snippet we create an instance of the AesManaged class and then use the Rfc289DerivedBytes to get the key and IV.

AesManaged algorithm = new
AesManaged();
byte[] key =
rgb.GetBytes(algorithm.KeySize / 8);
byte[] iv =
rgb.GetBytes(algorithm.BlockSize / 8);

We are using the default key size which is 256, but we can specify it to be 128, 192 or 256. Now that we have what is needed to create an encryptor object we just call the CreateEncryptor method of our AesManaged instance.

ICryptoTransform encryptor =
algorithm.CreateEncryptor(key, iv);

To use the encryptor we need a CryptoStream together with any other stream where we can write the encrypted bytes as for example a MemoryStream. The next code snippet shows these steps.

MemoryStream bufferStream = new
MemoryStream();
CryptoStream cryptoStream = new
CryptoStream( bufferStream, encryptor,
CryptoStreamMode.Write)

Now we need to transform the confidential piece of text that we need to encrypt (inputMessage) into an array of bytes (arrayMessage)

bytes[] arrayMessage =
Encoding.ASCII.GetBytes(inputMessage);

Finally we can call the Write method of the CryptoStream and complete the encryption process.

cryptoStream.Write(messageBytes , 0,
messageBytes.Length);
cryptoStream.FlushFinalBlock();
cryptoStream.Close();

Note that the cryptoStream is using the MemoryStream instance bufferStream, so after we call the Write method the result to be collected comes from the bufferStream which we could for example use to pass the encrypted stream to another process or simply save it to a file in the file system as the next code snippet shows:

FileStream file = new
FileStream("file.bin", FileMode.Create,
System.IO.FileAccess.Write);
byte[] bytes =
new byte[bufferStream.Length];
bufferStream.Read(bytes, 0,
bufferStream.Length);
file.Write(bytes, 0, bytes.Length);
bufferStream.Close();

How do your Excel skills stack up?   

Test Now  

About the Author:

Newton Godoy  

With over 17 years of in-class training experience and over 16 years of industry experience, Newton offers students a wealth of real-world technical knowledge and expertise in the areas of .NET application development, SQL Server and SharePoint Server. After spending several years lecturing as a professor, Newton found his true calling and began his career as a MCT. He worked as a technical trainer for some of Brazil's and Australia’s largest corporate training organisations before finally finding a home with New Horizons where he is now one of our top trainers. Newton brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. His combination of technical knowledge and instructor experience make him one of the most respected instructors within the IT training industry.

Read full bio
top
Back to top