dthjnc306679 2018-02-13 14:29
浏览 144
已采纳

Java和PHP中的相同哈希算法给出了不同的结果

I am integrating the same login functionality using same database on java and php platforms but having some problem in password algorithms.

Here is my java code:-

public static String encryptPassword(String strToEncrypt,String saltToEncrypt)      
{
    String encryptedString = "";
    String stringToEncrypt = "";
    byte[] encodedValue;

    stringToEncrypt = strToEncrypt + saltToEncrypt;

    encodedValue = Base64.encodeBase64(DigestUtils.sha256(stringToEncrypt
            .getBytes()));
    encryptedString = new String(encodedValue);

    return encryptedString;
}

Here is my PHP code:-

  function  encryptPassword($strToEncrypt, $saltToEncrypt) 
  {
    $stringToEncrypt = $strToEncrypt.$saltToEncrypt;

    $encodedValue = base64_encode(hash('sha256', $stringToEncrypt));

    return $encodedValue;
 }

Ideally, both of these functions should generate the same encrypted string but these are giving different results. What is wrong with my code? Please advise.

  • 写回答

1条回答 默认 最新

  • dongmin1166 2018-02-13 16:51
    关注

    It's because the SHA-256 functions do not use the same format for the return value. The hash function in PHP returns a hex string by default, but you can choose to output the raw string using the RAW_OUTPUT parameter (reference here) :

    $encodedValue = base64_encode(hash('sha256', $stringToEncrypt, TRUE)); 
    

    Alternatively, you may change the Java side and use a method named sha256Hex in Apache Commons Codec which takes a String and returns the hash in hexadecimal :

    // You don't need the getBytes here
    encodedValue = Base64.encodeBase64(DigestUtils.sha256Hex(stringToEncrypt)); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?