What should I do if java md5 is inconsistent? Solution to the problem of inconsistent Java Chinese character md5 values
Recommended tutorial: "java learning"
Get an encrypted value through the main method test, and call it through the servlet request An encrypted value is obtained, which encrypts the same Chinese characters, but the results are different.
If it is encrypted English, there will be no such problem.
The reason lies in the Chinese character encoding. When encrypting, set the encoding to UTF-8 and the problem is solved.
public static String EncoderByMd5(String str) { String result = ""; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); // 这句是关键 md5.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } byte b[] = md5.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); return result; }
The above is the detailed content of What to do if java md5 is inconsistent. For more information, please follow other related articles on the PHP Chinese website!