Java关于md5+salt盐加密验证

一.陈述一下工作流程:

1.根据已有的密码字符串去生成一个密码+盐字符串,可以将盐的加密字符串也存放在数据库(看需求),

2.验证时将提交的密码字符串进行同样的加密再从数据库中取得已有的盐进行组合密码+盐的字符串和已有的进行验证

package com.mi.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

public class Md5SaltTool {

    private static final String HEX_NUMS_STR="0123456789ABCDEF";   
    private static final Integer SALT_LENGTH = 12;   
       
    /**   
     * 将16进制字符串转换成字节数组   
     * @param hex   
     * @return   
     */  
    public static byte[] hexStringToByte(String hex) {   
        int len = (hex.length() / 2);   
        byte[] result = new byte[len];   
        char[] hexChars = hex.toCharArray();   
        for (int i = 0; i < len; i++) {   
            int pos = i * 2;   
            result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4    
                            | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));   
        }   
        return result;   
    }   
       
    /**  
     * 将指定byte数组转换成16进制字符串  
     * @param b  
     * @return  
     */  
    public static String byteToHexString(byte[] b) {   
        StringBuffer hexString = new StringBuffer();   
        for (int i = 0; i < b.length; i++) {   
            String hex = Integer.toHexString(b[i] & 0xFF);   
            if (hex.length() == 1) {   
                hex = '0' + hex;   
            }   
            hexString.append(hex.toUpperCase());   
        }   
        return hexString.toString();   
    }   
       
    /**  
     * 验证口令是否合法  
     * @param password  
     * @param passwordInDb  
     * @return  
     * @throws NoSuchAlgorithmException  
     * @throws UnsupportedEncodingException  
     */  
    public static boolean validPassword(String password, String passwordInDb)   
            throws NoSuchAlgorithmException, UnsupportedEncodingException {   
        //将16进制字符串格式口令转换成字节数组   
        byte[] pwdInDb = hexStringToByte(passwordInDb);   
        //声明盐变量   
        byte[] salt = new byte[SALT_LENGTH];   
        //将盐从数据库中保存的口令字节数组中提取出来   
        System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);   
        //创建消息摘要对象   
        MessageDigest md = MessageDigest.getInstance("MD5");   
        //将盐数据传入消息摘要对象   
        md.update(salt);   
        //将口令的数据传给消息摘要对象   
        md.update(password.getBytes("UTF-8"));   
        //生成输入口令的消息摘要   
        byte[] digest = md.digest();   
        //声明一个保存数据库中口令消息摘要的变量   
        byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];   
        //取得数据库中口令的消息摘要   
        System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length);   
        //比较根据输入口令生成的消息摘要和数据库中消息摘要是否相同   
        if (Arrays.equals(digest, digestInDb)) {   
            //口令正确返回口令匹配消息   
            return true;   
        } else {   
            //口令不正确返回口令不匹配消息   
            return false;   
        }   
    }   
  
    /**  
     * 获得加密后的16进制形式口令  
     * @param password  
     * @return  
     * @throws NoSuchAlgorithmException  
     * @throws UnsupportedEncodingException  
     */  
    public static String getEncryptedPwd(String password)   
            throws NoSuchAlgorithmException, UnsupportedEncodingException {   
        //声明加密后的口令数组变量   
        byte[] pwd = null;   
        //随机数生成器   
        SecureRandom random = new SecureRandom();   
        //声明盐数组变量   12
        byte[] salt = new byte[SALT_LENGTH];   
        //将随机数放入盐变量中   
        random.nextBytes(salt);   
  
        //声明消息摘要对象   
        MessageDigest md = null;   
        //创建消息摘要   
        md = MessageDigest.getInstance("MD5");   
        //将盐数据传入消息摘要对象   
        md.update(salt);   
        //将口令的数据传给消息摘要对象   
        md.update(password.getBytes("UTF-8"));   
        //获得消息摘要的字节数组   
        byte[] digest = md.digest();   
  
        //因为要在口令的字节数组中存放盐,所以加上盐的字节长度   
        pwd = new byte[digest.length + SALT_LENGTH];   
        //将盐的字节拷贝到生成的加密口令字节数组的前12个字节,以便在验证口令时取出盐   
        System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);   
        //将消息摘要拷贝到加密口令字节数组从第13个字节开始的字节   
        System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);   
        for(int i=0;i<pwd.length;i++){
            System.out.print(pwd[i]);
        }
        //将字节数组格式加密后的口令转化为16进制字符串格式的口令   
        return byteToHexString(pwd);   
    }   
}

