Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

java - HmacSHA256 algorithm in Android API 23

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-

enter image description here

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}
{1}
{2}
{3}
{4}
",
            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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...