2

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.

  • Follow this [link](https://stackoverflow.com/questions/1391613/best-way-to-encode-passwords-in-php), you're question has been answered – Sterli Feb 13 '18 at 14:32
  • 1
    No it hasn't, that question is totally unrelated to this one. – Erwin Bolwidt Feb 13 '18 at 14:33
  • 2
    show us the result –  Feb 13 '18 at 14:36
  • 2 things: `DigestUtils.sha256(stringToEncrypt.getBytes())` might produce a different result than `DigestUtils.sha256(stringToEncrypt)` due to endianess and PHP `hash` returns a hex string and not raw bytes. To get raw bytes from PHP pass a 3rd argument `hash('sha256', $stringToEncrypt, true)` – apokryfos Feb 13 '18 at 14:41

1 Answers1

0

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)); 
ttzn
  • 2,543
  • 22
  • 26