我正在尝试转换这个 php 函数:
string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )
其中 algo = SHA-256,数据 = dd-mm-yyy,key =“密码”
我用 Message Digest 编写了一段代码,用于计算串联数据 + key 上的 sha-256,但输出与 php 函数的输出不同。
将这个 php 函数写入 android java 有什么帮助吗?
事实上,我为 String key 设置了个人密码,为 String 设置了日期。现在,当我运行应用程序并生成添加到 URL 的 hmacsha256 时,我打印的 hmacSha256 值与计算到 iOS 中的 hmacSha256 不同。
我使用了改编自一个答案的代码:
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不同。这里出了什么问题。
最佳答案
这就是我实现 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) {
// ...
}
}
关于java - 将 hash_hmac 转换为 android java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29895779/