3

I have a simple application in PHP which uses the following code to hash the password and store it in a 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, produces the following password to store in the db: $1$ad$BH3wnQs1wym28vdzP8zyh1

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

thr33pwood
  • 31
  • 5
  • 1
    if you dont need to use md5 for what ever app your building, try sha1 its much more secure then md5 and im sure java would support that – Lawrence Cherone May 21 '11 at 22:25
  • Does this help? http://stackoverflow.com/questions/415953/generate-md5-hash-in-java – jbrookover May 21 '11 at 22:27
  • I thought that by using the following code String password = MD5Crypt.crypt("1234","a"); System.out.println(password); I would have what I needed, but it doesn't work, I guess because I am not importing the right package? – thr33pwood May 21 '11 at 23:32
  • Finally I got that working with the following code: String password = MD5Crypt.crypt("1234","a"); System.out.println(password); I just had to create also the MD5Crypt.class . Thanx for the answers all – thr33pwood May 22 '11 at 00:49

1 Answers1

0

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);

Also, you can change "MD5" to "SHA1" and should work too.

Imanol Luengo
  • 15,366
  • 2
  • 49
  • 67
  • 1
    this seems to be working, but it is actually what md5("1234") does in PHP. I am looking for a way to 'represent' what crypt($password, $salt) does in PHP, although I could just use this code and change the way i store the password in the db. – thr33pwood May 21 '11 at 23:29