Alan Godoi
Alan Godoi

Reputation: 667

SHA1 encryption and SHA1 to Hex in php

I have two methods in Java and I want to do the same methods in php. I don't know absolutely nothing in php. How can I do it?

Method 1:

public static String encyptPassword (String in) throws UnsupportedEncodingException, NoSuchAlgorithmException{
    byte[] bytes=in.getBytes("UTF-8");
    MessageDigest md=MessageDigest.getInstance(MGF1ParameterSpec.SHA1.getDigestAlgorithm());
    md.update(bytes);
    byte[] digest=md.digest();
    return toHex(digest);
}

Method 2:

public static String toHex(byte[] bytes) {
    BigInteger bi = new BigInteger(1, bytes);
    return String.format("%0" + (bytes.length << 1) + "x", bi);
}

The methods (function?) in php must have the same result as in java, because it's hashing passwords for a working and online login system.

I'm trying it about 3 hours, but I can't do it or found a solution. I think I read all posts on Stack. Can you help me? Thanks.

Upvotes: 2

Views: 2923

Answers (2)

Mi-Creativity
Mi-Creativity

Reputation: 9654

PHP Fiddle - hit run to see the result

<?php

    $pass = 'MySecretP@55';
    $hashed = hash("SHA512", $pass);
    echo $hashed;
    echo '<hr>' . bin2hex($hashed);

?>

Above is sha512, which is certainly better that sha1, and bcrypt with reasonably high cost is considered as the best currently

Upvotes: 3

Sammitch
Sammitch

Reputation: 32232

  1. Hashing != Encryption
  2. SHA1 is weak, SHA2 is better, bcrypt is currently the best generally-available hashing algorithm for password storage.
  3. $myHash = hash("SHA1", "foobar") Docs
  4. Don't use #3, use $myActuallySecureHash = password_hash("foobar") Docs
  5. Use #4.
  6. PHP < 5.4 is not an excuse.

Upvotes: 2

Related Questions