0

I'm trying to make a hash in php but I cant get the correct hash.

The java code is:

if (sPassword == null || sPassword.equals("")) {
        return "empty:";
    } else {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(sPassword.getBytes("UTF-8"));
            byte[] res = md.digest();
            return "sha1:" + StringUtils.byte2hex(res);



        } catch (NoSuchAlgorithmException e) {
            return "plain:" + sPassword;
        } catch (UnsupportedEncodingException e) {
            return "plain:" + sPassword;
        }
    }

Can somebody translate this to php?

For example if I put in Java the following pass: 123456789, The hash is: sha1:625D7360E198F528978A4D061F3420923AF867C5.

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75

2 Answers2

0

The PHP has an sha1() function, your code should be something like this:

<?php
    if ($sPassword == null || $sPassword == "")
    {
        return "empty:";
    }
    else
    {
        if (!function_exists("sha1"))
        {
            return "plain:" . $sPassword;
        }
        else
        {
            return "sha1:" . strtoupper(sha1($sPassword));
        }
    }
?>

The strtoupper() is needed to make the hash uppercase as the sha1() returns it in lowercase. I believe the function_exists("sha1") will always return false as the sha1() is a built-in function. But maybe with some specific build options you can get rid of it.

Just a note: sha1() will give you a hash for empty passwords.

Gábor Héja
  • 458
  • 7
  • 17
  • Thanks, this code gives me sha1 hash: f7c3bc1d808e04732adf679965ccc34ca7ae3441 for input 123456789.And i need: sha1:625D7360E198F528978A4D061F3420923AF867C5. – user3430586 Mar 17 '14 at 20:51
  • Are you sure that's the hash for "123456789"? I've checked the hash on a site with an sha1 hash database and it says the input is ".adgjmptw" (which is correct for the PHP version). Could you try another input and share the results here? – Gábor Héja Mar 17 '14 at 21:06
  • It is interesting that the characters of ".adgjmptw" are three steps away from each other in the ASCII table (excluding the "."), it seems that the `.getBytes("UTF-8")` is doing some unexpected things to the input string. – Gábor Héja Mar 17 '14 at 21:15
0

simply try this:

   <?PHP
        $sPassword  =   "enter-password-here";
        if(!empty($sPassword)) {
            return sprintf("sha1 hash: %s", sha1($sPassword));
        } else {
            return "empty";
        }
    ?>
Sidstar
  • 354
  • 2
  • 6
  • since we are using "return" I believe this code is part of a user defined `function()` – Sidstar Mar 17 '14 at 20:42
  • Thanks, this code gives me sha1 hash: f7c3bc1d808e04732adf679965ccc34ca7ae3441 for input 123456789.And i need: sha1:625D7360E198F528978A4D061F3420923AF867C5. – user3430586 Mar 17 '14 at 20:52