在​​Android​​开发过程中加密密码常常采用md5加密方式,然而如果服务器端采用php开发(php采用md5加密很简单,直接md5($str)),很可能与java的md5加密不一致。以下方法是md5加密与php一致的源码:


import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
//密码加密 与php加密一致
public static String md5(String input) throws NoSuchAlgorithmException {
String result = input;
if(input != null) {
MessageDigest md = MessageDigest.getInstance("MD5"); //or "SHA-1"
md.update(input.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
result = hash.toString(16);
while(result.length() < 32) { //31位string
result = "0" + result;
}
}
return result;
}
}