[英]Convert hash_hmac into android java
I'm trying to convert this php function: 我正在尝试转换此php函数:
string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = false ] )
where algo = SHA-256, data = dd-mm-yyy, key = "password" 其中算法= SHA-256,数据= dd-mm-yyy,密钥=“密码”
I have write a code with Message Digest that calculate sha-256 on the concatenation data + key, but the output it's different form the output of php function. 我已经用Message Digest编写了一个代码,该代码计算了连接数据+键上的sha-256,但是输出与php函数的输出不同。
Any help for write this php function into android java? 任何将此PHP函数写入android java的帮助吗?
In fact, I set for String key a personal password and for String sa date. 实际上,我为String键设置了个人密码,并为String设置了日期。 Now when I run the app and generete the hmacsha256 that I add to a url get, the value hmacSha256 that I print it's different form a hmacSha256 calculate into iOS. 现在,当我运行该应用程序并生成添加到URL中的hmacsha256时,生成的hmacSha256值与在iOS中计算的hmacSha256不同。
I used this code adapted from one answer : 我使用了从一个答案改编的这段代码:
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;
}
But when I print hmacSha256(sdf,PRIVATE_KEY), my output is: 76934121da91e03df3ca531057cdca132ebc7fe37ba60fc12da11dba285e3ba2 但是当我打印hmacSha256(sdf,PRIVATE_KEY)时,我的输出是:76934121da91e03df3ca531057cdca132ebc7fe37ba60fc12da11dba285e3ba2
and this value it's different respect to hmacSha256 genereted by iOS. 这个值与iOS发行的hmacSha256不同。 What is wrong here. 怎么了
This is how I did a HmacSHA256 implementation: 这是我执行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) {
// ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.