有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Android API 23中的java HmacSHA256算法

我正在尝试在我的Android应用程序(API 23)中生成哈希值。我遵循了这个链接-https://developer.安卓.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) 个答案

  1. # 1 楼答案

    你输入的算法不正确 是HmacSHA256不是HmacSHA256

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

    从您的快照中,我可以看出您使用了

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

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

    正确的答案是

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

    第一个H应该在caps上