Base64_encode different between Java and PHP

送分小仙女□ 提交于 2019-12-02 12:46:59

问题


Here is my problem :

I have a JAVA function to generate an encrypted string. I have to do the same thing in PHP.

My Java function :

String generateSignature () {
    byte[] Sequence = ("hello").getBytes("UTF-8");
    Mac HMAC = Mac.getInstance("HMACSHA256");
    HMAC.init("SECRET_KEY");
    byte[] Hash = HMAC.doFinal(Sequence);
    String Signature = new String(Base64.encodeBase64(Hash));
    return Signature;
}

My PHP function :

function generateSignature() {
    $sequence = "hello";
    $encrypted = hash_hmac('sha256', $sequence, "SECRET_KEY");
    return base64_encode($encrypted);
}

The return value of the two functions are not the same. What I noticed is that before the encoding to base 64, both functions have the same result. So, for me the problem is not on the generation of the key but on the encoding.

Anybody able to help please ?


回答1:


The answer is in the documentation for the PHP function hash_hmac.

When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.

Pass "true" as the final argument. Hashes are binary. When turning them into strings, they are often encoded in hexadecimal. But in this case you are going to base-64 encode it, so you want the raw binary form.



来源:https://stackoverflow.com/questions/11002603/base64-encode-different-between-java-and-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!