HmacSHA256 algorithm in Android API 23

≯℡__Kan透↙ 提交于 2019-12-12 06:38:57

问题


I am trying to generate hash value in my Android app (API 23). I followed this link- https://developer.android.com/reference/javax/crypto/Mac.html and below code should work as per it.

Mac hmacSha256 = Mac.getInstance("HmacSHA1");

But this gives compile time error-

java.security.NoSuchAlgorithmException

I searched and tried few solutions from across other Stackoverflow posts but they didn't work.

Tried this- MessageDigest digest = MessageDigest.getInstance("SHA-256"); got same error.

My overall intention is to convert the below C# code in Java so I can use it in my Android app-

string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

    verb = verb ?? "";
    resourceType = resourceType ?? "";
    resourceId = resourceId ?? "";

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
            verb.ToLowerInvariant(),
            resourceType.ToLowerInvariant(),
            resourceId,
            date.ToLowerInvariant(),
            ""
    );

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
    string signature = Convert.ToBase64String(hashPayLoad);

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
        keyType,
        tokenVersion,
        signature));
}

So I am just going and converting each line manually step by step and stuck at this point. Any ideas I can make this work?


回答1:


You typed the algorithm incorrectly It's HmacSHA256 not hmacSHA256

You need to be careful when choosing the algorithms because they're case sensitive.

From your snapshot I can see that you used

Mac hmacSHA256 = Mac.getInstance("hmacSHA256");

It's incorrect because you're trying to get the instance of hmacSHA256 witch does not exists!

The correct one would be

Mac hmacSHA256 = Mac.getInstance("HmacSHA245");

The first H should be on caps



来源:https://stackoverflow.com/questions/47678782/hmacsha256-algorithm-in-android-api-23

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!