DEV Community

Meow
Meow

Posted on • Edited on

AES-GCM Encryption with C#

Here is example how can you use encryption with AES GCM with C#. Its currently supported in .NET Core 3.0, 3.1 and .NET Standard 2.1. For .NET Framework you will need to use CBC. This code and more is awailable in my nuget package MayMeow.Cryptography.

So How to encrypt data?



 public static byte[] Encrypt(byte[] toEncrypt, byte[] key, byte[] associatedData = null)
{
    byte[] tag = new byte[KEY_BYTES];
    byte[] nonce = new byte[NONCE_BYTES];
    byte[] cipherText = new byte[toEncrypt.Length];

    using (var cipher = new AesGcm(key))
    {
        cipher.Encrypt(nonce, toEncrypt, cipherText, tag, associatedData);

        return Concat(tag, Concat(nonce, cipherText));
    }
}


Enter fullscreen mode Exit fullscreen mode

This will create byte array which looks like this

Tag Nonce Encrypted Data
16 Bytes 12 bytes ...x bytes

Everything you have to provide is key. Tag and NONCE is different for each data you vant to encrypt and its a part of array.

Function for decrypt data:



public static byte[] Decrypt(byte[] cipherText, byte[] key, byte[] associatedData = null)
{
    byte[] tag = SubArray(cipherText, 0, KEY_BYTES);
    byte[] nonce = SubArray(cipherText, KEY_BYTES, NONCE_BYTES);

    byte[] toDecrypt = SubArray(cipherText, KEY_BYTES + NONCE_BYTES, cipherText.Length - tag.Length - nonce.Length);
    byte[] decryptedData = new byte[toDecrypt.Length];

    using (var cipher = new AesGcm(key))
    {
        cipher.Decrypt(nonce, toDecrypt, tag, decryptedData, associatedData);

        return decryptedData;
    }
}


Enter fullscreen mode Exit fullscreen mode

In those functions i using concat and subarray functions. For merging arrays together and splitting them. they are here:



public static byte[] Concat(byte[] a, byte[] b)
{
    byte[] output = new byte[a.Length + b.Length];

    for (int i = 0; i < a.Length; i++)
    {
        output[i] = a[i];
    }

    for (int j = 0; j < b.Length; j ++)
    {
        output[a.Length + j] = b[j];
    }

    return output;
}


Enter fullscreen mode Exit fullscreen mode


public static byte[] SubArray(byte[] data, int start, int length)
{
    byte[] result = new byte[length];

    Array.Copy(data, start, result, 0, length);

    return result;
}


Enter fullscreen mode Exit fullscreen mode

Theese and more are part of MayMeow.Cryptography repository which is awailable on my Github.

ko-fi

Top comments (0)