2

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.

jerdiggity
  • 3,655
  • 1
  • 29
  • 41
Alan Godoi
  • 657
  • 1
  • 12
  • 39
  • Be aware that hashing passwords with SHA* is unsecure, especially unsalted, because it is ways too fast. SHA1 can be brute forced with a speed of [30 Giga SHA1/second](http://hashcat.net/oclhashcat/#performance), that's why one should use a slow hash function with a cost factor like BCrypt or PBKDF2. – martinstoeckli Nov 27 '15 at 07:55

2 Answers2

3

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

Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
  • Thank you all for helping me. I choose your response because you told me how to hash and how to hex it. @Sammitch is a good answer with pretty good link that I will study. gregn3 give the same response. Again, thank you all. – Alan Godoi Nov 27 '15 at 02:09
  • You welcome and I'm glad it helped, what @Sammitch wrote considered best practices, `sha1` produces 40 characters and for easy and known passwords it's so crack-able with brute-force or rainbow or such techniques, there are several websites that offers "*decrypting*" them for free, i.re: https://hashkiller.co.uk/sha1-decrypter.aspx, `sha512` is a better it produces 128 characters, but if you use it with dynamic salting that improves it much better, the new built-in password_hash($string) is currently a best choice . enjoy coding – Mi-Creativity Nov 27 '15 at 02:25
2
  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.
Community
  • 1
  • 1
Sammitch
  • 30,782
  • 7
  • 50
  • 77