feat(encrypt/password-encoder): 新增密码编码器模块(经过考量重新拆分出来)

This commit is contained in:
2025-09-13 22:15:27 +08:00
parent 68895787a7
commit e414abc735
15 changed files with 57 additions and 41 deletions

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>top.continew.starter</groupId>
<artifactId>continew-starter-encrypt</artifactId>
<version>${revision}</version>
</parent>
<artifactId>continew-starter-encrypt-password-encoder</artifactId>
<packaging>jar</packaging>
<name>${project.artifactId}</name>
<description>ContiNew Starter 加密模块 - 密码编码器</description>
<dependencies>
<!-- 加密模块 - 核心模块 -->
<dependency>
<groupId>top.continew.starter</groupId>
<artifactId>continew-starter-encrypt-core</artifactId>
</dependency>
<!-- Spring Security 附带的一个密码加密库 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,78 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.autoconfigure;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.continew.starter.core.constant.PropertiesConstants;
import top.continew.starter.core.util.validation.CheckUtils;
import top.continew.starter.encrypt.password.encoder.enums.PasswordEncoderAlgorithm;
import top.continew.starter.encrypt.password.encoder.util.PasswordEncoderUtil;
import java.util.HashMap;
import java.util.Map;
/**
* 密码编码器自动配置
*
* @author Charles7c
* @since 2.14.0
*/
@AutoConfiguration
@EnableConfigurationProperties(PasswordEncoderProperties.class)
@ConditionalOnProperty(prefix = PropertiesConstants.ENCRYPT_PASSWORD_ENCODER, name = PropertiesConstants.ENABLED, havingValue = "true")
public class PasswordEncoderAutoConfiguration {
private static final Logger log = LoggerFactory.getLogger(PasswordEncoderAutoConfiguration.class);
/**
* 密码编码器配置
*
* @see DelegatingPasswordEncoder
* @see PasswordEncoderFactories
*/
@Bean
@ConditionalOnMissingBean
public PasswordEncoder passwordEncoder(PasswordEncoderProperties properties) {
Map<String, PasswordEncoder> encoders = new HashMap<>();
encoders.put(PasswordEncoderAlgorithm.BCRYPT.name().toLowerCase(), PasswordEncoderUtil
.getEncoder(PasswordEncoderAlgorithm.BCRYPT));
encoders.put(PasswordEncoderAlgorithm.SCRYPT.name().toLowerCase(), PasswordEncoderUtil
.getEncoder(PasswordEncoderAlgorithm.SCRYPT));
encoders.put(PasswordEncoderAlgorithm.PBKDF2.name().toLowerCase(), PasswordEncoderUtil
.getEncoder(PasswordEncoderAlgorithm.PBKDF2));
encoders.put(PasswordEncoderAlgorithm.ARGON2.name().toLowerCase(), PasswordEncoderUtil
.getEncoder(PasswordEncoderAlgorithm.ARGON2));
PasswordEncoderAlgorithm algorithm = properties.getAlgorithm();
CheckUtils.throwIf(PasswordEncoderUtil.getEncoder(algorithm) == null, "不支持的加密算法: {}", algorithm);
return new DelegatingPasswordEncoder(algorithm.name().toLowerCase(), encoders);
}
@PostConstruct
public void postConstruct() {
log.debug("[ContiNew Starter] - Auto Configuration 'Encrypt-Password Encoder' completed initialization.");
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.autoconfigure;
import org.springframework.boot.context.properties.ConfigurationProperties;
import top.continew.starter.core.constant.PropertiesConstants;
import top.continew.starter.encrypt.password.encoder.enums.PasswordEncoderAlgorithm;
/**
* 密码编码器配置属性
*
* @author Jasmine
* @author Charles7c
* @since 1.3.0
*/
@ConfigurationProperties(PropertiesConstants.ENCRYPT_PASSWORD_ENCODER)
public class PasswordEncoderProperties {
/**
* 是否启用
*/
private Boolean enabled;
/**
* 默认启用的编码器算法默认BCrypt 加密算法)
*/
private PasswordEncoderAlgorithm algorithm = PasswordEncoderAlgorithm.BCRYPT;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public PasswordEncoderAlgorithm getAlgorithm() {
return algorithm;
}
public void setAlgorithm(PasswordEncoderAlgorithm algorithm) {
this.algorithm = algorithm;
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.encryptor;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.continew.starter.core.util.SpringUtils;
import top.continew.starter.encrypt.context.CryptoContext;
import top.continew.starter.encrypt.encryptor.AbstractEncryptor;
import top.continew.starter.encrypt.password.encoder.autoconfigure.PasswordEncoderProperties;
/**
* 密码编码器加密器
*
* <p>
* 使用前必须注入 {@link PasswordEncoder},此加密方式不可逆,适合于密码场景
* </p>
*
* @see PasswordEncoder
* @see PasswordEncoderProperties
*
* @author Charles7c
* @since 2.13.3
*/
public class PasswordEncoderEncryptor extends AbstractEncryptor {
private final PasswordEncoderProperties properties = SpringUtils.getBean(PasswordEncoderProperties.class, true);
public PasswordEncoderEncryptor(CryptoContext context) {
super(context);
}
@Override
public String encrypt(String plaintext) {
// 如果已经是加密格式,直接返回
if (properties == null || properties.getAlgorithm().getPattern().matcher(plaintext).matches()) {
return plaintext;
}
return SpringUtil.getBean(PasswordEncoder.class).encode(plaintext);
}
@Override
public String decrypt(String ciphertext) {
return ciphertext;
}
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.enums;
import java.util.regex.Pattern;
/**
* 密码编码器加密算法枚举
*
* @author Charles7c
* @since 2.13.3
*/
public enum PasswordEncoderAlgorithm {
/** BCrypt加密算法 */
BCRYPT(Pattern.compile("\\A\\$2(a|y|b)?\\$(\\d\\d)\\$[./0-9A-Za-z]{53}")),
/** SCrypt加密算法 */
SCRYPT(Pattern.compile("\\A\\$s0\\$[0-9a-f]+\\$[0-9a-f]+\\$[0-9a-f]+")),
/** PBKDF2加密算法 */
PBKDF2(Pattern.compile("\\A\\$pbkdf2-sha256\\$\\d+\\$[0-9a-f]+\\$[0-9a-f]+")),
/** Argon2加密算法 */
ARGON2(Pattern.compile("\\A\\$argon2(id|i|d)\\$v=\\d+\\$m=\\d+,t=\\d+,p=\\d+\\$[0-9a-zA-Z+/]+\\$[0-9a-zA-Z+/]+"));
/** 正则匹配 */
private final Pattern pattern;
PasswordEncoderAlgorithm(Pattern pattern) {
this.pattern = pattern;
}
public Pattern getPattern() {
return pattern;
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.exception;
import top.continew.starter.core.exception.BaseException;
import java.io.Serial;
/**
* 密码编码异常
*
* @author Charles7c
* @since 2.13.3
*/
public class PasswordEncodeException extends BaseException {
@Serial
private static final long serialVersionUID = 1L;
public PasswordEncodeException() {
}
public PasswordEncodeException(String message) {
super(message);
}
public PasswordEncodeException(Throwable cause) {
super(cause);
}
public PasswordEncodeException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,127 @@
/*
* Copyright (c) 2022-present Charles7c Authors. All Rights Reserved.
* <p>
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.gnu.org/licenses/lgpl.html
* <p>
* 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 top.continew.starter.encrypt.password.encoder.util;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import top.continew.starter.encrypt.password.encoder.exception.PasswordEncodeException;
import top.continew.starter.encrypt.password.encoder.enums.PasswordEncoderAlgorithm;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 密码加密工具类
* <p>
* 支持多种加密算法可通过编码ID动态选择加密方式
* </p>
*
* @author Charles7c
* @since 2.13.3
*/
public final class PasswordEncoderUtil {
private static final Map<PasswordEncoderAlgorithm, PasswordEncoder> ENCODER_CACHE = new ConcurrentHashMap<>();
static {
// 初始化默认的加密算法实例
ENCODER_CACHE.put(PasswordEncoderAlgorithm.BCRYPT, new BCryptPasswordEncoder());
ENCODER_CACHE.put(PasswordEncoderAlgorithm.SCRYPT, SCryptPasswordEncoder.defaultsForSpringSecurity_v5_8());
ENCODER_CACHE.put(PasswordEncoderAlgorithm.PBKDF2, Pbkdf2PasswordEncoder.defaultsForSpringSecurity_v5_8());
ENCODER_CACHE.put(PasswordEncoderAlgorithm.ARGON2, Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8());
}
private PasswordEncoderUtil() {
}
/**
* 使用指定的加密算法加密密码
*
* @param algorithm 加密算法
* @param rawPassword 原始密码
* @return 加密后的密码
* @throws IllegalArgumentException 如果不支持指定的加密算法
*/
public static String encode(PasswordEncoderAlgorithm algorithm, String rawPassword) {
// 参数校验
if (algorithm == null) {
throw new IllegalArgumentException("加密算法不能为空");
}
if (rawPassword == null) {
throw new IllegalArgumentException("原始密码不能为空");
}
// 获取对应的密码编码器
PasswordEncoder encoder = ENCODER_CACHE.get(algorithm);
if (encoder == null) {
throw new IllegalArgumentException("不支持的加密算法: " + algorithm);
}
try {
return encoder.encode(rawPassword);
} catch (Exception e) {
throw new PasswordEncodeException("密码加密失败: " + e.getMessage(), e);
}
}
/**
* 验证密码是否匹配
*
* @param algorithm 加密算法
* @param rawPassword 原始密码
* @param encodedPassword 加密后的密码
* @return 是否匹配
* @throws IllegalArgumentException 如果不支持指定的加密算法
*/
public static boolean matches(PasswordEncoderAlgorithm algorithm, String rawPassword, String encodedPassword) {
// 参数校验
if (algorithm == null) {
throw new IllegalArgumentException("加密算法不能为空");
}
if (rawPassword == null || encodedPassword == null) {
return false;
}
// 获取对应的密码编码器
PasswordEncoder encoder = ENCODER_CACHE.get(algorithm);
if (encoder == null) {
throw new IllegalArgumentException("不支持的加密算法: " + algorithm);
}
try {
return encoder.matches(rawPassword, encodedPassword);
} catch (Exception e) {
return false;
}
}
/**
* 获取指定算法的密码编码器
*
* @param algorithm 加密算法
* @return 密码编码器实例不存在则返回null
*/
public static PasswordEncoder getEncoder(PasswordEncoderAlgorithm algorithm) {
if (algorithm == null) {
return null;
}
return ENCODER_CACHE.get(algorithm);
}
}

View File

@@ -0,0 +1 @@
top.continew.starter.encrypt.password.encoder.autoconfigure.PasswordEncoderAutoConfiguration