我正在使用以下行计算PHP中的MD5(see documentation以获取更多信息):
md5($password, true); // returns raw output
我正在使用以下Java代码:
byte[] bytesOfMessage = password.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
上面的代码不会返回与PHP代码返回的输出相同的输出。
我如何解决Android / Java生成完全相同的MD5与原始输出而不是哈希字符串?
答案 0 :(得分:2)
是。我有同样的问题。我找到了正确的方法:
这相当于PHP的md5(password, true)
:
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public byte[] md5x16(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
String md5Text = new String(md5Bytes); // if you need in String format
// better use md5Bytes if applying further processing to the generated md5.
// Otherwise it may give undesired results.
return md5Bytes;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
等同于PHP的md5(password, false)
:
public static String md5(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
String md5Text = null;
md5Text = bytesToHex(md5Bytes);
return md5Text;
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
如果您需要转换等效的PHP base64_encode(text)
,请使用以下内容:
public String convertToBase64(byte[] bytes) {
try {
String base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
catch (Exception e) {
}
return "";
}
答案 1 :(得分:-1)
我有同样的问题,这是我的Java程序代码:
public static String encryptPassword(String password) {
String hash = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes("UTF-8"));
byte[] raw = md.digest();
hash = (new BASE64Encoder()).encode(raw);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return hash;
}
这是我的PHP代码:
<?php
$str = 'encodeIt';
$toutf8 = utf8_encode($str);
$var = md5($str,true);
echo base64_encode($var);
?>
它们总是返回相同的哈希值。