欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MD5加盐加密工具类

程序员文章站 2024-03-19 10:59:34
...

Md5Util

package com.leyou.utils;

import org.springframework.security.crypto.codec.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author kang
 * @version 1.0
 * @date 2019/12/5 14:07
 */
public class Md5Util {
    /**
     * MD5加密
     * @param input
     * @return
     */
    public static String MD5(String input) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return "check jdk";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        char[] charArray = input.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++){
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * MD5加盐加密
     * @param password
     * @param salt
     * @return
     */
    public static String generate(String password,String salt) {
        //MD5盐值加密
        password = md5Hex(password + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     * 获取盐值
     * @return
     */
    public static String getSalt() {
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        return sb.toString();
    }

    /**
     * 判断是否是同一字符串 校验
     * @param password
     * @param md5
     * @return
     */
    public static boolean verify(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(password + salt).equals(new String(cs1));
    }

    /**
     * MD5加盐加密的方法
     * @param src
     * @return
     */
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String args[]) {

        String plaintext = "DingSai";

        System.out.println("明文:" + plaintext);
        System.out.println("普通MD5码:" + MD5(plaintext));
        //获取盐值
        String salt = getSalt();
        // 获取加盐后的MD5值
        String ciphertext = generate(plaintext,salt);
        System.out.println("加盐后MD5码:" + ciphertext);
        System.out.println("是否是同一字符串:" + verify(plaintext, ciphertext));

    }
}
明文:DingSai
普通MD5码:d67d190a7b4166d2896fbd49b3ef2219
加盐后MD5码:f4d478e05b3321a465e8ae89f4483c61c05d25381fb17767
是否是同一字符串:true
public Boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //从redis中取出验证码
        String codeCache = this.redisTemplate.opsForValue().get(key).toString();
        //检查验证码是否正确
        if(!code.equals(codeCache)){
            //验证码不一致
            return false;
        }
        user.setId(null);
        user.setCreated(new Date());
        //生成盐
        String salt = Md5Util.getSalt();
        user.setSalt(salt);
        //MD5加密 + 加盐
        user.setPassword(Md5Util.generate(user.getPassword(),salt));
        //写入数据库
        boolean boo = this.userMapper.insertSelective(user) == 1;
        if(boo){
            try {
                //删除缓存的数据
                this.redisTemplate.delete(key);
            } catch (Exception e) {
                logger.error("删除缓存验证码失败,code:{}", code, e);
            }
        }
        return boo;
    }