mercredi 19 décembre 2018

C# / Generate a 1024 bits symmetric key for HMAC-SHA256

Here is the way to generate a symmetric key for HMAC-SHA256 encryption, that is needed, for example, in using JWT Security Tokens when providing a REST API :

        private static void GenerateEncryptionKey()
        {
            RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider();
            byte[] keyForHmacSha256 = new byte[64];
            cryptoProvider.GetNonZeroBytes(keyForHmacSha256);
            StringBuilder hex = new StringBuilder(keyForHmacSha256.Length * 2);
            foreach (byte b in keyForHmacSha256)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            Console.WriteLine(hex.ToString());
        }

An example of output is composed of 128 bytes, that means 128x8 bits, so 1024 bits :
"401b09eab3c013c48a54922bb802bec8fd531819211125f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f59d3ed1"

You could then copy and paste this generated key into your Token Validation Handler if needed for this purpose...