Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...