Android API 23中的HmacSHA256算法

时间:2017-12-06 16:13:20

标签: java c# android sha256

我正在尝试在我的Android应用中生成哈希值(API 23)。我按照这个链接 - https://developer.android.com/reference/javax/crypto/Mac.html,下面的代码应该按照它工作。

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

但是这会给出编译时错误 -

enter image description here

  

java.security.NoSuchAlgorithmException

我搜索并尝试了其他Stackoverflow帖子中的一些解决方案,但它们没有用。

试过这个 - MessageDigest digest = MessageDigest.getInstance("SHA-256");得到了同样的错误。

我的总体意图是在Java中转换下面的C#代码,以便我可以在我的Android应用程序中使用它 -

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));
}

所以我只是一步一步地手动转换每一行并坚持到这一点。我可以做任何想法吗?

1 个答案:

答案 0 :(得分:0)

您输入的算法不正确 它的HmacSHA256不是hmacSHA256

选择算法时需要小心,因为它们区分大小写。

从快照中我可以看到您使用了

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

这是不正确的,因为您试图获取hmacSHA256的实例并不存在!

正确的是

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

第一个 H 应该在上限