Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of PHP's crypt function in Java

I am migrating my PHP code to Google App Engine - Java.
So I need an equivalent of PHP's crypt function in Java,
since I have stored all the passwords of registered users
using crypt in my DB.

Edit 1: Here is my php code for encrypting passwords :

$password = "test123";
$pwd = crypt($password,$password);
echo $pwd;

Output is (On Windows as well as a linux based server on HostMonser):
temjCCsjBECmU

Can someone give me equivalted java code?
I have tried various permutations & combinations with
MessageDigest class, but can't get it right..

Edit 2:
Here is sample code which I thought would work but did not:

try {
                {
                    String password = "test123";
                    MessageDigest digest = MessageDigest.getInstance( "MD5" ); 
                    byte[] passwordBytes = password.getBytes( ); 

                    digest.reset( );
                    digest.update( passwordBytes );
                    digest.update( passwordBytes );
                    byte[] message = digest.digest( );

                    StringBuffer hexString = new StringBuffer();
                    for ( int i=0; i < message.length; i++) 
                    {
                        hexString.append( Integer.toHexString(
                            0xFF & message[ i ] ) );
                    }
                    String encrypted = hexString.toString();
                    System.out.println(encrypted);
                  } } catch (NoSuchAlgorithmException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
like image 609
simplfuzz Avatar asked Jul 20 '10 16:07

simplfuzz


2 Answers

This is an old thread but I ran into the same issue and found a different solution. You can use the UnixCrypt/Md5Crypt classes in the Apache Commons Codec 1.7 library.

For example you can call

UnixCrypt.crypt(string, salt)

OR

Md5Crypt.md5Crypt(byte[], salt)

I haven't looked into the other encryption types but I imagine their are other utilities as well.

  • org.apache.commons.codec.digest.UnixCrypt
  • org.apache.commons.codec.digest.Md5Crypt
like image 179
karc Avatar answered Sep 30 '22 07:09

karc


You have to know what implementation of PHP crypt has been used (MD5? SHA256? SHA512?) because there are several, depending on your OS : http://php.net/manual/fr/function.crypt.php

The Java equivalent class is MessageDigest. When you create an instance of this class, you provide the hash algorithm, for example :

MessageDigest md = MessageDigest.getInstance("MD5");
MessageDigest md2 = MessageDigest.getInstance("SHA-256");
MessageDigest md3 = MessageDigest.getInstance("SHA-512");
// etc.
byte[] encryptedPassword = md.digest("yourPassword".getBytes());
like image 26
Benoit Courtine Avatar answered Sep 30 '22 06:09

Benoit Courtine