PBKDF2实现

PBKDF2简介

常见的加密算法,如MD5,此类算法为单向的,无法通过逆向破解,但由于技术的不断进步,可以通过字典和暴力破解。后来人们通过加盐来增加密码的安全性,但彩虹表的出现让这种方式也变得不安全。以至于出现了现在的PBKDF2算法。

PBKDF2算法通过多次hash来对密码进行加密。原理是通过password和salt进行hash,然后将结果作为salt在与password进行hash,多次重复此过程,生成最终的密文。此过程可能达到上千次,逆向破解的难度太大,破解一个密码的时间可能需要几百年,所以PBKDF2算法是安全的.


算法实现

public class PBKDF2 {
	public static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";  
	  
	//盐的长度  
    public static final int SALT_SIZE = 16;  
  
     //生成密文的长度 
    public static final int HASH_SIZE = 32;  
  
     // 迭代次数 
    public static final int PBKDF2_ITERATIONS = 1000;  
  
    /** 
     * 对输入的密码进行验证 
     *  
     */  
    public static boolean verify(String password, String salt, String key)  
            throws NoSuchAlgorithmException, InvalidKeySpecException {  
        // 用相同的盐值对用户输入的密码进行加密  
        String result = getPBKDF2(password, salt);  
        // 把加密后的密文和原密文进行比较,相同则验证成功,否则失败  
        return result.equals(key);  
    }  
  
    /**
     * 根据password和salt生成密文
     * 
     */
    public static String getPBKDF2(String password, String salt) throws NoSuchAlgorithmException,  
            InvalidKeySpecException {  
    	//将16进制字符串形式的salt转换成byte数组
    	byte[] bytes = DatatypeConverter.parseHexBinary(salt);
        KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, PBKDF2_ITERATIONS, HASH_SIZE * 4);  
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);  
        byte[] hash = secretKeyFactory.generateSecret(spec).getEncoded();
		//将byte数组转换为16进制的字符串
        return DatatypeConverter.printHexBinary(hash);  
    }  
    
  
    /** 
     * 生成随机盐值
     *  
     */  
    public static String getSalt() throws NoSuchAlgorithmException {  
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");  
        byte[] bytes = new byte[SALT_SIZE / 2];  
        random.nextBytes(bytes);  
        //将byte数组转换为16进制的字符串
        String salt = DatatypeConverter.printHexBinary(bytes);
        return salt;  
    }  
}

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值