Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL MD5 and Java MD5 not equal

The next function in MySQL

MD5( 'secret' ) generates 5ebe2294ecd0e0f08eab7690d2a6ee69

I would like to have a Java function to generate the same output. But

public static String md5( String source ) {
    try {
        MessageDigest md = MessageDigest.getInstance( "MD5" );
        byte[] bytes = md.digest( source.getBytes("UTF-8") );
        return getString( bytes );
    } catch( Exception e )  {
        e.printStackTrace();
        return null;
    }
}

private static String getString( byte[] bytes ) {
    StringBuffer sb = new StringBuffer();
    for( int i=0; i<bytes.length; i++ ) {
        byte b = bytes[ i ];
        sb.append( ( int )( 0x00FF & b ) );
        if( i+1 <bytes.length ) {
            sb.append( "-" );
        }
    }
    return sb.toString();
}

generates

94-190-34-148-236-208-224-240-142-171-118-144-210-166-238-105
like image 417
Sergio del Amo Avatar asked Jun 23 '09 17:06

Sergio del Amo


1 Answers

Rather than reinventing the wheel, try Apache commons codec (http://commons.apache.org/codec/) which will handle the hex encoding for you with Hex.encodeHex(byte[])

private String encodeAsMD5(String password) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(password.getBytes());
        return new String(Hex.encodeHex(bytes));
    } 
    catch(Exception e) {
        e.printStackTrace();
        return null;
    }
}
like image 123
James Frost Avatar answered Oct 02 '22 12:10

James Frost