MD5 encryption is often used in programming. Java language does not provide native MD5 encrypted string functions like PHP. When MD5 encryption is required, you often need to write it yourself.
The code is as follows:
import java.security.MessageDigest;public class MD5 {//Public salt private static final String PUBLIC_SALT = "demo" ;//Mapping array of numbers to characters in hexadecimal private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};/** * User password encryption, the salt value is: private salt + public salt* @param password Password* @param salt Private salt* @return MD5 encryption string*/public static String encryptPassword(String password,String salt){return encodeByMD5(PUBLIC_SALT+password+salt);}/** * md5 encryption algorithm* @param originString * @return */private static String encodeByMD5(String originString){if (originString != null){try{//Create information summary with the specified algorithm name MessageDigest md = MessageDigest.getInstance("MD5");//Use the specified byte array to last update the digest, and then complete the summary calculation byte[] results = md.digest(originString.getBytes());//Return the obtained byte array into a string and return String resultString = byteArrayToHexString(results); return resultString.toUpperCase();}catch(Exception ex){ex.printStackTrace();}}return null;}/** * Convert the byte array to a hexadecimal string* @param Byte array* @return Hexadecimal string*/private static String byteArrayToHexString(byte[] b){StringBuffer resultSb = new StringBuffer();for (int i = 0; i < b.length; i++){resultSb.append(byteToHexString(b[i]));}return resultSb.toString();}/** Convert a byte into a string in hex form*/private static String byteToHexString(byte b){int n = b;if (n < 0) n = 256 + n;int d1 = n / 16;int d2 = n % 16;return hexDigits[d1] + hexDigits[d2];}}Summarize
The above is all the content of this article about the Java language description of the MD5 encryption tool instance code, and I hope it will be helpful to everyone. Interested friends can continue to refer to other Java-related topics on this website. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!