All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.dromara.hutool.crypto.symmetric.PBKDF2 Maven / Gradle / Ivy

There is a newer version: 6.0.0.M3
Show newest version
/*
 * Copyright (c) 2013-2024 Hutool Team and hutool.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.dromara.hutool.crypto.symmetric;

import org.dromara.hutool.core.codec.binary.HexUtil;
import org.dromara.hutool.crypto.KeyUtil;

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

/**
 * PBKDF2应用一个伪随机函数以导出密钥,PBKDF2简单而言就是将salted hash进行多次重复计算。
 * 参考:https://blog.csdn.net/huoji555/article/details/83659687
 *
 * @author looly
 */
public class PBKDF2 {

	private String algorithm = "PBKDF2WithHmacSHA1";
	//生成密文的长度
	private int keyLength = 512;

	//迭代次数
	private int iterationCount = 1000;

	/**
	 * 构造,算法PBKDF2WithHmacSHA1,盐长度16,密文长度512,迭代次数1000
	 */
	public PBKDF2() {
	}

	/**
	 * 构造
	 *
	 * @param algorithm      算法,一般为PBKDF2WithXXX
	 * @param keyLength      生成密钥长度,默认512
	 * @param iterationCount 迭代次数,默认1000
	 */
	public PBKDF2(final String algorithm, final int keyLength, final int iterationCount) {
		this.algorithm = algorithm;
		this.keyLength = keyLength;
		this.iterationCount = iterationCount;
	}

	/**
	 * 加密
	 *
	 * @param password 密码
	 * @param salt     盐
	 * @return 加密后的密码
	 */
	public byte[] encrypt(final char[] password, final byte[] salt) {
		final PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
		final SecretKey secretKey = KeyUtil.generateKey(algorithm, pbeKeySpec);
		return secretKey.getEncoded();
	}

	/**
	 * 加密
	 *
	 * @param password 密码
	 * @param salt     盐
	 * @return 加密后的密码
	 */
	public String encryptHex(final char[] password, final byte[] salt) {
		return HexUtil.encodeStr(encrypt(password, salt));
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy