将密码加密从java转换为php [英] convert password encryption from java to php

查看:121
本文介绍了将密码加密从java转换为php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建现有JSP程序的PHP版本,但是我被困在密码加密部分。

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

你能告诉我转换一个?我知道它试图获得md5(),但之后,我不明白。我迷失在Stringbuffer和for()部分。

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.

你能帮我吗?

 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; 
 }


推荐答案

Iraklis应该是对的。默认情况下, md5()给出十六进制编码的输出字符串。通过传递 TRUE 可选的 $ raw_output 参数,您只能得到如Java中的未编码字节。

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.


长度范围从29到32

the lengths range from 29 to 32

然后你的Java代码有一个错误。 MD5哈希总是128位(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 ] ) );

这将生成 1 而不是 01 对于16以下的所有字节。您存储的是一个混乱的哈希,从中无法恢复原始的MD5值。如果你绝对必须保留这个破损的数据,你将不得不重现PHP中的错误:

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;
}

这篇关于将密码加密从java转换为php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