本文主要是介绍MD5加密技术(加盐),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import org.apache.commons.lang3.StringUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;public class MD5Util {public static void main(String[] args) {//字符串加密String str = "123456";String salt = getSalt();System.out.println(salt);System.out.println(getMD5CodeBySalt(str,salt));}//对字符串进行MD5编码public static String getMD5Code(String str){if(StringUtils.isBlank(str)){return null;}try {//创建具有指定算法名称的信息摘要MessageDigest md = MessageDigest.getInstance("MD5");//使用指定的字节数组对摘要进行最后的更新,然后完成摘要计算byte[] results = md.digest(str.getBytes());//将得到的字节数组编程字符串返回String resultString = byteArrayToHexString(results);return resultString.toUpperCase();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}//对字符串进行MD5编码加盐操作public static String getMD5CodeBySalt(String str,String salt){if(StringUtils.isBlank(str)){return null;}return getMD5Code(getMD5Code(str)+salt);}//转换字节数组为十六进制字符串private static String byteArrayToHexString(byte[] results){StringBuffer resultNew = new StringBuffer();for(int i = 0;i < results.length;i++){resultNew.append(byteToHexString(results[i]));}return resultNew.toString();}//16进制下数字到字符的映射数组private static String[] HEXDIGITS = new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};//将字节转化成十六进制的字符串private static String byteToHexString(byte b){int byteNum = b;if(byteNum < 0){byteNum = byteNum + 256;}int d1 = byteNum / 16;int d2 = byteNum % 16;return HEXDIGITS[d1]+HEXDIGITS[d2];}//传入的字符串加密后和Md5字符串的比较,常用语登录时密码的核对private static boolean compareStringWithMD5Code(String str,String MD5Code){boolean isEquals = false;if(StringUtils.isBlank(str)){return isEquals;}if(MD5Code.equals(getMD5Code(str))){isEquals = true;}return isEquals;}//生成一个10位的随机saltpublic static String getSalt(){String salt = "";Random rand = new Random();for(int i=0;i<10;i++){int num = rand.nextInt(3);switch(num){case 0:char c1 = (char)(rand.nextInt(26)+'a');//生成随机小写字母salt += c1;break;case 1:char c2 = (char)(rand.nextInt(26)+'A');//生成随机大写字母salt += c2;break;case 2:salt += rand.nextInt(10);//生成随机数字}}return salt;}}
这篇关于MD5加密技术(加盐)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!