MD5加密本身是不可逆的,无法对加密之后的报文进行解密。一般用作签名算法,用来检查报文是否被窜改。实际应使用加盐加密来确保数据的安全性。
import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.security.MessageDigest; /** * MD5算法不可逆,用于校验报文窜改 */ public class MD5Utils { private static final Logger LOGGER = LoggerFactory.getLogger(MD5Utils.class); private static final char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private static final String MD5 = "MD5"; private static final String ENCODING = "UTF-8"; /** * MD一次加密 * @param string 待加密内容 * @return */ public static String getMD5(String string){ if(StringUtils.isBlank(string)){ LOGGER.info("MD5 encrypt string is null"); return null; } try { //获得待加密内容的字节数组 byte[] bytes = string.getBytes(ENCODING); //初始化加密工具类 MessageDigest md5 = MessageDigest.getInstance(MD5); md5.update(bytes); byte[] digest = md5.digest(); int j = digest.length; char str[] = new char[j * 2]; int k = 0; for (int i = 0; i < j; i++) { byte byte0 = digest[i]; str[k++] = hexDigits[byte0 >>> 4 & 0xf]; str[k++] = hexDigits[byte0 & 0xf]; } return new String(str); } catch (Exception e) { LOGGER.info(e.getMessage()); return null; } } /** * MD5二次加密 * @param string 待加密内容 * @return */ public static String getMd5X2(String string){ return getMD5(getMD5(string)); } /** * MD5多次加密 * @param string 待加密内容 * @param times 加密次数 * @return */ public static String getMd5Times(String string, int times){ for(int i = 0; i < times; i++){ string = getMD5(string); } return string; } /** * MD5加盐加密 * @param string 待加密的内容 * @param salt 盐 * @return */ public static String getMD5WithSalt(String string, String salt){ return getMD5(string + salt); } public static void main(String[] args) { String str = "MD5测试"; String s = getMD5(str); System.out.println("MD5一次加密:" + s); System.out.println("MD5二次加密:" + getMd5X2(str)); String withSalt = getMD5WithSalt(str, "123456"); System.out.println("MD5一次加盐加密:" + withSalt); } }