Generate a strong HMACSHA256 key in C#

One way to generate a (presumably secure) key is:

var hmac = new HMACSHA256();
var key = Convert.ToBase64String(hmac.Key);

If a key is longer than the HMAC supports, it'll usually be hashed to the proper size. This is mainly to support human-readable keys of arbitrary length. If you're generating a key programatically and don't need it to be human-readable, I'd recommend using RandomNumberGenerator. This is basically what it was made for.

using System.Security.Cryptography;

using RandomNumberGenerator rng = RandomNumberGenerator.Create();

byte[] data = new byte[32];
rng.GetBytes(data);

Tags:

C#

Hmac