Create a strong HMACSHA256 key in C #

I am looking to fulfill the request request HMACSHA256 in the API that I am creating. From what I understood from https://tools.ietf.org/html/rfc4868 , it is best for the private key to be the same number of bits as the hashing algorithm (i.e. SHA256 private keys should be up to 256 bits / 32 bytes).

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

Finally, Amazon Web Services uses HMACSHA256, but the secret keys they provide (at least for me) are 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 the hash algorithm requires since it is truncated?

+6
source share
2 answers

If the key is longer than HMAC support, it will usually be hashed to the desired size. This is mainly for supporting human-readable keys of arbitrary lengths. If you generate the key programmatically and do not need it to be human readable, I would recommend using RandomNumberGenerator . This is basically what it was made for.

 using System.Security.Cryptography; RandomNumberGenerator rng = RandomNumberGenerator.Create(); byte[] data = new byte[32]; rng.GetBytes(data); 
+5
source

One way to create a key (presumably secure):

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

Source: https://habr.com/ru/post/949142/


All Articles