This section describes the two Java MD5 encryption methods.
1. The first is with ava. Security. The MessageDigest class, the use of simple method is as follows:
* MD5 encryption * @param Input String to be encrypted * @returnReturns the encrypted string */ publicstatic String generateMD5(String input) throws NoSuchAlgorithmException {
// Get the MD5 confidential instance
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] byteArr = md5.digest(input.getBytes(StandardCharsets.UTF_8));
return byte2hex(byteArr);
}
Copy the code
public static String byte2hex(byte[] b) {
StringBuilder hs= new StringBuilder();
String stmp="";
for (byte value : b) {
// To keep the number of binary machines constant, &0xff is required
stmp = (Integer.toHexString(value & 0XFF));
// If there is only one digit, you need to add 0 to make up for two digits
if(stmp.length() == 1) {
hs.append("0").append(stmp);
}else{ hs.append(stmp); }}return hs.toString();
}
Copy the code
There are a few details to note when converting an encrypted array to a String: (1) You can’t use new String(byte[] b) directly, because the String is garbled because the array is not encoded by a String. (2) Converting a single byte into a hexadecimal string requires the integer.tohexString (int num) method, which cannot be passed directly to byte data. If a byte value is passed directly, the value will first be converted upward to int. Since Java keeps the decimal value unchanged when converting byte to int, it is possible to change the complement when byte is negative. For example, the binary complement of (byte)-10 is 1111 0110, which corresponds to the hexadecimal string f6. Int 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0110, the corresponding string fffffff6, so we need to operate on byte data: &0xff to set the height 24 to 0 to ensure that the resulting string is what we want. (3)
if(stmp.length() == 1) {
hs.append("0").append(stmp);
}else {
hs.append(stmp);
}
Copy the code
To ensure that each byte is converted to a two-digit string, you need to prefix 0 with only one byte. For example integer.tohexString (10) ==>a, which needs to be preceded by a 0.
2. The second method is to use Guava’s tool class. This method is simple and practical
Public static String generateMD5(String input) public static String generateMD5(String input) Throws UnsupportedEncodingException {/ / get the MD5 confidential instance return of Hashing. The MD5 () hashBytes (input. GetBytes (" utf-8 ")). The toString (); }Copy the code