2

Refer to this question for background.

Hashing using algorithms like SHA-256 in Java and PHP produce the same result when the string given is in English, but how can I make the two languages produce the same result when the input is in a language other than English (like Chinese for example)?

Java

public static String encodePassword(String password) {
    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(password.getBytes("UTF-8")); //I've tried messing around with the encoding
        String result = "";
        for(int i : hash) {
            result += String.format("%02x", 0xff & i);
            }
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

PHP

For PHP I use the hash function:

hash("sha256", $password);

Output (with input as 国)

Java

Encoding set to UTF-8: d1566afa505af0f03b9156d0a9a518a25c2d4568b095ef4ee2dca7fcbb6c29c9

Encoding set to iso-8859-1: 8a8de823d5ed3e12746a62ef169bcf372be0ca44f0a1236abc35df05d96928e1

PHP

e1c8436bc8529d791d58c74fefa160dfd678ca8db8f879b8392a42be84f78db3

Community
  • 1
  • 1
KILL3RTACO
  • 75
  • 9
  • 1
    Can you post the code you are using to generate both and show a case where it doesn't match up? – Justin L. Sep 11 '13 at 04:34
  • 2
    Assuming correct implementations, SHA-256 will produce the same hash for the same binary input on all platforms. If you suspect otherwise, make sure the binary representation of the text is the same on all the platforms you're using. – Michael Petrotta Sep 11 '13 at 04:36

1 Answers1

0

This might help.

public static String SHA(String text)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    MessageDigest md;
    md = MessageDigest.getInstance("SHA-256");
    byte[] md5 = new byte[64];
    md.update(text.getBytes("iso-8859-1"), 0, text.length());
    md5 = md.digest();
    return convertedToHex(md5);
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Jhanvi
  • 5,069
  • 8
  • 32
  • 41