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());
    }
}

你可能感兴趣的:(Java,java,算法)