用户在注册账户时,通常在后端的业务部分会对用户的密码进行加密处理,大多采用 md5 + salt + 散列。盐是一定长度的随机乱码(字母、数字、特殊符号),每次都是随机生成的,所以可以写一个随机盐生成类来完成随机盐的生成。
public class SaltUtils {
public static String getSalt(int n){
char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
"1234567890!@#$%^&*()_+").toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++){
//Random().nextInt()返回值为[0,n)
char aChar = chars[new Random().nextInt(chars.length)];
sb.append(aChar);
}
return sb.toString();
}
}
其中参数n为盐的长度。SaltUtils.getSalt()来调用。