julienpar
julienpar

Reputation: 13

Base64_encode different between Java and PHP

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 ?

Upvotes: 1

Views: 6726

Answers (1)

John Watts
John Watts

Reputation: 8885

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.

Upvotes: 2

Related Questions