How to implement php crypt_md5 in java

I have a simple PHP application that uses the following code to hash a password and store it in db.

<?php
$user_name = "admin";
$password = "1234";
$salt = substr($user_name, 0, 2);
$salt = '$1$' . $salt . '$'; //$salt = $1$ad$
$crypt_password = crypt($password, $salt);
echo $crypt_password;
?>

this code creates the following password to store in db: $ 1 $ ad $ BH3wnQs1wym28vdzP8zyh1

I'm trying to make exactly the same code with Java, but since I'm new to Java, I have a lot of difficulties. I checked here http://www.java2s.com/Open-Source/Java-Document/Groupware/LibreSource/md5/MD5Crypt.java.htm#cryptStringString and it seems like this is what I need, but I failed make it work. Any help would be greatly appreciated. Thank you in advance.

+3
source share
1 answer

If md5 works for you, you can try the following code:

    String pass = "1234";
    MessageDigest crypt = null;

    try {
        crypt = java.security.MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        System.out.println("MD5 not supported");
        return; // depends on your method
    }

    byte[] digested = crypt.digest(pass.getBytes());
    String crypt_password = new String();

    // Converts bytes to string
    for (byte b : digested) 
        crypt_password += Integer.toHexString(0xFF & b);

    System.out.println(crypt_password);

, "MD5" "SHA1" .

0

All Articles