测试类如下:
package com.mi.util;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class Md5SaltTest {

      private static Map users = new HashMap();   
      
        public static void main(String[] args){   
            String userName = "zyg";   
            String password = "123";   
            registerUser(userName,password);   
               
            userName = "changong";   
            password = "456";   
            registerUser(userName,password);   
               
            String loginUserId = "zyg";   
            String pwd = "1232";   
            try {   
                if(loginValid(loginUserId,pwd)){   
                    System.out.println("欢迎登陆!!!");   
                }else{   
                    System.out.println("口令错误,请重新输入!!!");   
                }   
            } catch (NoSuchAlgorithmException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            } catch (UnsupportedEncodingException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            }    
        }   
           
        /**  
         * 注册用户  
         *   
         * @param userName  
         * @param password  
         */  
        public static void registerUser(String userName,String password){   
            String encryptedPwd = null;   
            try {   
                encryptedPwd = Md5SaltTool.getEncryptedPwd(password);   
                users.put(userName, encryptedPwd);   
                   
            } catch (NoSuchAlgorithmException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            } catch (UnsupportedEncodingException e) {   
                // TODO Auto-generated catch block   
                e.printStackTrace();   
            }   
        }   
           
        /**  
         * 验证登陆  
         *   
         * @param userName  
         * @param password  
         * @return  
         * @throws UnsupportedEncodingException   
         * @throws NoSuchAlgorithmException   
         */  
        public static boolean loginValid(String userName,String password)    
                    throws NoSuchAlgorithmException, UnsupportedEncodingException{   
             /*String loginUserId = "zyg";   
               String pwd = "1232";*/ 
            String pwdInDb = (String)users.get(userName);   
            if(null!=pwdInDb){ // 该用户存在   
                    return Md5SaltTool.validPassword(password, pwdInDb);   
            }else{   
                System.out.println("不存在该用户!!!");   
                return false;   
            }   
        }
}


Java中,MD5是一种常用的哈希算法,用于快速计算任意长度数据的固定长度摘要(通常是16字节),常用于密码存储的安全增强。"加盐"(Salting)是指在原始数据(例如密码)前添加随机值的过程,其目的是增加哈希结果的复杂性和不可预测性,防止彩虹表攻击。 当你想结合MD5进行安全哈希时,通常步骤如下: 1. **生成随机**: 使用`SecureRandom`类生成一个随机字符串作为的长度可以根据需求设置。 2. **组合原始数据**: 将用户输入的密码和随机生成的拼接在一起。 3. **计算MD5哈希**: 使用`MessageDigest`类(特别是`MessageDigest.getInstance("MD5")`获取MD5算法的实例)对拼接后的字符串进行哈希运算。 以下是简单的示例代码: ```java import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class MD5WithSaltExample { public static String getMD5WithSalt(String password) throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstanceStrong(); String salt = generateRandomSalt(random, 8); // 生成8位随机 String saltedPassword = password + salt; // 拼接原密码和 MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] hashedBytes = md5.digest(saltedPassword.getBytes(StandardCharsets.UTF_8)); return bytesToHex(hashedBytes); } private static String generateRandomSalt(SecureRandom random, int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { sb.append((char) random.nextInt(122) + 'a'); // 生成小写字母的随机字符 } return sb.toString(); } private static String bytesToHex(byte[] bytes) { char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; StringBuilder result = new StringBuilder(); for (byte b : bytes) { result.append(hexChars[(b & 0xF0) >> 4]); result.append(hexChars[b & 0x0F]); } return result.toString(); } public static void main(String[] args) { try { String password = "example"; String hashedPassword = getMD5WithSalt(password); System.out.println("哈希值(带):" + hashedPassword); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } ``` 在这个例子中,每次计算出来的MD5哈希都会因为的不同而有所变化,增加了破解的难度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值