问题
I currently have been given the following java code snippet as an example of how to calculate a hash based on a supplied 'in' and 'salt' variable. In these examples the variables are hardcoded for testing:
package generatehash;
import java.security.MessageDigest;
import sun.misc.BASE64Encoder;
public class GenerateHash {
public static void main(String[] args)
{
String in = "abcdef12345";
String salt = "test1";
try {
MessageDigest hash = MessageDigest.getInstance("SHA-256");
byte[] digest = hash.digest((in + salt).getBytes());
String out = new BASE64Encoder().encode(digest);
System.out.println("Calculated: " + out);
} catch(java.security.NoSuchAlgorithmException e) {
System.err.println("SHA-256 is not a valid message digest algorithm. " + e.toString());
}
}
}
The output here is:
Calculated: bfiUcT46ftaC76MCbGbpCFisFSlEY96/4CBwdtznaCE=
When attempting to run the PHP equivalent I tried the following:
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$in = 'abcdef12345';
$salt = 'test1';
$out = hash('sha256', $in.$salt);
echo 'Calculated: ' . $out;
The output here is completely different:
Calculated: 6df894713e3a7ed682efa3026c66e90858ac15294463debfe0207076dce76821
I've tried a number of variations but not hitting the mark. Is there something I'm missing here? Any help would be greatly appreciated.
回答1:
The Java result is in base64 while the php result is in hex. You missed the step of base64 encoding the raw PHP result .
$in = 'abcdef12345';
$salt = 'test1';
$out = hash('sha256', $in.$salt,true); //3rd parameter says return raw result
echo 'Calculated: ' . base64_encode($out);
Outputs:
Calculated: bfiUcT46ftaC76MCbGbpCFisFSlEY96/4CBwdtznaCE=
Example: http://sandbox.onlinephpfunctions.com/code/bb12ed98c16e2b732f29292da75aeebc36da2d48
来源:https://stackoverflow.com/questions/44963287/how-to-reproduce-java-messagedigest-sha-256-hash-in-php