Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

convert password encryption from java to php

I'm trying to create a PHP version of an existing JSP program, however I'm stuck at the password encryption part.

Could you please tell me how to convert this one? I know it tries to get the md5() but after that, I don't get it. I get lost in the Stringbuffer and for() parts.

Can you help me out?

 public static String encryptPassword( String password ) 
 {
     String encrypted = "";
     try
     {
        MessageDigest digest = MessageDigest.getInstance( "MD5" ); 
        byte[] passwordBytes = password.getBytes( ); 

        digest.reset( );
        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 ] ) );
        }
        encrypted = hexString.toString();
     }
     catch( Exception e ) { }
     return encrypted; 
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iraklis should be right. md5() gives you a hex-encoded output string by default. You only get the unencoded bytes like in Java by passing in TRUE for the optional $raw_output argument.

the lengths range from 29 to 32

Then your Java code has a bug. MD5 hashes are always 128 bits (32 hex digits). Here it is:

hexString.append( Integer.toHexString(0xFF & message[ i ] ) );

this will generate 1 instead of 01 for all bytes below 16. What you have stored is a mangled hash, from which you cannot recover the original MD5 value. If you absolutely must keep this broken data, you will have to reproduce the bug in PHP:

function makeBrokenMD5($s) {
    $hash= md5($s, TRUE);
    $bytes= preg_split('//', $hash, -1, PREG_SPLIT_NO_EMPTY);
    $broken= '';
    foreach ($bytes as $byte)
        $broken.= dechex(ord($byte));
    return $broken;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...