Robert
Robert

Reputation: 374

PHP SHA-256 check sum in base64 to match that of Java

I have java program which calculates SHA-256 checksum as follows. For example, if I provide the input abcd123ABCD00-4000 it outputs 0QtyIu4B+lU+TLqM/zfJz5ULVpyXgfLRs5mKXCQvbHM= . It also matches the online check sum calculator.

However the PHP code I used won't match it.

PHP code :

$s = 'abcd123ABCD00-4000';
$signature = base64_encode(hash_hmac("sha256", $s, True)); 
print  base64_encode($signature); 

Output : TWpRM1pEWXpaVFl4TURoallqTXdPRFV6WVRrNU5XVTRNRGxoWkRJMU1XWTVNREk1TnpBeU4ySXhaR0psTW1ZMk16Y3hPRE01WldFelkySXhOalJrWXc9PQ==

Java Code :

private static String getSHA256Hash(String text) {


    String hash = null;
    MessageDigest md = null;


    try {

      md = MessageDigest.getInstance("SHA-256");

      md.update(text.getBytes("UTF-8"));

      byte[] shaDig = md.digest();
      // hash = Hex.encodeHexString(shaDig);
      hash = Base64.encodeBase64String(shaDig);

    } catch (NoSuchAlgorithmException ex) {


    } catch (UnsupportedEncodingException e) {

      e.printStackTrace();
    }
    return hash;

  }

Output : 0QtyIu4B+lU+TLqM/zfJz5ULVpyXgfLRs5mKXCQvbHM=

Here what I want is to get the equivalent result in PHP (i.e to change PHP code to match result of the Java program[ I won't able to change the Java code ]. Any help is appreciated

Upvotes: 2

Views: 4607

Answers (1)

Darsstar
Darsstar

Reputation: 1895

If you use hash() and base64 encode once you get the same result.

$s = 'abcd123ABCD00-4000';
$signature = base64_encode(hash("sha256", $s, True)); 
print  $signature; // 0QtyIu4B+lU+TLqM/zfJz5ULVpyXgfLRs5mKXCQvbHM=

Upvotes: 11

Related Questions