MD5Util:
private static String encode(String codeOriginalText) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
byte[] byteArray = null;
try {
byteArray = codeOriginalText.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
切记byteArray = codeOriginalText.getBytes("utf-8");必须要utf-8,不管是请求加密者还是接收请求加密者,今天是对接口要MD5,参数有中文,找了半天的原因,搞半天是MD5工具出了问题。
多说一句,不太喜欢在工具类里判断参数为null的情况,传参参数正常与否应该由调用者负责。