javaphp加密md5
繼續求助第二波,那位大神能這個Java md5的方法寫個php版的,得加密結果一致的,謝謝了,第一波有位達人寫了一個了,但是加密結果不一樣,大家可以參考下!
java方法描述的思路如下
1.將秘鑰、源串分別轉換byte數組
2.聲明2個64位元組 將key的byte數組分別做異或運算填充進去 並分別補充 54、92 補滿64長度
3.獲得md5摘要演算法的MessageDigest 對象
4.使用其中一個數組及源串的數組更新MessageDigest 摘要 完成雜湊計算
5.重設摘要
6.使用另一個數組更新摘要 使用4中結果 從0到16開始更新摘要 完成雜湊計算
7.轉換字串
方法如下
public String cryptMd5(String source, String key) {
byte[] k_ipad = new byte[64];
byte[] k_opad = new byte[64];
byte[] keyb;
byte[] value;
try { byte[] keyb = key.getBytes("UTF-8");
value = source.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e)
{
byte[] value;
keyb = key.getBytes();
value = source.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, 54);
Arrays.fill(k_opad, keyb.length, 64, 92);
for (int i = 0; i < keyb.length; i++)
{
k_ipad[i] = (byte)(keyb[i] ^ 0x36);
k_opad[i] = (byte)(keyb[i] ^ 0x5C);
}
MessageDigest md = null;
try
{
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException e)
{
return null;
}
md.update(k_ipad);
md.update(value);
byte[] dg = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg); }
public static String toHex(byte[] input)
{
if (input == null) {
return null;
}
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++)
{
int current = input[i] & 0xFF;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
下面這個是上次提問達人寫的,加密結果和Java的還是不一致
function cryptMd5($source, $key) {
if(! mb_check_encoding($source, 'utf-8')) $source = mb_convert_encoding($source, "utf-8", "auto");
if(! mb_check_encoding($key, 'utf-8')) $key = mb_convert_encoding($key, "utf-8", "auto");
$k_ipad = str_pad($key, 64, chr(54));
$k_opad = str_pad($key, 64, chr(92));
for($i=0; $i $k_ipad{$i} = $key{$i} ^ chr(0x36);
$k_opad{$i} = $key{$i} ^ chr(0x5c);
}
$dg = md5($source . substr($k_ipad, strlen($source)), true);
$dg = md5(substr($dg, 0, 16) . substr($k_opad, 16), true);
return bin2hex($dg);
}