【问题标题】:Convert hash_hmac into android java将 hash_hmac 转换为 android java
【发布时间】:2015-07-05 21:48:01
【问题描述】:

我正在尝试转换这个 php 函数:

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )

其中算法 = SHA-256,数据 = dd-mm-yyy,密钥 = “密码”

我用 Message Digest 编写了一个代码,它在连接数据 + 键上计算 sha-256,但输出与 php 函数的输出不同。

对将这个php函数写入android java有什么帮助吗?

事实上,我为 String key 设置了个人密码,为 String s 设置了日期。现在,当我运行应用程序并生成我添加到 url 的 hmacsha256 时,我打印它的值 hmacSha256 与 hmacSha256 计算到 iOS 中的值不同。

我使用了这个改编自一个答案的代码:

String PRIVATE_KEY = (String) "asf";
String dateInString = "2015-04-26";  // Start date
String sdf = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String Token = (String) sdf + PRIVATE_KEY;

private static String toHexString(final byte[] bytes) {
    final Formatter formatter = new Formatter();
    for (final byte b : bytes) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

public static String hmacSha256(final String PRIVATE_KEY, final String sdf) {
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(PRIVATE_KEY.getBytes(), "HmacSHA256"));
        return toHexString(mac.doFinal(sdf.getBytes()));
    }
    catch (final Exception e) {
        // ...
    }
    return PRIVATE_KEY;
}

但是当我打印 hmacSha256(sdf,PRIVATE_KEY) 时,我的输出是:76934121da91e03df3ca531057cdca132ebc7fe37ba60fc12da11dba285e3ba2

这个值与 iOS 生成的 hmacSha256 不同。这里有什么问题。

【问题讨论】:

  • 在 Stack Overflow 中,您应该编辑您的问题以添加相关信息,并且切勿将其放入答案中。并且您应该添加 iOS 产生的价值,以帮助其他人了解可能发生的事情。

标签: java php android sha


【解决方案1】:

这就是我执行 HmacSHA256 的方式:

private static String toHexString(final byte[] bytes) {
    final Formatter formatter = new Formatter();
    for (final byte b : bytes) {
        formatter.format("%02x", b);
    }
    return formatter.toString();
}

public static String hmacSha256(final String key, final String s) {
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256");
        return toHexString(mac.doFinal(s.getBytes()));
    }
    catch (final Exception e) {
        // ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多