标签:odi ati equals res ram param log util random
Java实现MD5的随机加盐加密,这样以来就很难解密了,必须使用原密码才能正常的登录系统了,以下为Java实现的MD5随机加盐加密,以及使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转:
1 package com.dq.online.onlinezuul.util; 2 3 import org.apache.commons.codec.binary.Hex; 4 5 import java.security.MessageDigest; 6 import java.util.Random; 7 8 /** 9 * @Author Allen.Lv 10 * @Description //TODO 11 * @Date 13:43 2019/4/1 12 * @Desc: Coding Happy! 13 **/ 14 public class Md5Utils { 15 16 /** 17 * 加盐MD5加密 18 * <p> 19 * 20 * @Title : getSaltMD5 21 * </p> 22 * <p> 23 * @Description : TODO 24 * </p> 25 */ 26 public static String getSaltMD5(String password) { 27 // 生成一个16位的随机数 28 Random random = new Random(); 29 StringBuilder sBuilder = new StringBuilder(16); 30 sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999)); 31 int len = sBuilder.length(); 32 if (len < 16) { 33 for (int i = 0; i < 16 - len; i++) { 34 sBuilder.append("0"); 35 } 36 } 37 // 生成最终的加密盐 38 String Salt = sBuilder.toString(); 39 password = md5Hex(password + Salt); 40 char[] cs = new char[48]; 41 for (int i = 0; i < 48; i += 3) { 42 cs[i] = password.charAt(i / 3 * 2); 43 char c = Salt.charAt(i / 3); 44 cs[i + 1] = c; 45 cs[i + 2] = password.charAt(i / 3 * 2 + 1); 46 } 47 return String.valueOf(cs); 48 } 49 50 /** 51 * 使用Apache的Hex类实现Hex(16进制字符串和)和字节数组的互转 52 * <p> 53 * 54 * @Title : md5Hex 55 * </p> 56 * <p> 57 * @Description : TODO 58 * </p> 59 */ 60 // @SuppressWarnings("unused") 61 private static String md5Hex(String str) { 62 try { 63 MessageDigest md = MessageDigest.getInstance("MD5"); 64 byte[] digest = md.digest(str.getBytes()); 65 return new String(new Hex().encode(digest)); 66 } catch (Exception e) { 67 e.printStackTrace(); 68 System.out.println(e.toString()); 69 return ""; 70 } 71 } 72 73 74 /** 75 * 验证加盐后密码是否还相同 76 * @param password 77 * @param md5str 78 * @return 79 */ 80 public static boolean getSaltverifyMD5(String password, String md5str) { 81 char[] cs1 = new char[32]; 82 char[] cs2 = new char[16]; 83 for (int i = 0; i < 48; i += 3) { 84 cs1[i / 3 * 2] = md5str.charAt(i); 85 cs1[i / 3 * 2 + 1] = md5str.charAt(i + 2); 86 cs2[i / 3] = md5str.charAt(i + 1); 87 } 88 String Salt = new String(cs2); 89 return md5Hex(password + Salt).equals(String.valueOf(cs1)); 90 } 91 92 }
参考文献:
https://blog.csdn.net/Hello_World_QWP/article/details/78913096
标签:odi ati equals res ram param log util random
原文地址:https://www.cnblogs.com/javallh/p/10635982.html