MySQL MD5和Java MD5不相等

Ser*_*Amo 10 java mysql md5 cryptography cryptographic-hash-function

MySQL中的下一个功能

MD5( 'secret' )生成5ebe2294ecd0e0f08eab7690d2a6ee69

我想有一个Java函数来生成相同的输出.但

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();
}
Run Code Online (Sandbox Code Playgroud)

生成

94-190-34-148-236-208-224-240-142-171-118-144-210-166-238-105
Run Code Online (Sandbox Code Playgroud)

Ran*_*pho 25

尝试在base 16编码.只是为了让你开始...基数16中的94是5E.

**编辑:**尝试更改getString方法:

private static String getString( byte[] bytes ) 
{
  StringBuffer sb = new StringBuffer();
  for( int i=0; i<bytes.length; i++ )     
  {
     byte b = bytes[ i ];
     String hex = Integer.toHexString((int) 0x00FF & b);
     if (hex.length() == 1) 
     {
        sb.append("0");
     }
     sb.append( hex );
  }
  return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)


mih*_*ihi 6

更换

sb.append( ( int )( 0x00FF & b ) );
if( i+1 <bytes.length ) {
    sb.append( "-" );
}
Run Code Online (Sandbox Code Playgroud)

通过

String hex = Integer.toHexString((int) 0x00FF & b);
if (hex.length == 1) sb.append("0");
sb.append( hex );
Run Code Online (Sandbox Code Playgroud)