dharm0us dharm0us - 1 year ago 145
Java Question

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


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();
} } catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download