Java SHA256 outputs different hash to PHP SHA256? Java SHA256 outputs different hash to PHP SHA256? php php

Java SHA256 outputs different hash to PHP SHA256?


Well, the very first thing you need to do is use a consistent string encoding. I've no idea what PHP will do, but "jake".getBytes() will use whatever your platform default encoding is for Java. That's a really bad idea. Using UTF-8 would probably be a good start, assuming that PHP copes with Unicode strings to start with. (If it doesn't, you'll need to work out what it is doing and try to make the two consistent.) In Java, use the overload of String.getBytes() which takes a Charset or the one which takes the name of a Charset. (Personally I like to use Guava's Charsets.UTF_8.)

Then persuade PHP to use UTF-8 as well.

Then output the Java result in hex. I very much doubt that the code you've given is the actual code you're running, as otherwise I'd expect output such as "[B@e48e1b". Whatever you're doing to convert the byte array into a string, change it to use hex.


They are printing the same .. convert your byte[] to a hex string, then you'll see CDF30C6B345276278BEDC7BCEDD9D5582F5B8E0C1DD858F46EF4EA231F92731D as Java output, too:

public void testSomething() throws Exception {    MessageDigest md = MessageDigest.getInstance("SHA-256");    md.update("jake".getBytes());    System.out.println(getHex(md.digest()));}static final String HEXES = "0123456789ABCDEF";public static String getHex( byte [] raw ) {    if ( raw == null ) {      return null;    }    final StringBuilder hex = new StringBuilder( 2 * raw.length );    for ( final byte b : raw ) {      hex.append(HEXES.charAt((b & 0xF0) >> 4))         .append(HEXES.charAt((b & 0x0F)));    }    return hex.toString();}


You need to convert the digest to a HEX string before printing it out. Example code can be found here.