java 实现 pbkdf2_sha256 加密验证算法

 在线加密验证地址:PBKDF2 Derive Key Onlineicon-default.png?t=M5H6https://8gwifi.org/pbkdf.jsp

import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;

/**
 * pbkdf2_sha256加密验证算法
 * @author Administrator
 *
 */
public class Pbkdf2Sha256 {

    //默认迭代计数为 27500
    private static final Integer DEFAULT_ITERATIONS = 27500;
    //算法名称
    private static final String algorithm = "pbkdf2_sha256";
    // 密文长度
    private static final Integer KEY_LENGTH = 512;

    /**
     * 获取密文
     *
     * @param password   密码明文
     * @param salt       加盐
     * @param iterations 迭代计数
     * @return
     */
    private static String getEncodedHash(String password, String salt, int iterations,int keyLength) {
        // 仅返回整个编码密码的最后一部分
        SecretKeyFactory keyFactory = null;
        try {
            // Instance:PBKDF2WithHmacSHA1、PBKDF2WithHmacSHA256、PBKDF2WithHmacSHA224、PBKDF2WithHmacSHA512、PBKDF2WithHmacSHA384
            keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("无法检索 pbkdf2_sha256 算法:"+e);
        }
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), Base64.getDecoder().decode(salt), iterations, keyLength);
//        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(Charset.forName("UTF-8")), iterations, keyLength);
        SecretKey secret = null;
        try {
            secret = keyFactory.generateSecret(keySpec);
        } catch (InvalidKeySpecException e) {
            System.out.println("无法生成密钥:"+e);
        }
        byte[] rawHash = secret.getEncoded();
        byte[] hashBase64 = Base64.getEncoder().encode(rawHash);

        return new String(hashBase64);
    }

    /**
     * 明文加盐
     *
     * @return String
     */
    private static String getSalt() {
        int length = 22;
        Random rand = new Random();
        char[] rs = new char[length];
        for (int i = 0; i < length; i++) {
            int t = rand.nextInt(3);
            if (t == 0) {
                rs[i] = (char) (rand.nextInt(10) + 48);
            } else if (t == 1) {
                rs[i] = (char) (rand.nextInt(26) + 65);
            } else {
                rs[i] = (char) (rand.nextInt(26) + 97);
            }
        }
        return new String(rs)+"==";
    }

    /**
     * 随机加盐
     * 默认迭代次数 27500
     * 默认加密长度 512
     * @param password 密码明文
     * @return
     */
    public static String encode(String password) {
        return encode(password, getSalt());
    }

    /**
     * 随机加盐
     *
     * @param password 密码明文
     * @return
     */
    public static String encode(String password, int iterations, int keyLength) {
        return encode(password, getSalt(), iterations, keyLength);
    }

    /**
     * 随机加盐
     * 默认迭代次数 27500
     * @param password 密码明文
     * @return
     */
    public static String encode(String password, int iterations) {
        return encode(password, getSalt(), iterations, KEY_LENGTH);
    }

    /**
     * 默认迭代次数 27500
     * 默认加密长度 512
     * @param password 密码明文
     * @param salt 加盐
     * @return
     */
    public static String encode(String password, String salt) {
        return encode(password, salt, DEFAULT_ITERATIONS, KEY_LENGTH);
    }

    /**
     * @param password   密码明文
     * @param salt       加盐
     * @param iterations 迭代计数
     * @return
     */
    public static String encode(String password, String salt, int iterations,int keyLength) {
        // 返回散列密码,以及算法、迭代次数和salt
        String hash = getEncodedHash(password, salt, iterations,keyLength);
        return String.format("%s$%d$%d$%s$%s", algorithm, iterations, keyLength, salt, hash);
    }

    /**
     * 校验密码是否合法
     *
     * @param password       密码明文
     * @param hashedPassword 密码密文
     * @return
     */
    public static boolean verification(String password, String hashedPassword) {
        // hashedPassword包括:ALGORITHM、ITERATIONS_NUMBER、SALT和HASH;部分用美元字符(“$”)连接
        String[] parts = hashedPassword.split("\\$");
        if (parts.length != 5) {
            // 哈希格式错误
            return false;
        }
        Integer iterations = Integer.parseInt(parts[1]);
        Integer keyLength = Integer.parseInt(parts[2]);
        String salt = parts[3];
        String hash = encode(password, salt, iterations,keyLength);
        return hash.equals(hashedPassword);
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID());
        System.out.println(new Date().getTime());
        System.out.println(Pbkdf2Sha256.encode("123456", "Do7yDa9wXAvlvqwTJuIh0Q==", 27500,512));
        String en = "pbkdf2_sha256$27500$512$Do7yDa9wXAvlvqwTJuIh0Q==$lqoUCJciczBJ3OqW1myBEru3dZEnVfsz7qS3wc/e6lBLA93p6SQEwuWTFrVUBshkQBQkHy/TbdjlqWVa5ZcVJw==";
        System.out.println(Pbkdf2Sha256.verification("123456", en));
//        System.out.println(Pbkdf2Sha256.getSalt());
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Please Sit Down

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值