How to calculate HMAC-SHA1 authentication code in .NET 4.5 Core
Asked Answered
A

1

5

I’m currently facing a big problem (Environment: .NET 4.5 Core): We need to protect a message with a key using a HMAC-SHA1 algorithm. The problem is that the HMACSHA1-class of the namespace System.Security.Cryptography and the namespace itself do not exist in .NET 4.5 Core, this namespace only exists in the normal version of .NET.

I tried a lot of ways to find an equivalent namespace for our purpose but the only thing I found was Windows.Security.Cryptography which sadly does not offer a HMAC-Encryption.

Does anyone have an idea how I could solve our problem or is there any free to use 3rd-party solution?

Angloindian answered 11/1, 2013 at 13:37 Comment(1)
For clarification, when you refer to .net 4.5 core, you are meaning the win8 api subset of .net 4.5, which is why you don't have access to System.Security.Cryptography?Germany
G
9

The Windows.Security.Cryptography namespace does contain HMAC.

You create a MacAlgorithmProvider object by calling the static OpenAlgorithm method and specifying one of the following algorithm names: HMAC_MD5 HMAC_SHA1 HMAC_SHA256 HMAC_SHA384 HMAC_SHA512 AES_CMAC

http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.core.macalgorithmprovider.aspx

public static byte[] HmacSha1Sign(byte[] keyBytes, string message){ 
    var messageBytes= Encoding.UTF8.GetBytes(message);
    MacAlgorithmProvider objMacProv = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
    CryptographicKey hmacKey = objMacProv.CreateKey(keyBytes.AsBuffer());
    IBuffer buffHMAC = CryptographicEngine.Sign(hmacKey, messageBytes.AsBuffer());
    return buffHMAC.ToArray();

}
Germany answered 11/1, 2013 at 13:43 Comment(1)
Thank you for your quick response. This was helpful I was able to run the CreateHMAC method (described on technet msdn.microsoft.com/en-us/library/windows/apps/xaml/…) successfuly but what I need is something like this: HMAC_SHA1("key", "The quick brown fox jumps over the lazy dog") = 0xde7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9 Do you know how I can retrieve such a hash-value. Thank you in advanceAngloindian

© 2022 - 2024 — McMap. All rights reserved.