Exact hashing in Java as PHP with salt? (SHA-256)

I can just hash in PHP with salt:

$orig_pw = "abcd";
$salt = 5f8f041b75042e56;
$password = hash('sha256', $orig_pw . $salt);

(This is not how I implement it, this is just an example. Salt is different for everyone)

And at the same time the saved password:

bc20a09bc9b3d3e1fecf0ed5742769726c93573d4133dbd91e2d309155fa9929

But if I try to do the same in Java, I get a different result. I triedString password = "abcd";

byte[] salt = hexStringToByteArray("5f8f041b75042e56");

try {
    System.out.println(new String(getHash(password, salt)));
} catch (NoSuchAlgorithmException e1) {
    e1.printStackTrace();
}

And two methods:

public byte[] getHash(String password, byte[] salt) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.reset();
        digest.update(salt);
        try {
            return digest.digest(password.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }


public byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

Result:

/¬1¶ĆĽëüFd?[$?¶»_9ËZ»ç¶S‘Ęŗש

The encoding in hex is not close to it:

2fac31b6434c14ebfc46643f5b243fb6bb5f39cb5abb10e7b65391454c97d7a90d0a

Can anyone help with this?

+4
source share
2 answers

, , , PHP , , Java , MessageDigest. , , . :

PHP: → () → SHA-256
Java: → (unhex) → SHA-256

Java-, . - PHP, Java, .

PHP:

String password = "abcd";
String salt = "5f8f041b75042e56";

try {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");

    return digest.digest((password + salt).getBytes("UTF-8"));
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
    return null;
}

:

60359BC8A0B09898335AA5A037B1E1B9CE3A1FE0D4CEF13514901FB32F3BCEB0

PHP:

<?
echo hash('sha256', "abcd"."5f8f041b75042e56");
?>

.

+7

,

digest.update(salt);
digest.digest(password.getBytes("UTF-8"));

:

hash('sha256', $salt . $orig_pw);

, . ?

+2

Source: https://habr.com/ru/post/1548319/


All Articles