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)); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Fluent udf 编写问题
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500
  • ¥15 氧化掩蔽层与注入条件关系
  • ¥15 Django DRF 如何反序列化得到Python对象类型数据
  • ¥15 多数据源与Hystrix的冲突