Reference Rewriter: Error: type `System.Security.Cryptography.HMACSHA1` doesn't exist in target fram

I am using Unity 5, Build Platform Windows Store Apps.
I am Using The following code.

public static string ComputeHmac(string input, byte[ ] key)
{
HMACSHA1 myhmacsha1 = new HMACSHA1(key);
byte[ ] byteArray = Encoding.UTF8.GetBytes(input);
MemoryStream stream = new MemoryStream(byteArray);
return Convert.ToBase64String(myhmacsha1.ComputeHash(stream));
}

This works fine in Unity 4.3, but not working in Unity 5. I am using HMACSHA1 for making signature, it is very important for me, if this is not supported by windows store apps then any alternative/workaround.

Any help would be appreciated.

thanx.

Look at this topic - c# - Working with hmacsha256 in windows store app - Stack Overflow, it might provide some hints, just don’t forget to wrap that function with NETFX_CORE

1 Like

Hello Tomas,
If I use HMACSHA256, the error is still exists and says HMACSHA256 doesn’t exist in target framework.
What I have to do for solving my problem. Is there any alternative to achive this.
Thanx.

Do you have Compilation Overrides set to .NET Core ?

Yes it is, but i also tried None and Use Net Core Partially. The error is same nothing changed.

Can you show the full code?

I already shared the full code in My Post above, this is a method takes two params (string, byte[ ]).
The code is not more than that.

If Compilation Overrides is set to Use Net Core, you should have seen an error:
error CS0246: The type or namespace name ‘HMACSHA1’ could not be found (are you missing a using directive or an assembly reference?)

And that’s normal, because HMACSHA1 doesn’t exist in .NET for Windows Store Apps. You have to use Windows Store API , like it’s suggested in stackoveflow link:

#if NETFX_CORE
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
#endif

....

#if NETFX_CORE
    private string GetSHA256Key(byte[] secretKey, string value)
    {
        var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
        var hash = objMacProv.CreateHash(secretKey.AsBuffer());
        hash.Append(CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8));
        return CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());
    }
#endif

Thank you very much Tomas. The error is solved now.
But I just wanted to know that, did this code works from dll. Means #if NETFX_CORE tag works in dll.
Thanks.

If dll is compiled against .NET Core, then yes - NETFX_CORE will be defined. You can check it yourself, go to VS 2013->New->Project->Visual C#->Store Apps->Windows Apps->Class Library