PHP中的MD5功能与Android/Java等效吗? [英] What will be the Android/Java equivalent of MD5 function in PHP?
本文介绍了PHP中的MD5功能与Android/Java等效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在如下计算Android/Java中的MD5:
I am calculating the MD5 in Android/Java as follows:
byte raw[] = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0; i<raw.length; i++)
hexString.append(Integer.toHexString(0xFF & raw[i]));
v_password = hexString.toString();
但是与PHP的md5()
函数不匹配.
However there's a mismatch with PHP's md5()
function.
MD5 - PHP - Raw Value - catch12 - 214423105677f2375487b4c6880c12ae
MD5 - JAVA - Raw Value - catch12 - 214423105677f2375487b4c688c12ae
这是怎么引起的,我该如何解决,以便Android/Java和PHP都生成完全相同的MD5哈希?
How is this caused and how can I solve it so that the both Android/Java and PHP generate exactly the same MD5 hash?
推荐答案
当字节小于0x10
时,您需要在0
前面添加十六进制值的前缀.这是一个完整的示例:
You need to prefix hex value with 0
when the byte is less than 0x10
. Here's a full example:
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
int i = (b & 0xFF);
if (i < 0x10) hex.append('0');
hex.append(Integer.toHexString(i));
}
return hex.toString();
}
这篇关于PHP中的MD5功能与Android/Java等效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文