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();
}
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With