[英]php base64_encode hash_hmac and java gives different results
I saw some same questions in stack-overflow but it doesn't help me.我在堆栈溢出中看到了一些相同的问题,但这对我没有帮助。
I have this php code我有这个 php 代码
$signature=base64_encode(hash_hmac("sha256", trim($xmlReq), $signature_key, True));
I want to write java equivalent to that and this is my java code.我想编写与它等效的 java,这是我的 java 代码。
public static String encodeXML(String key, String data) {
String result = "";
try {
Mac mac = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
mac.init(secretKeySpec);
result = Base64.encodeBase64String(mac.doFinal(data.getBytes("UTF-8")));
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
log.error("exception occured when encording HmacSHA256 hash");
}
return result;
}
but they give different results.但他们给出了不同的结果。 someone help.
有人帮忙。
Apache Commons Codec Apache Commons 编解码器
import org.apache.commons.codec.binary.Base64;
....
Base64.encodeBase64String(.....);
PHP Test Code: PHP测试代码:
$signature=base64_encode(hash_hmac("sha256", 'Message', 'secret', true));
echo $signature;
Java Test Code: Java测试代码:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class TestJava {
public static void main(String[] args) {
try {
String secret = "secret";
String message = "Message";
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
Base64.Encoder encoder = Base64.getEncoder();
String hash = encoder.encodeToString(sha256_HMAC.doFinal(message.getBytes()));
System.out.println(hash);
} catch (Exception e){
System.out.println("Error");
}
}
}
Output for both should be: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=两者的输出应该是:qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.