Basics: Use of MessageDigest class
In fact, to complete MD5 encryption in Java, most of the MessageDigest class will help you implement it, and a few lines of code are enough:
/** * Encrypt the string md5* * @param str * @return */import java.security.MessageDigest;public static String getMD5(String str) { try { // Generate an MD5 encryption calculation digest MessageDigest md = MessageDigest.getInstance("MD5"); // Calculate the md5 function md.update(str.getBytes()); // digest() finally determines that the md5 hash value returns, and the return value is 8 as a string. Because the md5 hash value is a 16-bit hex value, it is actually an 8-bit character // BigInteger function converts an 8-bit string into a 16-bit hex value, and represents it as a string; gets the hash value in the form of a string return new BigInteger(1, md.digest()).toString(16); } catch (Exception e) { throw new SpeedException("MD5 encryption error occurred"); }} Advanced: Encryption and decryption
Java implements MD5 encryption and decryption classes, with test classes, see the code for details.
MD5 encryption and decryption class - MyMD5Util, the code is as follows
package com.zyg.security.md5;import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.security.SecureRandom;import java.util.Arrays;public class MyMD5Util { private static final String HEX_NUMS_STR="0123456789ABCDEF"; private static final Integer SALT_LENGTH = 12; /** * Convert hex strings into byte array* @param hex * @return */ public static byte[] hexStringToByte(String hex) { int len = (hex.length() / 2); byte[] result = new byte[len]; char[] hexChars = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1])); } return result; } /** * Convert the specified byte array into a hex string* @param b * @return */ public static String byteToHexString(byte[] b) { StringBuffer hexString = new StringBuffer(); for (int i = 0; i < b.length; i++) { String hex = Integer.toHexString(b[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } hexString.append(hex.toUpperCase()); } return hexString.toString(); } /** * Verify whether the password is legal* @param password * @param passwordInDb * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { //Convert the hex string format password into byte array byte[] pwdInDb = hexStringToByte(passwordInDb); //Declare the salt variable byte[] salt = new byte[SALT_LENGTH]; //Extract the salt from the byte array saved in the database System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); //Create the message digest object MessageDigest md = MessageDigest.getInstance("MD5"); //Pause the salt data into the message digest object md.update(salt); //Pass the password data to the message digest object md.update(password.getBytes("UTF-8")); //Generate the message digest of the input password byte[] digest = md.digest(); //Declare a variable that saves the message digest of the password in the database byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; //Get the message digest of the password in the database System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); //Compare whether the message digest generated based on the input password is the same as the message digest in the database if (Arrays.equals(digest, digestInDb)) { //Password correctly returns password matching message return true; } else { //Password incorrect returns password mismatch message return false; } } /** * Get the encrypted hexadecimal password* @param password * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException */ public static String getEncryptedPwd(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { //Declare the encrypted password array variable byte[] pwd = null; //Random number generator SecureRandom random = new SecureRandom(); //Declare the salt array variable byte[] salt = new byte[SALT_LENGTH]; //Put the random number into the salt variable random.nextBytes(salt); //Declare the message digest object MessageDigest md = null; //Create the message digest md = MessageDigest.getInstance("MD5"); //Pause the salt data into the message digest object md.update(salt); //Pass the data of the password to the message digest object md.update(password.getBytes("UTF-8")); //Get the byte array of the message digest byte[] digest = md.digest(); //Because salt is to be stored in the byte array of the password, add the byte length of the salt pwd = new byte[digest.length + SALT_LENGTH]; //Copy the bytes of the salt to the first 12 bytes of the generated encrypted password byte array, so as to get the salt out when verifying the password System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); //Copy the message digest to the bytes in the encrypted password byte array starting from the 13th byte System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); //Convert the password encrypted byte array format into a hexadecimal string format password return byteToHexString(pwd); }}Test class - Client, the code is as follows:
package com.zyg.security.md5;import java.io.UnsupportedEncodingException;import java.security.NoSuchAlgorithmException;import java.util.HashMap;import java.util.Map;public class Client { private static Map users = new HashMap(); public static void main(String[] args){ String userName = "zyg"; String password = "123"; registerUser(userName,password); userName = "changong"; password = "456"; registerUser(userName,password); String loginUserId = "zyg"; String pwd = "1232"; try { if(loginValid(loginUserId,pwd)){ System.out.println("Welcome to login!!!"); }else{ System.out.println("Password error, please re-enter!!!"); } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Registered user* * @param userName * @param password */ public static void registerUser(String userName,String password){ String encryptedPwd = null; try { encryptedPwd = MyMD5Util.getEncryptedPwd(password); users.put(userName, encryptedPwd); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Verification login* * @param userName * @param password * @return * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException */ public static boolean loginValid(String userName,String password) throws NoSuchAlgorithmException, UnsupportedEncodingException{ String pwdInDb = (String)users.get(userName); if(null!=pwdInDb){ // This user exists return MyMD5Util.validPassword(password, pwdInDb); }else{ System.out.println("This user does not exist! ! ! "); return false; } }}PS: Here are two more MD5 encryption tools for you. Interested friends can refer to it:
MD5 online encryption tool:
http://tools.VeVB.COM/password/CreateMD5Password
Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tool:
http://tools.VeVB.COM/password/hash_md5_sha