Sending encrypted messages with .NET

Davor Lozić
December 26th, 2016.

1. Introduction

When you need to send a message securely, AES[1] encryption (also known as Rijndael) is a way go. This article will not explain how AES works as a standard but how to encrypt and decrypt a message with AES encryption within .NET. In System.Core assembly is a System.Security.Cryptography namespace where we can use classes like AesCryptoServiceProvider or AesManaged. After the encryption process, cipertext variable will contain the encrypted text.

First we need to introduce some fundamentals:

This process can be formulated as:

C = Ek(P)
P = Dk(C)

2. Encryption

Encrypting a message means converting a plaintext into a cyphertext. Class AesCryptoServiceProvider performs symmetric encryption and decryption using the Cryptographic Application Programming Interfaces (CAPI) implementation of the Advanced Encryption Standard (AES) algorithm[2]. CryptoStream class defines a stream that links data streams to cryptographic transformations[3].

    
public void EncryptMessage(string plaintext)
{
    SymmetricAlgorithm aes = new AesCryptoServiceProvider();
    aes.KeySize = 256;

    MemoryStream ms = new MemoryStream();

    var cs = new CryptoStream(
      ms,
      aes.CreateEncryptor(),
      CryptoStreamMode.Write
    );

    using (var writer = new StreamWriter(cs)) { writer.Write(plaintext); }

    byte[] ciphertext = ms.ToArray();
}
  
  

3. Decryption

Decrypting a message means converting a cyphertex to plaintext. Instead of CryptoStreamMode.Write and StreamWriter, when decrypting a message you use CryptoStreamMode.Read and StreamReader.

  
private static string DecryptMessage(
  byte[] key, byte[] iv, byte[] ciphertext)
{
    SymmetricAlgorithm aes = new AesCryptoServiceProvider();
    MemoryStream ms = new MemoryStream(encryptedMessage);

    var cs = new CryptoStream(
      ms,
      aes.CreateDecryptor(key, iv),
      CryptoStreamMode.Read
    );

    string plaintext = null;
    using (var reader = new StreamReader(cryptoStream))
    {
        plaintext = reader.ReadToEnd();
    }
}
  
  

One question left is how to get an initialization vector and the key? If you look at the EncryptMessage, we created a key with keysize of 256 bits.

  
SymmetricAlgorithm aes = new AesCryptoServiceProvider();
aes.KeySize = 256;

// key and initialization vector
byte[] key = aes.Key;
byte[] iv = aes.IV;
  
  

4. Conclusion

Implementation within AesCryptoServiceProvider with a combination of a CryptoStream provides easy encryption and decryption of messages. Source code of AesCryptoServiceProvider[4] and CryptoStream[5] is also available.

5. Literature


  1. Announcing the ADVANCED ENCRYPTION STANDARD (AES)
  2. AesCryptoServiceProvider Class
  3. CryptoStream Class
  4. AesCryptoServiceProvider.cs
  5. cryptostream.cs