Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a strong HMACSHA256 key in C#

Tags:

c#

hmac

I'm looking to implement HMACSHA256 request signing in an API I'm building. From what I understood from https://www.rfc-editor.org/rfc/rfc4868, it's best that the secret key be the same number of bits as the hashing algorithm (i.e. SHA256 secret keys should be 256 bits/32 bytes).

Can I use one of the many different random number generators out there for C# or is there a specific way that these keys need to be generated.

Lastly, Amazon Web Services uses HMACSHA256, but they secret keys they provide (at least to me) is 320 bits/40 bytes (when the key is converted to bytes using UTF-8, see https://github.com/aws/aws-sdk-net/blob/master/AWSSDK/Amazon.Runtime/Internal/Auth/AWS4Signer.cs#L205-L232). Is there a reason to use more than needed by the hashing algorithm since it's truncated?

like image 814
Omar Avatar asked Jul 10 '13 16:07

Omar


1 Answers

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

var hmac = new HMACSHA256();
var key = Convert.ToBase64String(hmac.Key);
like image 81
Omar Avatar answered Sep 17 '22 16:09

Omar