diff --git a/CHANGELOG.md b/CHANGELOG.md index bddb9c5..18e14aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,49 @@ =========================== +## [2.3.2](https://github.com/buession/buession-security/releases/tag/v2.3.2) (2023-12-27) + +### 🔨依赖升级 + +- [依赖库版本升级和安全漏洞修复](https://github.com/buession/buession-parent/releases/tag/v2.3.2) +- [owasp antisamy](https://github.com/nahsra/antisamy) 版本升级至 1.7.4 + + +### ⭐ 新特性 + +- **buession-security-captcha:** GeetestClient 增加 v3、v4 版本判断方法 +- **buession-security-shiro:** 增加判断是否具备所有权限 Tag HasAllPermissionsTag + + +### 🔔 变化 + +- **buession-security-shiro:** 依赖 javax.servlet.jsp-api 更换为 jakarta.servlet.jsp-api + + +### 🐞 Bug 修复 + +- **buession-security-pac4j:** 修复 webflux 模式下 PrincipalMethodArgumentResolver 继承了错误类的 BUG + + +### 漏洞修复 + +- [owasp antisamy](https://github.com/nahsra/antisamy) 修复 [CVE-2023-43643] 漏洞 + + +### ⏪ 优化 + +- **buession-security-captcha:** 代码质量优化 +- **buession-security-pac4j:** 代码质量优化 + + +### 📔 文档 + +- **buession-security-shiro:** 完善注释 + + +--- + + ## [2.3.1](https://github.com/buession/buession-security/releases/tag/v2.3.1) (2023-11-17) ### 🔨依赖升级 diff --git a/buession-security-captcha/pom.xml b/buession-security-captcha/pom.xml index ab17bb3..9386b31 100644 --- a/buession-security-captcha/pom.xml +++ b/buession-security-captcha/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-captcha https://security.buession.com/ diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/aliyun/AliYunCaptchaClient.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/aliyun/AliYunCaptchaClient.java index f6a2750..ec0cf6b 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/aliyun/AliYunCaptchaClient.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/aliyun/AliYunCaptchaClient.java @@ -224,21 +224,10 @@ public String getEndpoint() { * @return 检测结果 */ private static boolean checkParam(final AliYunRequestData requestData) throws RequiredParameterCaptchaException { - if(Validate.hasText(requestData.getToken()) == false){ - throw new RequiredParameterCaptchaException("Token"); - } - - if(Validate.hasText(requestData.getSig()) == false){ - throw new RequiredParameterCaptchaException("Sig"); - } - - if(Validate.hasText(requestData.getSessionId()) == false){ - throw new RequiredParameterCaptchaException("SessionId"); - } - - if(Validate.hasText(requestData.getScene()) == false){ - throw new RequiredParameterCaptchaException("Scene"); - } + Assert.isBlank(requestData.getToken(), ()->new RequiredParameterCaptchaException("Token")); + Assert.isBlank(requestData.getSig(), ()->new RequiredParameterCaptchaException("Sig")); + Assert.isBlank(requestData.getSessionId(), ()->new RequiredParameterCaptchaException("SessionId")); + Assert.isBlank(requestData.getScene(), ()->new RequiredParameterCaptchaException("Scene")); return true; } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/core/RequiredParameterCaptchaException.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/core/RequiredParameterCaptchaException.java index 4f545fe..677fae9 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/core/RequiredParameterCaptchaException.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/core/RequiredParameterCaptchaException.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.captcha.core; @@ -34,27 +34,28 @@ public class RequiredParameterCaptchaException extends CaptchaException { private final String parameter; - public RequiredParameterCaptchaException(String parameter){ + public RequiredParameterCaptchaException(String parameter) { super("Parameter \"" + parameter + "\" cloud not be empty or null."); this.parameter = parameter; } - public RequiredParameterCaptchaException(String parameter, String message){ + public RequiredParameterCaptchaException(String parameter, String message) { super(message); this.parameter = parameter; } - public RequiredParameterCaptchaException(String parameter, Throwable cause){ + public RequiredParameterCaptchaException(String parameter, Throwable cause) { super("Parameter \"" + parameter + "\" cloud not be empty or null.", cause); this.parameter = parameter; } - public RequiredParameterCaptchaException(String parameter, String message, Throwable cause){ + public RequiredParameterCaptchaException(String parameter, String message, Throwable cause) { super(message, cause); this.parameter = parameter; } - public String getParameter(){ + public String getParameter() { return parameter; } + } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/GeetestClient.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/GeetestClient.java index ecfb811..d113776 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/GeetestClient.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/GeetestClient.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.captcha.geetest; @@ -37,8 +37,30 @@ public interface GeetestClient extends CaptchaClient { void setHttpClient(HttpClient httpClient); @Override - default Manufacturer getManufacturer(){ + default Manufacturer getManufacturer() { return Manufacturer.GEETEST; } + /** + * 返回是否为 V3 版本 + * + * @return true / false + * + * @since 2.3.2 + */ + default boolean isV3() { + return "v3".equalsIgnoreCase(getVersion()); + } + + /** + * 返回是否为 V3 版本 + * + * @return true / false + * + * @since 2.3.2 + */ + default boolean isV4() { + return "v4".equalsIgnoreCase(getVersion()); + } + } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v3/GeetestV3Client.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v3/GeetestV3Client.java index c43f1ab..ece2d3b 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v3/GeetestV3Client.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v3/GeetestV3Client.java @@ -26,6 +26,7 @@ import com.buession.core.builder.MapBuilder; import com.buession.core.id.SimpleIdGenerator; +import com.buession.core.utils.Assert; import com.buession.core.validator.Validate; import com.buession.httpclient.HttpClient; import com.buession.httpclient.core.Response; @@ -189,17 +190,9 @@ public String getVersion() { */ private static boolean checkParam(final GeetestV3RequestData requestData) throws RequiredParameterCaptchaException { - if(Validate.hasText(requestData.getChallenge()) == false){ - throw new RequiredParameterCaptchaException("challenge"); - } - - if(Validate.hasText(requestData.getValidate()) == false){ - throw new RequiredParameterCaptchaException("validate"); - } - - if(Validate.hasText(requestData.getSeccode()) == false){ - throw new RequiredParameterCaptchaException("seccode"); - } + Assert.isBlank(requestData.getChallenge(), ()->new RequiredParameterCaptchaException("challenge")); + Assert.isBlank(requestData.getValidate(), ()->new RequiredParameterCaptchaException("validate")); + Assert.isBlank(requestData.getSeccode(), ()->new RequiredParameterCaptchaException("seccode")); return true; } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v4/GeetestV4Client.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v4/GeetestV4Client.java index 8dab159..b2fb019 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v4/GeetestV4Client.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/geetest/api/v4/GeetestV4Client.java @@ -25,7 +25,7 @@ package com.buession.security.captcha.geetest.api.v4; import com.buession.core.builder.MapBuilder; -import com.buession.core.validator.Validate; +import com.buession.core.utils.Assert; import com.buession.httpclient.HttpClient; import com.buession.httpclient.core.EncodedFormRequestBody; import com.buession.httpclient.core.Response; @@ -62,7 +62,7 @@ public final class GeetestV4Client extends AbstractGeetestClient { * @param secretKey * 私钥 */ - public GeetestV4Client(final String appId, final String secretKey){ + public GeetestV4Client(final String appId, final String secretKey) { super(appId, secretKey); } @@ -76,12 +76,12 @@ public GeetestV4Client(final String appId, final String secretKey){ * @param httpClient * {@link HttpClient} */ - public GeetestV4Client(final String appId, final String secretKey, final HttpClient httpClient){ + public GeetestV4Client(final String appId, final String secretKey, final HttpClient httpClient) { super(appId, secretKey, httpClient); } @Override - public InitResponse initialize(RequestData requestData){ + public InitResponse initialize(RequestData requestData) { if(logger.isDebugEnabled()){ logger.debug("验证初始化"); } @@ -90,7 +90,7 @@ public InitResponse initialize(RequestData requestData){ } @Override - public Status validate(RequestData requestData) throws CaptchaException{ + public Status validate(RequestData requestData) throws CaptchaException { if(logger.isDebugEnabled()){ logger.debug("二次验证, 请求参数:{}.", requestData); } @@ -134,7 +134,7 @@ public Status validate(RequestData requestData) throws CaptchaException{ } @Override - public String getVersion(){ + public String getVersion() { return "v4"; } @@ -147,22 +147,11 @@ public String getVersion(){ * @return 检测结果 */ private static boolean checkParam(final GeetestV4RequestData requestData) - throws RequiredParameterCaptchaException{ - if(Validate.hasText(requestData.getLotNumber()) == false){ - throw new RequiredParameterCaptchaException("lot_number"); - } - - if(Validate.hasText(requestData.getCaptchaOutput()) == false){ - throw new RequiredParameterCaptchaException("captcha_output"); - } - - if(Validate.hasText(requestData.getPassToken()) == false){ - throw new RequiredParameterCaptchaException("pass_token"); - } - - if(Validate.hasText(requestData.getGenTime()) == false){ - throw new RequiredParameterCaptchaException("gen_time"); - } + throws RequiredParameterCaptchaException { + Assert.isBlank(requestData.getLotNumber(), ()->new RequiredParameterCaptchaException("lot_number")); + Assert.isBlank(requestData.getCaptchaOutput(), ()->new RequiredParameterCaptchaException("captcha_output")); + Assert.isBlank(requestData.getPassToken(), ()->new RequiredParameterCaptchaException("pass_token")); + Assert.isBlank(requestData.getGenTime(), ()->new RequiredParameterCaptchaException("gen_time")); return true; } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/tencent/TencentCaptchaClient.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/tencent/TencentCaptchaClient.java index fcd8e07..6adb23c 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/tencent/TencentCaptchaClient.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/tencent/TencentCaptchaClient.java @@ -25,7 +25,6 @@ package com.buession.security.captcha.tencent; import com.buession.core.utils.Assert; -import com.buession.core.validator.Validate; import com.buession.httpclient.HttpClient; import com.buession.httpclient.core.Response; import com.buession.lang.Status; @@ -71,7 +70,7 @@ public class TencentCaptchaClient extends AbstractCaptchaClient { * @param secretKey * 原始的 SecretKey */ - public TencentCaptchaClient(final String secretId, final String secretKey){ + public TencentCaptchaClient(final String secretId, final String secretKey) { Assert.isBlank(secretId, "Secret Id cloud not be empty or null"); Assert.isBlank(secretKey, "Secret Key cloud not be empty or null"); this.secretId = secretId; @@ -88,13 +87,13 @@ public TencentCaptchaClient(final String secretId, final String secretKey){ * @param httpClient * {@link HttpClient} 实例 */ - public TencentCaptchaClient(final String secretId, final String secretKey, final HttpClient httpClient){ + public TencentCaptchaClient(final String secretId, final String secretKey, final HttpClient httpClient) { this(secretId, secretKey); setHttpClient(httpClient); } @Override - public Status validate(RequestData requestData) throws CaptchaException{ + public Status validate(RequestData requestData) throws CaptchaException { if(logger.isDebugEnabled()){ logger.debug("二次验证, 请求参数:{}.", requestData); } @@ -135,12 +134,12 @@ public Status validate(RequestData requestData) throws CaptchaException{ } @Override - public Manufacturer getManufacturer(){ + public Manufacturer getManufacturer() { return Manufacturer.TENCENT; } @Override - public String getVersion(){ + public String getVersion() { return "2019-07-22"; } @@ -153,14 +152,9 @@ public String getVersion(){ * @return 检测结果 */ private static boolean checkParam(final TencentRequestData requestData) - throws RequiredParameterCaptchaException{ - if(Validate.hasText(requestData.getTicket()) == false){ - throw new RequiredParameterCaptchaException("Ticket"); - } - - if(Validate.hasText(requestData.getRandstr()) == false){ - throw new RequiredParameterCaptchaException("Randstr"); - } + throws RequiredParameterCaptchaException { + Assert.isBlank(requestData.getTicket(), ()->new RequiredParameterCaptchaException("Ticket")); + Assert.isBlank(requestData.getRandstr(), ()->new RequiredParameterCaptchaException("Randstr")); return true; } diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/reactive/ReactiveGeetestCaptchaValidator.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/reactive/ReactiveGeetestCaptchaValidator.java index e9f72ee..293e4f6 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/reactive/ReactiveGeetestCaptchaValidator.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/reactive/ReactiveGeetestCaptchaValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.captcha.validator.reactive; @@ -57,15 +57,15 @@ public class ReactiveGeetestCaptchaValidator extends GeetestCaptchaValidator imp * {@link GeetestParameter} 实例 */ public ReactiveGeetestCaptchaValidator(final GeetestCaptchaClient geetestCaptchaClient, - final GeetestParameter parameter){ + final GeetestParameter parameter) { super(geetestCaptchaClient, parameter); } @Override - public Status validate(final ServerHttpRequest request) throws CaptchaException{ + public Status validate(final ServerHttpRequest request) throws CaptchaException { MultiValueMap parameters = request.getQueryParams(); - if("v3".equals(captchaClient.getVersion())){ + if(captchaClient.isV3()){ final GeetestV3Parameter geetestV3Parameter = (GeetestV3Parameter) parameter; final GeetestV3RequestData requestData = new GeetestV3RequestData(); @@ -84,7 +84,7 @@ public Status validate(final ServerHttpRequest request) throws CaptchaException{ } return validate(requestData); - }else if("v4".equals(captchaClient.getVersion())){ + }else if(captchaClient.isV4()){ final GeetestV4Parameter geetestV4Parameter = (GeetestV4Parameter) parameter; final GeetestV4RequestData requestData = new GeetestV4RequestData(); diff --git a/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/servlet/ServletGeetestCaptchaValidator.java b/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/servlet/ServletGeetestCaptchaValidator.java index 1d9f873..e676621 100644 --- a/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/servlet/ServletGeetestCaptchaValidator.java +++ b/buession-security-captcha/src/main/java/com/buession/security/captcha/validator/servlet/ServletGeetestCaptchaValidator.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.captcha.validator.servlet; @@ -57,13 +57,13 @@ public class ServletGeetestCaptchaValidator extends GeetestCaptchaValidator impl * {@link GeetestParameter} 实例 */ public ServletGeetestCaptchaValidator(final GeetestCaptchaClient geetestCaptchaClient, - final GeetestParameter parameter){ + final GeetestParameter parameter) { super(geetestCaptchaClient, parameter); } @Override - public Status validate(final HttpServletRequest request) throws CaptchaException{ - if("v3".equals(captchaClient.getVersion())){ + public Status validate(final HttpServletRequest request) throws CaptchaException { + if(captchaClient.isV3()){ final GeetestV3Parameter geetestV3Parameter = (GeetestV3Parameter) parameter; final GeetestV3RequestData requestData = new GeetestV3RequestData(); @@ -82,7 +82,7 @@ public Status validate(final HttpServletRequest request) throws CaptchaException } return validate(requestData); - }else if("v4".equals(captchaClient.getVersion())){ + }else if(captchaClient.isV4()){ final GeetestV4Parameter geetestV4Parameter = (GeetestV4Parameter) parameter; final GeetestV4RequestData requestData = new GeetestV4RequestData(); diff --git a/buession-security-core/pom.xml b/buession-security-core/pom.xml index cce58a2..72aad15 100644 --- a/buession-security-core/pom.xml +++ b/buession-security-core/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-core https://security.buession.com/ diff --git a/buession-security-crypto/pom.xml b/buession-security-crypto/pom.xml index 589d129..3f6042e 100644 --- a/buession-security-crypto/pom.xml +++ b/buession-security-crypto/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-crypto https://security.buession.com/ diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/AESCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/AESCrypto.java new file mode 100644 index 0000000..b3f6b07 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/AESCrypto.java @@ -0,0 +1,345 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + * + * ================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.internal.SymmetricalCrypto; + +import java.nio.charset.Charset; +import java.security.GeneralSecurityException; + +/** + * AES 加密对象 + * slat 不足 16 位,以空格填充;slat 超过 16 位将截取前 16 位 + * 加密结果以 Base64 返回 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class AESCrypto extends AbstractCrypto { + + /** + * 加密模式 + */ + private Mode mode = Mode.ECB; + + /** + * 补码方式 + */ + private Padding padding = Padding.PKCS5; + + /** + * 构造函数 + */ + public AESCrypto() { + super(Algorithm.AES); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public AESCrypto(final String salt) { + super(Algorithm.AES, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public AESCrypto(final Charset charset) { + super(Algorithm.AES, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public AESCrypto(final String characterEncoding, final String salt) { + super(Algorithm.AES, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public AESCrypto(final Charset charset, final String salt) { + super(Algorithm.AES, charset, salt); + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + */ + public AESCrypto(final Mode mode) { + this(); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public AESCrypto(final String salt, final Mode mode) { + this(salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + */ + public AESCrypto(final Charset charset, final Mode mode) { + this(charset); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public AESCrypto(final String characterEncoding, final String salt, final Mode mode) { + this(characterEncoding, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public AESCrypto(final Charset charset, final String salt, final Mode mode) { + this(charset, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param padding + * 补码方式 + */ + public AESCrypto(final Padding padding) { + this(); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public AESCrypto(final String salt, final Padding padding) { + this(salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param padding + * 补码方式 + */ + public AESCrypto(final Charset charset, final Padding padding) { + this(charset); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public AESCrypto(final String characterEncoding, final String salt, final Padding padding) { + this(characterEncoding, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public AESCrypto(final Charset charset, final String salt, final Padding padding) { + this(charset, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public AESCrypto(final Mode mode, final Padding padding) { + this(mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public AESCrypto(final String salt, final Mode mode, final Padding padding) { + this(salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public AESCrypto(final Charset charset, final Mode mode, final Padding padding) { + this(charset, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public AESCrypto(final String characterEncoding, final String salt, final Mode mode, final Padding padding) { + this(characterEncoding, salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public AESCrypto(final Charset charset, final String salt, final Mode mode, final Padding padding) { + this(charset, salt, mode); + this.padding = padding; + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), + getSalt()); + return crypto.encrypt(object); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + + @Override + public String decrypt(final CharSequence cs) { + Assert.isNull(cs, "Mcrypt decrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, + getProvider(), getSalt()); + return crypto.decrypt(cs); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractCrypto.java index ec332bb..fabbc78 100644 --- a/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractCrypto.java +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractCrypto.java @@ -102,6 +102,20 @@ public AbstractCrypto(final Algorithm algorithm, final Charset charset) { this.charset = charset; } + /** + * 构造函数 + * + * @param algorithm + * 加密算法 + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public AbstractCrypto(final Algorithm algorithm, final String characterEncoding, final String salt) { + this(algorithm, Charset.forName(characterEncoding), salt); + } + /** * 构造函数 * @@ -130,6 +144,21 @@ public AbstractCrypto(final Algorithm algorithm, final Provider provider) { this.provider = provider; } + /** + * 构造函数 + * + * @param algorithm + * 加密算法 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public AbstractCrypto(final Algorithm algorithm, final String salt, final Provider provider) { + this(algorithm, salt); + this.provider = provider; + } + /** * 构造函数 * @@ -150,13 +179,16 @@ public AbstractCrypto(final Algorithm algorithm, final Charset charset, final Pr * * @param algorithm * 加密算法 + * @param characterEncoding + * 字符编码 * @param salt * 加密密钥 * @param provider * 信息摘要对象的提供者 */ - public AbstractCrypto(final Algorithm algorithm, final String salt, final Provider provider) { - this(algorithm, salt); + public AbstractCrypto(final Algorithm algorithm, final String characterEncoding, final String salt, + final Provider provider) { + this(algorithm, Charset.forName(characterEncoding), salt); this.provider = provider; } diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractHmacCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractHmacCrypto.java new file mode 100644 index 0000000..dbfcc33 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/AbstractHmacCrypto.java @@ -0,0 +1,115 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.utils.ObjectUtils; +import org.apache.commons.codec.digest.HmacAlgorithms; +import org.apache.commons.codec.digest.HmacUtils; + +import java.nio.charset.Charset; + +/** + * Hmac 加解密 + * + * @author Yong.Teng + * @since 2.3.0 + */ +public abstract class AbstractHmacCrypto extends AbstractCrypto { + + /** + * 构造函数 + * + * @param algorithm + * 加密算法 + */ + public AbstractHmacCrypto(final Algorithm algorithm) { + super(algorithm); + } + + /** + * 构造函数 + * + * @param algorithm + * 请求算法的名称 + * @param salt + * 加密密钥 + */ + public AbstractHmacCrypto(final Algorithm algorithm, final String salt) { + super(algorithm, salt); + } + + /** + * 构造函数 + * + * @param algorithm + * 请求算法的名称 + * @param charset + * 字符编码 + */ + public AbstractHmacCrypto(final Algorithm algorithm, final Charset charset) { + super(algorithm, charset); + } + + /** + * 构造函数 + * + * @param algorithm + * 加密算法 + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public AbstractHmacCrypto(final Algorithm algorithm, final String characterEncoding, final String salt) { + super(algorithm, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param algorithm + * 加密算法 + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public AbstractHmacCrypto(final Algorithm algorithm, final Charset charset, final String salt) { + super(algorithm, charset, salt); + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + Assert.isNull(getAlgorithm(), "Algo could not be null"); + + HmacUtils hmacUtils = new HmacUtils(getHmacAlgorithms(), getRealSalt().getBytes(getCharset())); + return hmacUtils.hmacHex(ObjectUtils.toBytes(object, getCharset())); + } + + protected abstract HmacAlgorithms getHmacAlgorithms(); + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Base64Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Base64Crypto.java new file mode 100644 index 0000000..65cfd93 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Base64Crypto.java @@ -0,0 +1,107 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + * + * ================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.utils.ObjectUtils; + +import java.nio.charset.Charset; +import java.util.Base64; + +/** + * base64 编码、解码 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Base64Crypto extends AbstractCrypto { + + /** + * 构造函数 + */ + public Base64Crypto() { + super(Algorithm.BASE64); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Base64Crypto(final String salt) { + super(Algorithm.BASE64, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Base64Crypto(final Charset charset) { + super(Algorithm.BASE64, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Base64Crypto(final String characterEncoding, final String salt) { + super(Algorithm.BASE64, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Base64Crypto(final Charset charset, final String salt) { + super(Algorithm.BASE64, charset, salt); + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null."); + return Base64.getEncoder() + .encodeToString((ObjectUtils.toString(object) + getRealSalt()).getBytes(getCharset())); + } + + @Override + public String decrypt(final CharSequence cs) { + Assert.isNull(cs, "Mcrypt decrypt object could not be null."); + return new String(Base64.getDecoder().decode(cs.toString()), getCharset()); + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/DESCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/DESCrypto.java new file mode 100644 index 0000000..1e7fbb6 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/DESCrypto.java @@ -0,0 +1,359 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + * + * ================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.internal.SymmetricalCrypto; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; +import java.nio.charset.Charset; +import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; + +/** + * DES 加密对象 + * slat 不足 16 位,以空格填充;slat 超过 16 位将截取前 16 位 + * 加密结果以 Base64 返回 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class DESCrypto extends AbstractCrypto { + + /** + * 加密模式 + */ + private Mode mode = Mode.ECB; + + /** + * 补码方式 + */ + private Padding padding = Padding.PKCS5; + + /** + * 构造函数 + */ + public DESCrypto() { + super(Algorithm.AES); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public DESCrypto(final String salt) { + super(Algorithm.AES, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public DESCrypto(final Charset charset) { + super(Algorithm.AES, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public DESCrypto(final String characterEncoding, final String salt) { + super(Algorithm.AES, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public DESCrypto(final Charset charset, final String salt) { + super(Algorithm.AES, charset, salt); + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + */ + public DESCrypto(final Mode mode) { + this(); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public DESCrypto(final String salt, final Mode mode) { + this(salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + */ + public DESCrypto(final Charset charset, final Mode mode) { + this(charset); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public DESCrypto(final String characterEncoding, final String salt, final Mode mode) { + this(characterEncoding, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public DESCrypto(final Charset charset, final String salt, final Mode mode) { + this(charset, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param padding + * 补码方式 + */ + public DESCrypto(final Padding padding) { + this(); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public DESCrypto(final String salt, final Padding padding) { + this(salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param padding + * 补码方式 + */ + public DESCrypto(final Charset charset, final Padding padding) { + this(charset); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public DESCrypto(final String characterEncoding, final String salt, final Padding padding) { + this(characterEncoding, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public DESCrypto(final Charset charset, final String salt, final Padding padding) { + this(charset, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public DESCrypto(final Mode mode, final Padding padding) { + this(mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public DESCrypto(final String salt, final Mode mode, final Padding padding) { + this(salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public DESCrypto(final Charset charset, final Mode mode, final Padding padding) { + this(charset, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public DESCrypto(final String characterEncoding, final String salt, final Mode mode, final Padding padding) { + this(characterEncoding, salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public DESCrypto(final Charset charset, final String salt, final Mode mode, final Padding padding) { + this(charset, salt, mode); + this.padding = padding; + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, + getProvider(), getKey()); + return crypto.encrypt(object); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + + @Override + public String decrypt(final CharSequence cs) { + Assert.isNull(cs, "Mcrypt decrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, + getProvider(), getKey()); + return crypto.decrypt(cs); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + + private Key getKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { + final DESKeySpec dks = new DESKeySpec(getRealSalt().getBytes()); + final SecretKeyFactory secretKeyFactory = getProvider() == null ? + SecretKeyFactory.getInstance(getAlgorithmName()) : SecretKeyFactory.getInstance(getAlgorithmName(), + getProvider()); + return secretKeyFactory.generateSecret(dks); + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/DiscuzCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/DiscuzCrypto.java new file mode 100644 index 0000000..8c5e0e4 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/DiscuzCrypto.java @@ -0,0 +1,172 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + * + * ================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.datetime.DateTime; +import com.buession.core.utils.Assert; +import com.buession.core.utils.StringUtils; +import com.buession.lang.Constants; +import com.buession.security.crypto.utils.ObjectUtils; + +import java.nio.charset.Charset; +import java.util.Optional; + +/** + * Discuz 版加解密 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class DiscuzCrypto extends AbstractCrypto { + + private final static int KEY_LENGTH = 4; + + /** + * 构造函数 + */ + public DiscuzCrypto() { + super(null); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public DiscuzCrypto(final String salt) { + super(null, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public DiscuzCrypto(final Charset charset) { + super(null, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public DiscuzCrypto(final String characterEncoding, final String salt) { + super(null, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public DiscuzCrypto(final Charset charset, final String salt) { + super(null, charset, salt); + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + + Base64Crypto crypto = new Base64Crypto(); + String s = ObjectUtils.toString(object); + + String key = md5(md5(getRealSalt())); + String keya = md5(StringUtils.substr(key, 16, 16)); + String keyb = StringUtils.substr(md5(StringUtils.replace(DateTime.microtime(), Constants.SPACING_STRING, ".")), + -4); + String keyc = getResultKey(key, keyb); + + s = StringUtils.repeat('0', 10) + StringUtils.substr(md5(s + keya), 0, 16) + s; + s = StringUtils.replace(crypto.encrypt(mod(s, keyc)), "=", Constants.EMPTY_STRING); + + return keyb + s; + } + + @Override + public String decrypt(final CharSequence cs) { + Assert.isNull(cs, "Mcrypt decrypt object could not be null"); + + Base64Crypto crypto = new Base64Crypto(); + String s = cs.toString(); + + String key = md5(md5(getRealSalt())); + String keya = md5(StringUtils.substr(key, 16, 16)); + String keyb = StringUtils.substr(cs.toString(), 0, KEY_LENGTH); + String keyc = getResultKey(key, keyb); + + s = crypto.decrypt(StringUtils.substr(s, KEY_LENGTH)); + + String result = mod(s, keyc); + + String s1 = StringUtils.substr(result, 0, 10); + String s2 = StringUtils.substr(result, 26); + long j = Long.parseLong(s1); + String k1 = md5(s2 + keya); + long timestamp = DateTime.unixtime(); + + return (j == 0 || j - timestamp > 0) && StringUtils.substr(result, 10, 16).equals(StringUtils.substr(k1, 0, + 16)) ? s2 : Constants.EMPTY_STRING; + } + + private static String md5(final String str) { + MD5Crypto crypto = new MD5Crypto(); + return crypto.encrypt(Optional.ofNullable(str).orElse(Constants.EMPTY_STRING)).toLowerCase(); + } + + private static String getResultKey(final String str, final String key) { + if(key.length() <= 16){ + return md5(key + StringUtils.substr(str, 0, 16) + StringUtils.substr(str, 16)); + }else{ + return md5(StringUtils.substr(key, 0, 16) + StringUtils.substr(key, 0, 16) + (StringUtils.substr(key, 16)) + + StringUtils.substr(str, 16)); + } + } + + private static String mod(final String str, final String key) { + int strLength = str.length(); + char[] result = new char[strLength]; + + for(int i = 0; i < strLength; i++){ + int j = str.charAt(i); + int k = key.charAt(i % 32); + + result[i] = (char) (j ^ k); + } + + return new String(result); + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacMD5Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacMD5Crypto.java new file mode 100644 index 0000000..7d10a17 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacMD5Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac MD5 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacMD5Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacMD5Crypto() { + super(Algorithm.HMAC_MD5); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacMD5Crypto(final String salt) { + super(Algorithm.HMAC_MD5, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacMD5Crypto(final Charset charset) { + super(Algorithm.HMAC_MD5, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacMD5Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_MD5, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacMD5Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_MD5, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_MD5; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha1Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha1Crypto.java new file mode 100644 index 0000000..1c383cd --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha1Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac SHA-1 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacSha1Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacSha1Crypto() { + super(Algorithm.HMAC_SHA1); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacSha1Crypto(final String salt) { + super(Algorithm.HMAC_SHA1, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacSha1Crypto(final Charset charset) { + super(Algorithm.HMAC_SHA1, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha1Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_SHA1, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha1Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_SHA1, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_SHA_1; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha224Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha224Crypto.java new file mode 100644 index 0000000..e0c863a --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha224Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac SHA-224 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacSha224Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacSha224Crypto() { + super(Algorithm.HMAC_SHA224); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacSha224Crypto(final String salt) { + super(Algorithm.HMAC_SHA224, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacSha224Crypto(final Charset charset) { + super(Algorithm.HMAC_SHA224, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha224Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_SHA224, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha224Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_SHA224, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_SHA_224; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha256Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha256Crypto.java new file mode 100644 index 0000000..9e82657 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha256Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac SHA-256 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacSha256Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacSha256Crypto() { + super(Algorithm.HMAC_SHA256); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacSha256Crypto(final String salt) { + super(Algorithm.HMAC_SHA256, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacSha256Crypto(final Charset charset) { + super(Algorithm.HMAC_SHA256, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha256Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_SHA256, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha256Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_SHA256, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_SHA_256; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha384Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha384Crypto.java new file mode 100644 index 0000000..33890e3 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha384Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac SHA-384 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacSha384Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacSha384Crypto() { + super(Algorithm.HMAC_SHA384); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacSha384Crypto(final String salt) { + super(Algorithm.HMAC_SHA384, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacSha384Crypto(final Charset charset) { + super(Algorithm.HMAC_SHA384, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha384Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_SHA384, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha384Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_SHA384, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_SHA_384; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha512Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha512Crypto.java new file mode 100644 index 0000000..1541e00 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/HmacSha512Crypto.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import org.apache.commons.codec.digest.HmacAlgorithms; + +import java.nio.charset.Charset; + +/** + * Hmac SHA-512 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class HmacSha512Crypto extends AbstractHmacCrypto implements HmacCrypto { + + /** + * 构造函数 + */ + public HmacSha512Crypto() { + super(Algorithm.HMAC_SHA512); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public HmacSha512Crypto(final String salt) { + super(Algorithm.HMAC_SHA512, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public HmacSha512Crypto(final Charset charset) { + super(Algorithm.HMAC_SHA512, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha512Crypto(final String characterEncoding, final String salt) { + super(Algorithm.HMAC_SHA512, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public HmacSha512Crypto(final Charset charset, final String salt) { + super(Algorithm.HMAC_SHA512, charset, salt); + } + + @Override + protected HmacAlgorithms getHmacAlgorithms() { + return HmacAlgorithms.HMAC_SHA_512; + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/MD5Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/MD5Crypto.java new file mode 100644 index 0000000..75875b0 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/MD5Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * MD5 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class MD5Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public MD5Crypto() { + super(Algorithm.MD5); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public MD5Crypto(final String salt) { + super(Algorithm.MD5, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public MD5Crypto(final Charset charset) { + super(Algorithm.MD5, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public MD5Crypto(final String characterEncoding, final String salt) { + super(Algorithm.MD5, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public MD5Crypto(final Charset charset, final String salt) { + super(Algorithm.MD5, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public MD5Crypto(final Provider provider) { + super(Algorithm.MD5, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public MD5Crypto(final String salt, final Provider provider) { + super(Algorithm.MD5, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public MD5Crypto(final Charset charset, final Provider provider) { + super(Algorithm.MD5, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public MD5Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.MD5, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public MD5Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.MD5, charset, salt, provider); + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha1Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha1Crypto.java new file mode 100644 index 0000000..de3ace0 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha1Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * SHA-1 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sha1Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sha1Crypto() { + super(Algorithm.SHA1); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sha1Crypto(final String salt) { + super(Algorithm.SHA1, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sha1Crypto(final Charset charset) { + super(Algorithm.SHA1, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha1Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA1, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha1Crypto(final Charset charset, final String salt) { + super(Algorithm.SHA1, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public Sha1Crypto(final Provider provider) { + super(Algorithm.SHA1, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha1Crypto(final String salt, final Provider provider) { + super(Algorithm.SHA1, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha1Crypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA1, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha1Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA1, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha1Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA1, charset, salt, provider); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha224Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha224Crypto.java new file mode 100644 index 0000000..27a7340 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha224Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * SHA-224 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sha224Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sha224Crypto() { + super(Algorithm.SHA224); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sha224Crypto(final String salt) { + super(Algorithm.SHA224, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sha224Crypto(final Charset charset) { + super(Algorithm.SHA224, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha224Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA224, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha224Crypto(final Charset charset, final String salt) { + super(Algorithm.SHA224, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public Sha224Crypto(final Provider provider) { + super(Algorithm.SHA224, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha224Crypto(final String salt, final Provider provider) { + super(Algorithm.SHA224, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha224Crypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA224, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha224Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA224, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha224Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA224, charset, salt, provider); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha256Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha256Crypto.java new file mode 100644 index 0000000..54df673 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha256Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * SHA-256 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sha256Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sha256Crypto() { + super(Algorithm.SHA256); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sha256Crypto(final String salt) { + super(Algorithm.SHA256, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sha256Crypto(final Charset charset) { + super(Algorithm.SHA256, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha256Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA256, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha256Crypto(final Charset charset, final String salt) { + super(Algorithm.SHA256, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public Sha256Crypto(final Provider provider) { + super(Algorithm.SHA256, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha256Crypto(final String salt, final Provider provider) { + super(Algorithm.SHA256, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha256Crypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA256, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha256Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA256, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha256Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA256, charset, salt, provider); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha384Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha384Crypto.java new file mode 100644 index 0000000..ce8e0db --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha384Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * SHA-384 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sha384Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sha384Crypto() { + super(Algorithm.SHA384); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sha384Crypto(final String salt) { + super(Algorithm.SHA384, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sha384Crypto(final Charset charset) { + super(Algorithm.SHA384, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha384Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA384, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha384Crypto(final Charset charset, final String salt) { + super(Algorithm.SHA384, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public Sha384Crypto(final Provider provider) { + super(Algorithm.SHA384, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha384Crypto(final String salt, final Provider provider) { + super(Algorithm.SHA384, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha384Crypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA384, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha384Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA384, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha384Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA384, charset, salt, provider); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha512Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha512Crypto.java new file mode 100644 index 0000000..f076718 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sha512Crypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * Sha-512 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sha512Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sha512Crypto() { + super(Algorithm.SHA512); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sha512Crypto(final String salt) { + super(Algorithm.SHA512, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sha512Crypto(final Charset charset) { + super(Algorithm.SHA512, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha512Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA512, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sha512Crypto(final Charset charset, final String salt) { + super(Algorithm.SHA512, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public Sha512Crypto(final Provider provider) { + super(Algorithm.SHA512, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha512Crypto(final String salt, final Provider provider) { + super(Algorithm.SHA512, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha512Crypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA512, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha512Crypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA512, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public Sha512Crypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA512, charset, salt, provider); + } + +} \ No newline at end of file diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/ShaCrypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/ShaCrypto.java new file mode 100644 index 0000000..8bae20a --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/ShaCrypto.java @@ -0,0 +1,151 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import java.nio.charset.Charset; +import java.security.Provider; + +/** + * SHA 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class ShaCrypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public ShaCrypto() { + super(Algorithm.SHA); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public ShaCrypto(final String salt) { + super(Algorithm.SHA, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public ShaCrypto(final Charset charset) { + super(Algorithm.SHA, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public ShaCrypto(final String characterEncoding, final String salt) { + super(Algorithm.SHA, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public ShaCrypto(final Charset charset, final String salt) { + super(Algorithm.SHA, charset, salt); + } + + /** + * 构造函数 + * + * @param provider + * 信息摘要对象的提供者 + */ + public ShaCrypto(final Provider provider) { + super(Algorithm.SHA, provider); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public ShaCrypto(final String salt, final Provider provider) { + super(Algorithm.SHA, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param provider + * 信息摘要对象的提供者 + */ + public ShaCrypto(final Charset charset, final Provider provider) { + super(Algorithm.SHA, charset, provider); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public ShaCrypto(final String characterEncoding, final String salt, final Provider provider) { + super(Algorithm.SHA, characterEncoding, salt, provider); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param provider + * 信息摘要对象的提供者 + */ + public ShaCrypto(final Charset charset, final String salt, final Provider provider) { + super(Algorithm.SHA, charset, salt, provider); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm3Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm3Crypto.java new file mode 100644 index 0000000..41d2117 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm3Crypto.java @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.utils.ObjectUtils; +import org.apache.commons.codec.binary.Base64; +import org.bouncycastle.crypto.digests.SM3Digest; + +import java.nio.charset.Charset; + +/** + * SM3 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sm3Crypto extends AbstractCrypto implements HashCrypto { + + /** + * 构造函数 + */ + public Sm3Crypto() { + super(Algorithm.SM3); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sm3Crypto(final String salt) { + super(Algorithm.SM3, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sm3Crypto(final Charset charset) { + super(Algorithm.SM3, charset); + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sm3Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SM3, characterEncoding, salt); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sm3Crypto(final Charset charset, final String salt) { + super(Algorithm.SM3, charset, salt); + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + + SM3Digest sm3Digest = new SM3Digest(); + byte[] salt = ObjectUtils.toBytes(getSalt(), getCharset()); + byte[] in = ObjectUtils.toBytes(object, getCharset()); + + byte[] data = new byte[salt.length + in.length]; + System.arraycopy(salt, 0, data, 0, salt.length); + System.arraycopy(in, 0, data, salt.length, in.length); + + sm3Digest.update(data, 0, data.length); + byte[] hash = new byte[sm3Digest.getDigestSize()]; + sm3Digest.doFinal(hash, 0); + + return Base64.encodeBase64String(hash); + } + +} diff --git a/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm4Crypto.java b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm4Crypto.java new file mode 100644 index 0000000..25ce535 --- /dev/null +++ b/buession-security-crypto/src/main/java/com/buession/security/crypto/Sm4Crypto.java @@ -0,0 +1,343 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package com.buession.security.crypto; + +import com.buession.core.utils.Assert; +import com.buession.security.crypto.internal.SymmetricalCrypto; +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +import java.nio.charset.Charset; +import java.security.GeneralSecurityException; + +/** + * SM4 加密对象 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public final class Sm4Crypto extends AbstractCrypto { + + /** + * 加密模式 + */ + private Mode mode = Mode.ECB; + + /** + * 补码方式 + */ + private Padding padding = Padding.PKCS5; + + /** + * 构造函数 + */ + public Sm4Crypto() { + super(Algorithm.SM4, new BouncyCastleProvider()); + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + */ + public Sm4Crypto(final String salt) { + super(Algorithm.SM4, salt, new BouncyCastleProvider()); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + */ + public Sm4Crypto(final Charset charset) { + super(Algorithm.SM4, charset, new BouncyCastleProvider()); + } + + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sm4Crypto(final String characterEncoding, final String salt) { + super(Algorithm.SM4, characterEncoding, salt, new BouncyCastleProvider()); + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + */ + public Sm4Crypto(final Charset charset, final String salt) { + super(Algorithm.SM4, charset, salt, new BouncyCastleProvider()); + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + */ + public Sm4Crypto(final Mode mode) { + this(); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public Sm4Crypto(final String salt, final Mode mode) { + this(salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + */ + public Sm4Crypto(final Charset charset, final Mode mode) { + this(charset); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public Sm4Crypto(final String characterEncoding, final String salt, final Mode mode) { + this(characterEncoding, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + */ + public Sm4Crypto(final Charset charset, final String salt, final Mode mode) { + this(charset, salt); + this.mode = mode; + } + + /** + * 构造函数 + * + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Padding padding) { + this(); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final String salt, final Padding padding) { + this(salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Charset charset, final Padding padding) { + this(charset); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final String characterEncoding, final String salt, final Padding padding) { + this(characterEncoding, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Charset charset, final String salt, final Padding padding) { + this(charset, salt); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Mode mode, final Padding padding) { + this(mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final String salt, final Mode mode, final Padding padding) { + this(salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Charset charset, final Mode mode, final Padding padding) { + this(charset, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param characterEncoding + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final String characterEncoding, final String salt, final Mode mode, final Padding padding) { + this(characterEncoding, salt, mode); + this.padding = padding; + } + + /** + * 构造函数 + * + * @param charset + * 字符编码 + * @param salt + * 加密密钥 + * @param mode + * 加密模式 + * @param padding + * 补码方式 + */ + public Sm4Crypto(final Charset charset, final String salt, final Mode mode, final Padding padding) { + this(charset, salt, mode); + this.padding = padding; + } + + @Override + public String encrypt(final Object object) { + Assert.isNull(object, "Mcrypt encrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), + getSalt()); + return crypto.encrypt(object); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + + @Override + public String decrypt(final CharSequence cs) { + Assert.isNull(cs, "Mcrypt decrypt object could not be null"); + + try{ + SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), + getSalt()); + return crypto.decrypt(cs); + }catch(GeneralSecurityException e){ + logger.error(e.getMessage()); + throw new SecurityException(e); + } + } + +} diff --git a/buession-security-mcrypt/pom.xml b/buession-security-mcrypt/pom.xml index 5e14f14..56d2a3a 100644 --- a/buession-security-mcrypt/pom.xml +++ b/buession-security-mcrypt/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-mcrypt https://security.buession.com/ diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/AESMcrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/AESMcrypt.java index 5244b15..72865fa 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/AESMcrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/AESMcrypt.java @@ -26,11 +26,9 @@ */ package com.buession.security.mcrypt; -import com.buession.core.utils.Assert; -import com.buession.security.crypto.internal.SymmetricalCrypto; +import com.buession.security.crypto.AESCrypto; import java.nio.charset.Charset; -import java.security.GeneralSecurityException; /** * AES 加密对象 @@ -550,30 +548,14 @@ public AESMcrypt(final Charset charset, final String salt, final com.buession.se @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), - getSalt()); - return crypto.encrypt(object); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } + final AESCrypto crypto = new AESCrypto(getCharset(), getSalt(), mode, padding); + return crypto.encrypt(object); } @Override public String decrypt(final CharSequence cs) { - Assert.isNull(cs, "Mcrypt decrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, - getProvider(), getSalt()); - return crypto.decrypt(cs); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } + final AESCrypto crypto = new AESCrypto(getCharset(), getSalt(), mode, padding); + return crypto.decrypt(cs); } /** diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Base64Mcrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Base64Mcrypt.java index d15c553..359b4e0 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Base64Mcrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Base64Mcrypt.java @@ -26,10 +26,7 @@ */ package com.buession.security.mcrypt; -import com.buession.core.utils.Assert; -import com.buession.security.crypto.utils.ObjectUtils; - -import java.util.Base64; +import com.buession.security.crypto.Base64Crypto; import java.nio.charset.Charset; @@ -94,15 +91,14 @@ public Base64Mcrypt(final Charset charset, final String salt) { @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null."); - return Base64.getEncoder() - .encodeToString((ObjectUtils.toString(object) + getRealSalt()).getBytes(getCharset())); + final Base64Crypto crypto = new Base64Crypto(getCharset(), getSalt()); + return crypto.encrypt(object); } @Override public String decrypt(final CharSequence cs) { - Assert.isNull(cs, "Mcrypt decrypt object could not be null."); - return new String(Base64.getDecoder().decode(cs.toString()), getCharset()); + final Base64Crypto crypto = new Base64Crypto(getCharset(), getSalt()); + return crypto.decrypt(cs); } } \ No newline at end of file diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DESMcrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DESMcrypt.java index 9c6e408..4ad633a 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DESMcrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DESMcrypt.java @@ -26,17 +26,9 @@ */ package com.buession.security.mcrypt; -import com.buession.core.utils.Assert; -import com.buession.security.crypto.internal.SymmetricalCrypto; +import com.buession.security.crypto.DESCrypto; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.DESKeySpec; import java.nio.charset.Charset; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.Key; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; /** * DES 加密对象 @@ -554,38 +546,14 @@ public DESMcrypt(final Charset charset, final String salt, final com.buession.se @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, - getProvider(), getKey()); - return crypto.encrypt(object); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } + final DESCrypto crypto = new DESCrypto(getCharset(), getSalt(), mode, padding); + return crypto.encrypt(object); } @Override public String decrypt(final CharSequence cs) { - Assert.isNull(cs, "Mcrypt decrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, - getProvider(), getKey()); - return crypto.decrypt(cs); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } - } - - private Key getKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { - final DESKeySpec dks = new DESKeySpec(getRealSalt().getBytes()); - final SecretKeyFactory secretKeyFactory = getProvider() == null ? - SecretKeyFactory.getInstance(getAlgorithmName()) : SecretKeyFactory.getInstance(getAlgorithmName(), - getProvider()); - return secretKeyFactory.generateSecret(dks); + final DESCrypto crypto = new DESCrypto(getCharset(), getSalt(), mode, padding); + return crypto.decrypt(cs); } /** diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DiscuzMycrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DiscuzMycrypt.java index 8d85e3f..e6db3eb 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DiscuzMycrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/DiscuzMycrypt.java @@ -26,12 +26,8 @@ */ package com.buession.security.mcrypt; -import com.buession.core.datetime.DateTime; -import com.buession.core.utils.Assert; -import com.buession.core.utils.StringUtils; -import com.buession.lang.Constants; import com.buession.security.crypto.Algorithm; -import com.buession.security.crypto.utils.ObjectUtils; +import com.buession.security.crypto.DiscuzCrypto; import java.nio.charset.Charset; @@ -42,8 +38,6 @@ */ public final class DiscuzMycrypt extends AbstractMcrypt { - private final static int KEY_LENGTH = 4; - /** * 构造函数 */ @@ -98,75 +92,14 @@ public DiscuzMycrypt(final Charset charset, final String salt) { @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null"); - - Base64Mcrypt base64Mcrypt = new Base64Mcrypt(); - String s = ObjectUtils.toString(object); - - String key = md5(md5(getRealSalt())); - String keya = md5(StringUtils.substr(key, 16, 16)); - String keyb = StringUtils.substr(md5(StringUtils.replace(DateTime.microtime(), Constants.SPACING_STRING, ".")), - -4); - String keyc = getResultKey(key, keyb); - - s = StringUtils.repeat('0', 10) + StringUtils.substr(md5(s + keya), 0, 16) + s; - s = StringUtils.replace(base64Mcrypt.encode(mod(s, keyc)), "=", Constants.EMPTY_STRING); - - return keyb + s; + final DiscuzCrypto crypto = new DiscuzCrypto(getCharset(), getSalt()); + return crypto.encrypt(object); } @Override public String decrypt(final CharSequence cs) { - Assert.isNull(cs, "Mcrypt decrypt object could not be null"); - - Base64Mcrypt base64Mcrypt = new Base64Mcrypt(); - String s = cs.toString(); - - String key = md5(md5(getRealSalt())); - String keya = md5(StringUtils.substr(key, 16, 16)); - String keyb = StringUtils.substr(cs.toString(), 0, KEY_LENGTH); - String keyc = getResultKey(key, keyb); - - s = base64Mcrypt.decrypt(StringUtils.substr(s, KEY_LENGTH)); - - String result = mod(s, keyc); - - String s1 = StringUtils.substr(result, 0, 10); - String s2 = StringUtils.substr(result, 26); - long j = Long.parseLong(s1); - String k1 = md5(s2 + keya); - long timestamp = DateTime.unixtime(); - - return (j == 0 || j - timestamp > 0) && StringUtils.substr(result, 10, 16).equals(StringUtils.substr(k1, 0, - 16)) ? s2 : Constants.EMPTY_STRING; - } - - private static String md5(final String str) { - MD5Mcrypt md5Mcrypt = new MD5Mcrypt(); - return md5Mcrypt.encrypt(str == null ? Constants.EMPTY_STRING : str).toLowerCase(); - } - - private static String getResultKey(final String str, final String key) { - if(key.length() <= 16){ - return md5(key + StringUtils.substr(str, 0, 16) + StringUtils.substr(str, 16)); - }else{ - return md5(StringUtils.substr(key, 0, 16) + StringUtils.substr(key, 0, 16) + (StringUtils.substr(key, 16)) + - StringUtils.substr(str, 16)); - } - } - - private static String mod(final String str, final String key) { - int strLength = str.length(); - char[] result = new char[strLength]; - - for(int i = 0; i < strLength; i++){ - int j = str.charAt(i); - int k = key.charAt(i % 32); - - result[i] = (char) (j ^ k); - } - - return new String(result); + final DiscuzCrypto crypto = new DiscuzCrypto(getCharset(), getSalt()); + return crypto.decrypt(cs); } } \ No newline at end of file diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm3Mcrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm3Mcrypt.java index 50da930..3cdac14 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm3Mcrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm3Mcrypt.java @@ -24,11 +24,8 @@ */ package com.buession.security.mcrypt; -import com.buession.core.utils.Assert; import com.buession.security.crypto.HashCrypto; -import com.buession.security.crypto.utils.ObjectUtils; -import org.apache.commons.codec.binary.Base64; -import org.bouncycastle.crypto.digests.SM3Digest; +import com.buession.security.crypto.Sm3Crypto; import java.nio.charset.Charset; @@ -94,21 +91,8 @@ public Sm3Mcrypt(final Charset charset, final String salt) { @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null"); - - SM3Digest sm3Digest = new SM3Digest(); - byte[] salt = ObjectUtils.toBytes(getSalt(), getCharset()); - byte[] in = ObjectUtils.toBytes(object, getCharset()); - - byte[] data = new byte[salt.length + in.length]; - System.arraycopy(salt, 0, data, 0, salt.length); - System.arraycopy(in, 0, data, salt.length, in.length); - - sm3Digest.update(data, 0, data.length); - byte[] hash = new byte[sm3Digest.getDigestSize()]; - sm3Digest.doFinal(hash, 0); - - return Base64.encodeBase64String(hash); + final Sm3Crypto crypto = new Sm3Crypto(getCharset(), getSalt()); + return crypto.encrypt(object); } } diff --git a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm4Mcrypt.java b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm4Mcrypt.java index 5825894..a44a231 100644 --- a/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm4Mcrypt.java +++ b/buession-security-mcrypt/src/main/java/com/buession/security/mcrypt/Sm4Mcrypt.java @@ -24,14 +24,12 @@ */ package com.buession.security.mcrypt; -import com.buession.core.utils.Assert; import com.buession.security.crypto.Mode; import com.buession.security.crypto.Padding; -import com.buession.security.crypto.internal.SymmetricalCrypto; +import com.buession.security.crypto.Sm4Crypto; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.nio.charset.Charset; -import java.security.GeneralSecurityException; /** * SM4 加密对象 @@ -295,30 +293,14 @@ public Sm4Mcrypt(final Charset charset, final String salt, final Mode mode, fina @Override public String encrypt(final Object object) { - Assert.isNull(object, "Mcrypt encrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), - getSalt()); - return crypto.encrypt(object); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } + final Sm4Crypto crypto = new Sm4Crypto(getCharset(), getSalt(), mode, padding); + return crypto.encrypt(object); } @Override public String decrypt(final CharSequence cs) { - Assert.isNull(cs, "Mcrypt decrypt object could not be null"); - - try{ - SymmetricalCrypto crypto = new SymmetricalCrypto(getAlgorithm(), getCharset(), mode, padding, getProvider(), - getSalt()); - return crypto.decrypt(cs); - }catch(GeneralSecurityException e){ - logger.error(e.getMessage()); - throw new SecurityException(e); - } + final Sm4Crypto crypto = new Sm4Crypto(getCharset(), getSalt(), mode, padding); + return crypto.decrypt(cs); } } diff --git a/buession-security-pac4j/pom.xml b/buession-security-pac4j/pom.xml index 06e0ef7..7ce11c5 100644 --- a/buession-security-pac4j/pom.xml +++ b/buession-security-pac4j/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-pac4j https://security.buession.com/ @@ -160,6 +160,12 @@ org.pac4j pac4j-cas + + + org.bouncycastle + * + + org.pac4j diff --git a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/PrincipalAnnotationUtils.java b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/PrincipalAnnotationUtils.java index 0d0f7d6..18a5ffa 100644 --- a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/PrincipalAnnotationUtils.java +++ b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/PrincipalAnnotationUtils.java @@ -38,6 +38,28 @@ public class PrincipalAnnotationUtils { private final static Logger logger = LoggerFactory.getLogger(PrincipalAnnotationUtils.class); + /** + * 判断是否支持 + * + * @param parameter + * {@link MethodParameter} + * + * @return true / false + * + * @since 2.3.2 + */ + public static boolean supportsParameter(MethodParameter parameter) { + if(parameter.hasParameterAnnotation(Principal.class) == true){ + final Class parameterType = parameter.getParameterType(); + + return parameterType.isPrimitive() == false && parameterType.isArray() == false && + parameterType.isAnnotation() == false && parameterType.isEnum() == false && + parameterType.isInterface() == false; + } + + return false; + } + public static T toObject(final Pac4jPrincipal principal, final Principal annotation, final Class paramType) { if(principal == null){ return null; diff --git a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/reactive/PrincipalMethodArgumentResolver.java b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/reactive/PrincipalMethodArgumentResolver.java index fc44a16..64c1465 100644 --- a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/reactive/PrincipalMethodArgumentResolver.java +++ b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/reactive/PrincipalMethodArgumentResolver.java @@ -33,9 +33,8 @@ import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.core.MethodParameter; import org.springframework.core.ReactiveAdapterRegistry; -import org.springframework.web.reactive.result.method.annotation.AbstractNamedValueArgumentResolver; +import org.springframework.web.reactive.result.method.annotation.AbstractNamedValueSyncArgumentResolver; import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; /** * 方法参数注解 {@link Principal} 解析器 @@ -43,7 +42,7 @@ * @author Yong.Teng * @since 2.1.0 */ -public class PrincipalMethodArgumentResolver extends AbstractNamedValueArgumentResolver { +public class PrincipalMethodArgumentResolver extends AbstractNamedValueSyncArgumentResolver { public PrincipalMethodArgumentResolver(ConfigurableBeanFactory factory, ReactiveAdapterRegistry registry) { super(factory, registry); @@ -51,18 +50,18 @@ public PrincipalMethodArgumentResolver(ConfigurableBeanFactory factory, Reactive @Override public boolean supportsParameter(MethodParameter parameter) { - return parameter.hasParameterAnnotation(Principal.class); + return PrincipalAnnotationUtils.supportsParameter(parameter); } @Override - protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { - Principal principal = parameter.getParameterAnnotation(Principal.class); + protected NamedValueInfo createNamedValueInfo(MethodParameter methodParameter) { + Principal principal = methodParameter.getParameterAnnotation(Principal.class); Assert.isNull(principal, "No Principal annotation"); - return new PrincipalNamedValueInfo(principal, parameter.getNestedParameterType()); + return new PrincipalNamedValueInfo(principal, methodParameter.getNestedParameterType()); } @Override - protected Mono resolveName(String name, MethodParameter parameter, ServerWebExchange exchange) { + protected Object resolveNamedValue(String name, MethodParameter parameter, ServerWebExchange exchange) { return exchange.getPrincipal() .map((principal)->PrincipalAnnotationUtils.resolve(parameter, (Pac4jPrincipal) principal)); } diff --git a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/servlet/PrincipalMethodArgumentResolver.java b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/servlet/PrincipalMethodArgumentResolver.java index cdffbcb..8024b6e 100644 --- a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/servlet/PrincipalMethodArgumentResolver.java +++ b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/annotation/servlet/PrincipalMethodArgumentResolver.java @@ -53,7 +53,7 @@ public PrincipalMethodArgumentResolver(@Nullable ConfigurableBeanFactory beanFac @Override public boolean supportsParameter(MethodParameter parameter) { - return parameter.hasParameterAnnotation(Principal.class); + return PrincipalAnnotationUtils.supportsParameter(parameter); } @Override diff --git a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/profile/ProfileUtils.java b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/profile/ProfileUtils.java index 6d43c13..6c6e919 100644 --- a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/profile/ProfileUtils.java +++ b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/profile/ProfileUtils.java @@ -24,6 +24,8 @@ */ package com.buession.security.pac4j.profile; +import com.buession.beans.BeanConverter; +import com.buession.beans.DefaultBeanConverter; import io.buji.pac4j.subject.Pac4jPrincipal; import org.pac4j.core.profile.CommonProfile; import org.springframework.beans.BeanUtils; @@ -99,10 +101,14 @@ public static Map toMap(final CommonProfile profile) { * @since 2.3.0 */ public static T toObject(final CommonProfile profile, final Class type) { - T instance = BeanUtils.instantiateClass(type); + final T instance = BeanUtils.instantiateClass(type); - com.buession.beans.BeanUtils.populate(instance, profile); - com.buession.beans.BeanUtils.populate(instance, profile.getAttributes()); + if(profile != null){ + final BeanConverter beanConverter = new DefaultBeanConverter(); + + beanConverter.convert(profile, instance); + beanConverter.convert(profile.getAttributes(), instance); + } return instance; } diff --git a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/spring/reactive/Pac4jWebFluxConfigurerAdapter.java b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/spring/reactive/Pac4jWebFluxConfigurerAdapter.java index d5c8a58..6f67151 100644 --- a/buession-security-pac4j/src/main/java/com/buession/security/pac4j/spring/reactive/Pac4jWebFluxConfigurerAdapter.java +++ b/buession-security-pac4j/src/main/java/com/buession/security/pac4j/spring/reactive/Pac4jWebFluxConfigurerAdapter.java @@ -30,7 +30,7 @@ import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.core.ReactiveAdapterRegistry; -import org.springframework.lang.Nullable; +import org.springframework.lang.NonNull; import org.springframework.web.reactive.config.WebFluxConfigurer; import org.springframework.web.reactive.result.method.annotation.ArgumentResolverConfigurer; @@ -46,14 +46,14 @@ public class Pac4jWebFluxConfigurerAdapter implements WebFluxConfigurer { private final ReactiveAdapterRegistry registry; - public Pac4jWebFluxConfigurerAdapter(@Nullable ConfigurableBeanFactory factory, - ReactiveAdapterRegistry registry){ + public Pac4jWebFluxConfigurerAdapter(@NonNull ConfigurableBeanFactory factory, + @NonNull ReactiveAdapterRegistry registry) { this.factory = factory; this.registry = registry; } @Override - public void configureArgumentResolvers(ArgumentResolverConfigurer configurer){ + public void configureArgumentResolvers(ArgumentResolverConfigurer configurer) { configurer.addCustomResolver(new PrincipalMethodArgumentResolver(factory, registry)); } diff --git a/buession-security-parent/pom.xml b/buession-security-parent/pom.xml index 852ec1a..d931b6f 100644 --- a/buession-security-parent/pom.xml +++ b/buession-security-parent/pom.xml @@ -7,13 +7,13 @@ com.buession parent - 2.3.1 + 2.3.2 com.buession.security buession-security-parent https://security.buession.com/ Buession Security Framework Parent - 2.3.1 + 2.3.2 pom @@ -65,7 +65,7 @@ - 2.3.1 + 2.3.2 diff --git a/buession-security-shiro/pom.xml b/buession-security-shiro/pom.xml index 5064320..6b846a1 100644 --- a/buession-security-shiro/pom.xml +++ b/buession-security-shiro/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-shiro https://security.buession.com/ @@ -95,9 +95,8 @@ true - javax.servlet.jsp - javax.servlet.jsp-api - 2.3.3 + jakarta.servlet.jsp + jakarta.servlet.jsp-api provided true diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCache.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCache.java index 1b166c1..218bfb3 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCache.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCache.java @@ -146,7 +146,7 @@ public RedisCache(RedisManager redisManager, String keyPrefix, int expire, Strin * * @since 1.2.2 */ - public RedisCache(RedisSerializer keySerializer, RedisSerializer valueSerializer) { + public RedisCache(RedisSerializer keySerializer, RedisSerializer valueSerializer) { setKeySerializer(keySerializer); setValueSerializer(valueSerializer); } @@ -166,7 +166,7 @@ public RedisCache(RedisSerializer keySerializer, RedisSerializer * @since 1.2.2 */ public RedisCache(String keyPrefix, int expire, RedisSerializer keySerializer, - RedisSerializer valueSerializer) { + RedisSerializer valueSerializer) { super(keyPrefix, expire); setKeySerializer(keySerializer); setValueSerializer(valueSerializer); @@ -189,7 +189,7 @@ public RedisCache(String keyPrefix, int expire, RedisSerializer keySeria * @since 1.2.2 */ public RedisCache(String keyPrefix, int expire, String principalIdFieldName, RedisSerializer keySerializer - , RedisSerializer valueSerializer) { + , RedisSerializer valueSerializer) { super(keyPrefix, expire, principalIdFieldName); setKeySerializer(keySerializer); setValueSerializer(valueSerializer); @@ -212,7 +212,7 @@ public RedisCache(String keyPrefix, int expire, String principalIdFieldName, Red * @since 1.2.2 */ public RedisCache(RedisManager redisManager, String keyPrefix, int expire, RedisSerializer keySerializer, - RedisSerializer valueSerializer) { + RedisSerializer valueSerializer) { this(keyPrefix, expire); setRedisManager(redisManager); setKeySerializer(keySerializer); @@ -238,7 +238,7 @@ public RedisCache(RedisManager redisManager, String keyPrefix, int expire, Redis * @since 1.2.2 */ public RedisCache(RedisManager redisManager, String keyPrefix, int expire, String principalIdFieldName, - RedisSerializer keySerializer, RedisSerializer valueSerializer) { + RedisSerializer keySerializer, RedisSerializer valueSerializer) { this(keyPrefix, expire, principalIdFieldName); setRedisManager(redisManager); setKeySerializer(keySerializer); @@ -285,9 +285,8 @@ public void setKeySerializer(RedisSerializer keySerializer) { * * @since 1.2.2 */ - @SuppressWarnings({"unchecked"}) - public RedisSerializer getValueSerializer() { - return (RedisSerializer) valueSerializer; + public RedisSerializer getValueSerializer() { + return valueSerializer; } /** @@ -298,10 +297,9 @@ public RedisSerializer getValueSerializer() { * * @since 1.2.2 */ - @SuppressWarnings({"unchecked"}) - public void setValueSerializer(RedisSerializer valueSerializer) { + public void setValueSerializer(RedisSerializer valueSerializer) { Assert.isNull(valueSerializer, "Value serializer could not be null."); - this.valueSerializer = (RedisSerializer) valueSerializer; + this.valueSerializer = valueSerializer; } @Override @@ -425,8 +423,7 @@ public Collection values() { Set keys; try{ - byte[] pattern = makeKey("*"); - keys = redisManager.keys(pattern); + keys = redisManager.keys(makeKey("*")); }catch(SerializerException e){ logger.error("Get cache values error", e); return Collections.emptySet(); @@ -507,9 +504,8 @@ private String getIdObj(Object principalObject, Method principalIdGetter) { try{ Object idObj = principalIdGetter.invoke(principalObject); - if(idObj == null){ - throw new PrincipalIdNullException(principalObject.getClass(), getPrincipalIdFieldName()); - } + Assert.isNull(idObj, + ()->new PrincipalIdNullException(principalObject.getClass(), getPrincipalIdFieldName())); return idObj.toString(); }catch(Exception e){ diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCacheManager.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCacheManager.java index 96df3db..e5b404a 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCacheManager.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/cache/RedisCacheManager.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.shiro.cache; @@ -314,17 +314,12 @@ public Cache getCache(String name) throws CacheException { logger.debug("Get cache name: {}", name); } - Cache cache = caches.get(name); - - if(cache == null){ + return caches.computeIfAbsent(name, (key)->{ String principalIdFieldName = Validate.isEmpty( getPrincipalIdFieldName()) ? DEFAULT_PRINCIPAL_ID_FIELD_NAME : getPrincipalIdFieldName(); - cache = new RedisCache<>(redisManager, makeKey(name), getExpire(), principalIdFieldName, + return new RedisCache<>(redisManager, makeKey(name), getExpire(), principalIdFieldName, getKeySerializer(), getValueSerializer()); - caches.put(name, cache); - } - - return cache; + }); } protected String makeKey(final String key) { diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/exception/PrincipalInstanceException.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/exception/PrincipalInstanceException.java index c769744..934b941 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/exception/PrincipalInstanceException.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/exception/PrincipalInstanceException.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.shiro.exception; @@ -31,24 +31,24 @@ public class PrincipalInstanceException extends RuntimeException { private final static long serialVersionUID = 8772605457174103686L; - public PrincipalInstanceException(Class clazz, String idMethodName){ + public PrincipalInstanceException(Class clazz, String idMethodName) { super(formatMessage(clazz, idMethodName)); } - public PrincipalInstanceException(Class clazz, String idMethodName, Exception e){ + public PrincipalInstanceException(Class clazz, String idMethodName, Exception e) { super(formatMessage(clazz, idMethodName), e); } - protected static String formatMessage(Class clazz, String idMethodName){ + protected static String formatMessage(Class clazz, String idMethodName) { final StringBuilder sb = new StringBuilder(); - sb.append(clazz).append(" must has getter for field: ").append(idMethodName).append("; "); + sb.append(clazz.getName()).append(" must has getter for field: ").append(idMethodName).append("; "); sb.append("We need a field to identify this Cache Object. "); sb.append("So you need to defined an id field which you can get unique id to identify this principal. "); - sb.append("For example, ").append("if you use UserInfo as Principal class, "); + sb.append("For example, if you use UserInfo as Principal class, "); sb.append("the id field maybe userId, email, etc. For example, getUserId(), getEmail(), etc."); sb.append("Default value is \"id\", ") - .append("that means your principal object has a method called \"getId()\""); + .append("that means your principal object has a method called \"getId()\"."); return sb.toString(); } diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/ObjectSerializer.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/ObjectSerializer.java index 8137bb7..1a6af8a 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/ObjectSerializer.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/ObjectSerializer.java @@ -32,6 +32,11 @@ import com.buession.core.serializer.SerializerException; /** + * 类型为 T 的对象序列化和反序列化 + * + * @param + * 对象类型引用 + * * @author Yong.Teng */ public class ObjectSerializer implements RedisSerializer { @@ -41,12 +46,12 @@ public class ObjectSerializer implements RedisSerializer { private final static ByteArrayDeserializer DESERIALIZER = new DefaultByteArrayDeserializer(); @Override - public byte[] serialize(T object) throws SerializerException{ + public byte[] serialize(T object) throws SerializerException { return SERIALIZER.serializeAsBytes(object); } @Override - public T deserialize(byte[] bytes) throws DeserializerException{ + public T deserialize(byte[] bytes) throws DeserializerException { return DESERIALIZER.deserialize(bytes); } diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/RedisSerializer.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/RedisSerializer.java index 6a5f9ab..7bda7c5 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/RedisSerializer.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/RedisSerializer.java @@ -28,12 +28,39 @@ import com.buession.core.serializer.SerializerException; /** + * Redis 序列化和反序列化 + * + * @param + * 对象类型引用 + * * @author Yong.Teng */ public interface RedisSerializer { + /** + * 将类型为 V 的对象序列化为字节数组 + * + * @param v + * 对象 + * + * @return byte 数组 + * + * @throws SerializerException + * 序列化异常 + */ byte[] serialize(V v) throws SerializerException; + /** + * 将字节数组反序列化为 V 对象 + * + * @param bytes + * 字节数组 + * + * @return V 对象 + * + * @throws DeserializerException + * 反序列化异常 + */ V deserialize(byte[] bytes) throws DeserializerException; } diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/StringSerializer.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/StringSerializer.java index fdaae20..4dadb36 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/StringSerializer.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/serializer/StringSerializer.java @@ -31,27 +31,29 @@ import java.nio.charset.StandardCharsets; /** + * 字符串序列化和反序列化 + * * @author Yong.Teng */ public class StringSerializer implements RedisSerializer { private Charset charset = StandardCharsets.UTF_8; - public Charset getCharset(){ + public Charset getCharset() { return charset; } - public void setCharset(Charset charset){ + public void setCharset(Charset charset) { this.charset = charset; } @Override - public byte[] serialize(String v) throws SerializerException{ + public byte[] serialize(String v) throws SerializerException { return v == null ? null : v.getBytes(getCharset()); } @Override - public String deserialize(byte[] bytes) throws DeserializerException{ + public String deserialize(byte[] bytes) throws DeserializerException { return bytes == null ? null : new String(bytes, getCharset()); } diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/session/MemorySessionDAO.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/session/MemorySessionDAO.java index 511ff9c..6927630 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/session/MemorySessionDAO.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/session/MemorySessionDAO.java @@ -43,24 +43,24 @@ class MemorySessionDAO extends org.apache.shiro.session.mgt.eis.MemorySessionDAO private final static Logger logger = LoggerFactory.getLogger(MemorySessionDAO.class); - public MemorySessionDAO(final long sessionTimeout){ + public MemorySessionDAO(final long sessionTimeout) { super(); this.sessionTimeout = sessionTimeout; } @Override - protected Serializable doCreate(Session session){ + protected Serializable doCreate(Session session) { session.setTimeout(sessionTimeout); return super.doCreate(session); } - public void clearExpiredSession(){ + public void clearExpiredSession() { logger.debug("Clean expired session in memory."); Collection activeSessions = getActiveSessions(); if(activeSessions == null){ return; } - + for(Session session : activeSessions){ if(System.currentTimeMillis() - session.getStartTimestamp().getTime() >= session.getTimeout()){ delete(session); diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/session/mgt/DefaultWebSessionManager.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/session/mgt/DefaultWebSessionManager.java index b9ee208..0885356 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/session/mgt/DefaultWebSessionManager.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/session/mgt/DefaultWebSessionManager.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.shiro.session.mgt; @@ -57,9 +57,11 @@ public DefaultWebSessionManager() { protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException { Serializable sessionId = getSessionId(sessionKey); if(sessionId == null){ - logger.debug( - "Unable to resolve session ID from SessionKey [{}]. Returning null to indicate a session could not be found.", - sessionKey); + if(logger.isDebugEnabled()){ + logger.debug( + "Unable to resolve session ID from SessionKey [{}]. Returning null to indicate a session could not be found.", + sessionKey); + } return null; } diff --git a/buession-security-shiro/src/main/java/com/buession/security/shiro/support/ViewSupport.java b/buession-security-shiro/src/main/java/com/buession/security/shiro/support/ViewSupport.java index badfa05..77f6807 100644 --- a/buession-security-shiro/src/main/java/com/buession/security/shiro/support/ViewSupport.java +++ b/buession-security-shiro/src/main/java/com/buession/security/shiro/support/ViewSupport.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.shiro.support; @@ -58,7 +58,7 @@ public interface ViewSupport { * * @return 用户是否已通过认证 */ - default boolean isAuthenticated(){ + default boolean isAuthenticated() { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.isAuthenticated(); } @@ -68,7 +68,7 @@ default boolean isAuthenticated(){ * * @return 用户是否未通过认证 */ - default boolean isNotAuthenticated(){ + default boolean isNotAuthenticated() { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.isAuthenticated(); } @@ -78,7 +78,7 @@ default boolean isNotAuthenticated(){ * * @return 用户是否为访客 */ - default boolean isGuest(){ + default boolean isGuest() { Subject subject = SecurityUtils.getSubject(); return subject == null || subject.getPrincipal() == null; } @@ -88,7 +88,7 @@ default boolean isGuest(){ * * @return 用户是否认证通过或已记住的用户 */ - default boolean isUser(){ + default boolean isUser() { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.getPrincipal() != null; } @@ -98,7 +98,7 @@ default boolean isUser(){ * * @return 用户是通过记住我登录的 */ - default boolean isRemembered(){ + default boolean isRemembered() { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.isRemembered(); } @@ -108,7 +108,7 @@ default boolean isRemembered(){ * * @return 用户 Principal */ - default Object getPrincipal(){ + default Object getPrincipal() { Subject subject = SecurityUtils.getSubject(); return subject != null ? subject.getPrincipal() : null; } @@ -121,7 +121,7 @@ default Object getPrincipal(){ * * @return 用户属性 */ - default Object getPrincipalProperty(String property){ + default Object getPrincipalProperty(String property) { Assert.isBlank(property, "property must be contains character."); Subject subject = SecurityUtils.getSubject(); @@ -138,7 +138,7 @@ default Object getPrincipalProperty(String property){ for(PropertyDescriptor pd : propertyDescriptors){ if(property.equals(pd.getName())){ - return pd.getReadMethod().invoke(principal, (Object[]) null); + return pd.getReadMethod().invoke(principal); } } @@ -164,7 +164,7 @@ default Object getPrincipalProperty(String property){ * * @return 用户是否具备某角色 */ - default boolean hasRole(String roleName){ + default boolean hasRole(String roleName) { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.hasRole(roleName); } @@ -177,7 +177,7 @@ default boolean hasRole(String roleName){ * * @return 用户是否不具备某角色 */ - default boolean lacksRole(String roleName){ + default boolean lacksRole(String roleName) { return hasRole(roleName) == false; } @@ -192,7 +192,7 @@ default boolean lacksRole(String roleName){ * @return 用户是否具有以下任意一个角色 */ @Deprecated - default boolean hasAnyRoles(String roleNames, String delimiter){ + default boolean hasAnyRoles(String roleNames, String delimiter) { return hasAnyRole(roleNames, delimiter); } @@ -208,7 +208,7 @@ default boolean hasAnyRoles(String roleNames, String delimiter){ * * @since 1.3.2 */ - default boolean hasAnyRole(String roleNames, String delimiter){ + default boolean hasAnyRole(String roleNames, String delimiter) { return hasAnyRole(StringUtils.split(roleNames, Validate.isBlank(delimiter) ? ROLE_NAMES_DELIMITER : delimiter)); } @@ -221,7 +221,7 @@ default boolean hasAnyRole(String roleNames, String delimiter){ * @return 用户是否具有以下任意一个角色 */ @Deprecated - default boolean hasAnyRoles(String roleNames){ + default boolean hasAnyRoles(String roleNames) { return hasAnyRole(roleNames); } @@ -233,7 +233,7 @@ default boolean hasAnyRoles(String roleNames){ * * @return 用户是否具有以下任意一个角色 */ - default boolean hasAnyRole(String roleNames){ + default boolean hasAnyRole(String roleNames) { return hasAnyRole(roleNames, ROLE_NAMES_DELIMITER); } @@ -246,7 +246,7 @@ default boolean hasAnyRole(String roleNames){ * @return 用户是否具有以下任意一个角色 */ @Deprecated - default boolean hasAnyRoles(Collection roleNames){ + default boolean hasAnyRoles(Collection roleNames) { return hasAnyRole(roleNames); } @@ -260,20 +260,13 @@ default boolean hasAnyRoles(Collection roleNames){ * * @since 1.3.2 */ - default boolean hasAnyRole(Collection roleNames){ - if(Validate.isNotEmpty(roleNames)){ - Subject subject = SecurityUtils.getSubject(); - - if(subject != null){ - for(String role : roleNames){ - if(role != null && subject.hasRole(role.trim())){ - return true; - } - } - } + default boolean hasAnyRole(Collection roleNames) { + if(Validate.isEmpty(roleNames)){ + return false; } - return false; + Subject subject = SecurityUtils.getSubject(); + return subject != null && roleNames.stream().anyMatch((role)->role != null && subject.hasRole(role.trim())); } /** @@ -285,7 +278,7 @@ default boolean hasAnyRole(Collection roleNames){ * @return 用户是否具有以下任意一个角色 */ @Deprecated - default boolean hasAnyRoles(String... roleNames){ + default boolean hasAnyRoles(String... roleNames) { return hasAnyRole(roleNames); } @@ -299,20 +292,14 @@ default boolean hasAnyRoles(String... roleNames){ * * @since 1.3.2 */ - default boolean hasAnyRole(String... roleNames){ - if(Validate.isNotEmpty(roleNames)){ - Subject subject = SecurityUtils.getSubject(); - - if(subject != null){ - for(String role : roleNames){ - if(role != null && subject.hasRole(role.trim())){ - return true; - } - } - } + default boolean hasAnyRole(String... roleNames) { + if(Validate.isEmpty(roleNames)){ + return false; } - return false; + Subject subject = SecurityUtils.getSubject(); + return subject != null && + Arrays.stream(roleNames).anyMatch((role)->role != null && subject.hasRole(role.trim())); } /** @@ -325,7 +312,7 @@ default boolean hasAnyRole(String... roleNames){ * * @return 用户是否具有以下所有角色 */ - default boolean hasRolesAll(String roleNames, String delimiter){ + default boolean hasRolesAll(String roleNames, String delimiter) { return hasRolesAll( StringUtils.split(roleNames, Validate.isBlank(delimiter) ? ROLE_NAMES_DELIMITER : delimiter)); } @@ -338,7 +325,7 @@ default boolean hasRolesAll(String roleNames, String delimiter){ * * @return 用户是否具有以下所有角色 */ - default boolean hasRolesAll(String roleNames){ + default boolean hasRolesAll(String roleNames) { return hasRolesAll(roleNames, ROLE_NAMES_DELIMITER); } @@ -350,7 +337,7 @@ default boolean hasRolesAll(String roleNames){ * * @return 用户是否具有以下所有角色 */ - default boolean hasRolesAll(Collection roleNames){ + default boolean hasRolesAll(Collection roleNames) { if(Validate.isEmpty(roleNames)){ return false; } @@ -369,7 +356,7 @@ default boolean hasRolesAll(Collection roleNames){ * * @since 1.3.2 */ - default boolean hasRolesAll(String... roleNames){ + default boolean hasRolesAll(String... roleNames) { return Validate.isNotEmpty(roleNames) && hasRolesAll(Arrays.asList(roleNames)); } @@ -381,7 +368,7 @@ default boolean hasRolesAll(String... roleNames){ * * @return 用户是否具备某权限 */ - default boolean hasPermission(String permission){ + default boolean hasPermission(String permission) { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.isPermitted(permission); } @@ -394,7 +381,7 @@ default boolean hasPermission(String permission){ * * @return 用户是否具备某权限 */ - default boolean hasPermission(Permission permission){ + default boolean hasPermission(Permission permission) { Subject subject = SecurityUtils.getSubject(); return subject != null && subject.isPermitted(permission); } @@ -407,7 +394,7 @@ default boolean hasPermission(Permission permission){ * * @return 用户是否不具备某权限 */ - default boolean lacksPermission(String permission){ + default boolean lacksPermission(String permission) { return hasPermission(permission) == false; } @@ -422,7 +409,7 @@ default boolean lacksPermission(String permission){ * @return 用户是否具有以下任意一个权限 */ @Deprecated - default boolean hasAnyPermissions(String permissions, String delimiter){ + default boolean hasAnyPermissions(String permissions, String delimiter) { return hasAnyPermission(permissions, delimiter); } @@ -438,7 +425,7 @@ default boolean hasAnyPermissions(String permissions, String delimiter){ * * @since 1.3.2 */ - default boolean hasAnyPermission(String permissions, String delimiter){ + default boolean hasAnyPermission(String permissions, String delimiter) { return hasAnyPermission( StringUtils.split(permissions, Validate.isBlank(delimiter) ? PERMISSION_NAMES_DELIMITER : delimiter)); } @@ -452,7 +439,7 @@ default boolean hasAnyPermission(String permissions, String delimiter){ * @return 用户是否具有以下任意一个权限 */ @Deprecated - default boolean hasAnyPermissions(String permissions){ + default boolean hasAnyPermissions(String permissions) { return hasAnyPermission(permissions); } @@ -464,7 +451,7 @@ default boolean hasAnyPermissions(String permissions){ * * @return 用户是否具有以下任意一个权限 */ - default boolean hasAnyPermission(String permissions){ + default boolean hasAnyPermission(String permissions) { return hasAnyPermission(permissions, PERMISSION_NAMES_DELIMITER); } @@ -477,7 +464,7 @@ default boolean hasAnyPermission(String permissions){ * @return 用户是否具有以下任意一个权限 */ @Deprecated - default boolean hasAnyPermissions(Collection permissions){ + default boolean hasAnyPermissions(Collection permissions) { return hasAnyPermission(permissions); } @@ -489,20 +476,14 @@ default boolean hasAnyPermissions(Collection permissions){ * * @return 用户是否具有以下任意一个权限 */ - default boolean hasAnyPermission(Collection permissions){ - if(Validate.isNotEmpty(permissions)){ - Subject subject = SecurityUtils.getSubject(); - - if(subject != null){ - for(String permission : permissions){ - if(permission != null && subject.isPermitted(permission.trim())){ - return true; - } - } - } + default boolean hasAnyPermission(Collection permissions) { + if(Validate.isEmpty(permissions)){ + return false; } - return false; + Subject subject = SecurityUtils.getSubject(); + return permissions.stream() + .anyMatch((permission)->permission != null && subject.isPermitted(permission.trim())); } /** @@ -514,7 +495,7 @@ default boolean hasAnyPermission(Collection permissions){ * @return 用户是否具有以下任意一个权限 */ @Deprecated - default boolean hasAnyPermissions(String... permissions){ + default boolean hasAnyPermissions(String... permissions) { return hasAnyPermission(permissions); } @@ -526,20 +507,14 @@ default boolean hasAnyPermissions(String... permissions){ * * @return 用户是否具有以下任意一个权限 */ - default boolean hasAnyPermission(String... permissions){ - if(Validate.isNotEmpty(permissions)){ - Subject subject = SecurityUtils.getSubject(); - - if(subject != null){ - for(String permission : permissions){ - if(permission != null && subject.isPermitted(permission.trim())){ - return true; - } - } - } + default boolean hasAnyPermission(String... permissions) { + if(Validate.isEmpty(permissions)){ + return false; } - return false; + Subject subject = SecurityUtils.getSubject(); + return subject != null && Arrays.stream(permissions) + .anyMatch((permission)->permission != null && subject.isPermitted(permission.trim())); } /** @@ -553,7 +528,7 @@ default boolean hasAnyPermission(String... permissions){ * @since 1.3.2 */ @Deprecated - default boolean hasAnyPermissions(Permission... permissions){ + default boolean hasAnyPermissions(Permission... permissions) { return hasAnyPermission(permissions); } @@ -565,20 +540,14 @@ default boolean hasAnyPermissions(Permission... permissions){ * * @return 用户是否具有以下任意一个权限 */ - default boolean hasAnyPermission(Permission... permissions){ - if(Validate.isNotEmpty(permissions)){ - Subject subject = SecurityUtils.getSubject(); - - if(subject != null){ - for(Permission permission : permissions){ - if(permission != null && subject.isPermitted(permission)){ - return true; - } - } - } + default boolean hasAnyPermission(Permission... permissions) { + if(Validate.isEmpty(permissions)){ + return false; } - return false; + Subject subject = SecurityUtils.getSubject(); + return subject != null && Arrays.stream(permissions) + .anyMatch((permission)->permission != null && subject.isPermitted(permission)); } /** @@ -591,7 +560,7 @@ default boolean hasAnyPermission(Permission... permissions){ * * @return 用户是否具有以下所有权限 */ - default boolean hasPermissionsAll(String permissions, String delimiter){ + default boolean hasPermissionsAll(String permissions, String delimiter) { return hasPermissionsAll( StringUtils.split(permissions, Validate.isBlank(delimiter) ? PERMISSION_NAMES_DELIMITER : delimiter)); } @@ -604,7 +573,7 @@ default boolean hasPermissionsAll(String permissions, String delimiter){ * * @return 用户是否具有以下所有权限 */ - default boolean hasPermissionsAll(String permissions){ + default boolean hasPermissionsAll(String permissions) { return hasPermissionsAll(permissions, PERMISSION_NAMES_DELIMITER); } @@ -616,7 +585,7 @@ default boolean hasPermissionsAll(String permissions){ * * @return 用户是否具有以下所有权限 */ - default boolean hasPermissionsAll(Collection permissions){ + default boolean hasPermissionsAll(Collection permissions) { return permissions != null && hasPermissionsAll(permissions.toArray(new String[]{})); } @@ -628,7 +597,7 @@ default boolean hasPermissionsAll(Collection permissions){ * * @return 用户是否具有以下所有权限 */ - default boolean hasPermissionsAll(String... permissions){ + default boolean hasPermissionsAll(String... permissions) { if(Validate.isEmpty(permissions)){ return false; } @@ -645,7 +614,7 @@ default boolean hasPermissionsAll(String... permissions){ * * @return 用户是否具有以下所有权限 */ - default boolean hasPermissionsAll(Permission... permissions){ + default boolean hasPermissionsAll(Permission... permissions) { if(Validate.isEmpty(permissions)){ return false; } diff --git a/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/BaseMultiplePermissionTag.java b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/BaseMultiplePermissionTag.java new file mode 100644 index 0000000..8864cd7 --- /dev/null +++ b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/BaseMultiplePermissionTag.java @@ -0,0 +1,51 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package org.apache.shiro.web.tags; + +import com.buession.core.utils.StringUtils; +import org.apache.shiro.subject.Subject; + +/** + * @author Yong.Teng + * @since 2.3.2 + */ +public abstract class BaseMultiplePermissionTag extends PermissionTag { + + protected final static String PERMISSION_NAMES_SEPARATOR = ","; + + @Override + protected boolean showTagBody(String permissionNames) { + Subject subject = getSubject(); + return subject != null && + isPermitted(subject, StringUtils.split(permissionNames, getPermissionNamesSeparator())); + } + + protected String getPermissionNamesSeparator() { + return PERMISSION_NAMES_SEPARATOR; + } + + protected abstract boolean isPermitted(Subject subject, String[] permissionNames); + +} diff --git a/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAllPermissionsTag.java b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAllPermissionsTag.java new file mode 100644 index 0000000..49c875d --- /dev/null +++ b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAllPermissionsTag.java @@ -0,0 +1,44 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. + * See the NOTICE file distributed with this work for additional information regarding copyright ownership. + * The ASF licenses this file to you 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. + * + * ========================================================================================================= + * + * This software consists of voluntary contributions made by many individuals on behalf of the + * Apache Software Foundation. For more information on the Apache Software Foundation, please see + * . + * + * +-------------------------------------------------------------------------------------------------------+ + * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | + * | Author: Yong.Teng | + * | Copyright @ 2013-2023 Buession.com Inc. | + * +-------------------------------------------------------------------------------------------------------+ + */ +package org.apache.shiro.web.tags; + +import org.apache.shiro.subject.Subject; + +import java.util.Arrays; + +/** + * 判断是否具备所有权限,多个权限名称以","分割 + * + * @author Yong.Teng + * @since 2.3.2 + */ +public class HasAllPermissionsTag extends BaseMultiplePermissionTag { + + @Override + protected boolean isPermitted(Subject subject, String[] permissionNames) { + return Arrays.stream(permissionNames).allMatch((permission)->subject.isPermitted(permission.trim())); + } + +} diff --git a/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAnyPermissionsTag.java b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAnyPermissionsTag.java index 1fc22c8..0101bba 100644 --- a/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAnyPermissionsTag.java +++ b/buession-security-shiro/src/main/java/org/apache/shiro/web/tags/HasAnyPermissionsTag.java @@ -24,32 +24,21 @@ */ package org.apache.shiro.web.tags; -import com.buession.core.utils.StringUtils; import org.apache.shiro.subject.Subject; +import java.util.Arrays; + /** * 判断是否具备任意权限,多个权限名称以","分割 * * @author Yong.Teng * @since 2.3.1 */ -public class HasAnyPermissionsTag extends PermissionTag { - - private final static char PERMISSION_NAMES_SEPARATOR = ','; +public class HasAnyPermissionsTag extends BaseMultiplePermissionTag { @Override - protected boolean showTagBody(String permissionNames) { - Subject subject = getSubject(); - - if(subject != null){ - for(String permission : StringUtils.split(permissionNames, PERMISSION_NAMES_SEPARATOR)){ - if(subject.isPermitted(permission.trim())){ - return true; - } - } - } - - return false; + protected boolean isPermitted(Subject subject, String[] permissionNames) { + return Arrays.stream(permissionNames).anyMatch((permission)->subject.isPermitted(permission.trim())); } } diff --git a/buession-security-spring/pom.xml b/buession-security-spring/pom.xml index cfd99f4..a5e82d4 100644 --- a/buession-security-spring/pom.xml +++ b/buession-security-spring/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-spring https://security.buession.com/ diff --git a/buession-security-web/pom.xml b/buession-security-web/pom.xml index 66f6a2d..a6bc0f8 100644 --- a/buession-security-web/pom.xml +++ b/buession-security-web/pom.xml @@ -7,7 +7,7 @@ com.buession.security buession-security-parent ../buession-security-parent - 2.3.1 + 2.3.2 buession-security-web https://security.buession.com/ @@ -125,7 +125,7 @@ org.owasp.antisamy antisamy - 1.7.3 + 1.7.4 org.slf4j diff --git a/buession-security-web/src/main/java/com/buession/security/web/builder/reactive/ReactiveHttpSecurityBuilder.java b/buession-security-web/src/main/java/com/buession/security/web/builder/reactive/ReactiveHttpSecurityBuilder.java index 7fe671e..c4e7304 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/builder/reactive/ReactiveHttpSecurityBuilder.java +++ b/buession-security-web/src/main/java/com/buession/security/web/builder/reactive/ReactiveHttpSecurityBuilder.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.builder.reactive; @@ -66,7 +66,7 @@ public class ReactiveHttpSecurityBuilder implements HttpSecurityBuilder { * @param serverHttpSecurity * ServerHttpSecurity 实例 */ - protected ReactiveHttpSecurityBuilder(final ServerHttpSecurity serverHttpSecurity){ + protected ReactiveHttpSecurityBuilder(final ServerHttpSecurity serverHttpSecurity) { this.serverHttpSecurity = serverHttpSecurity; } @@ -78,12 +78,12 @@ protected ReactiveHttpSecurityBuilder(final ServerHttpSecurity serverHttpSecurit * * @return ReactiveHttpSecurityBuilder 实例 */ - public static ReactiveHttpSecurityBuilder getInstance(final ServerHttpSecurity serverHttpSecurity){ + public static ReactiveHttpSecurityBuilder getInstance(final ServerHttpSecurity serverHttpSecurity) { return new ReactiveHttpSecurityBuilder(serverHttpSecurity); } @Override - public ReactiveHttpSecurityBuilder httpBasic(HttpBasic config){ + public ReactiveHttpSecurityBuilder httpBasic(HttpBasic config) { if(config.isEnabled() == false){ serverHttpSecurity.httpBasic().disable(); } @@ -92,7 +92,8 @@ public ReactiveHttpSecurityBuilder httpBasic(HttpBasic config){ } @Override - public ReactiveHttpSecurityBuilder csrf(Csrf config){ + public ReactiveHttpSecurityBuilder csrf(Csrf config) { + PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenHasText(); ServerHttpSecurity.CsrfSpec csrfSpec = serverHttpSecurity.csrf(); if(config.isEnabled()){ @@ -103,25 +104,11 @@ public ReactiveHttpSecurityBuilder csrf(Csrf config){ CookieServerCsrfTokenRepository cookieCsrfTokenRepository = new CookieServerCsrfTokenRepository(); - if(Validate.hasText(cookie.getParameterName())){ - cookieCsrfTokenRepository.setParameterName(cookie.getParameterName()); - } - - if(Validate.hasText(cookie.getHeaderName())){ - cookieCsrfTokenRepository.setHeaderName(cookie.getHeaderName()); - } - - if(Validate.hasText(cookie.getCookieName())){ - cookieCsrfTokenRepository.setCookieName(cookie.getCookieName()); - } - - if(Validate.hasText(cookie.getCookieDomain())){ - cookieCsrfTokenRepository.setCookieDomain(cookie.getCookieDomain()); - } - - if(Validate.hasText(cookie.getCookiePath())){ - cookieCsrfTokenRepository.setCookiePath(cookie.getCookiePath()); - } + propertyMapper.from(cookie.getParameterName()).to(cookieCsrfTokenRepository::setParameterName); + propertyMapper.from(cookie.getHeaderName()).to(cookieCsrfTokenRepository::setHeaderName); + propertyMapper.from(cookie.getCookieName()).to(cookieCsrfTokenRepository::setCookieName); + propertyMapper.from(cookie.getCookieDomain()).to(cookieCsrfTokenRepository::setCookieDomain); + propertyMapper.from(cookie.getCookiePath()).to(cookieCsrfTokenRepository::setCookiePath); cookieCsrfTokenRepository.setCookieHttpOnly(cookie.getCookieHttpOnly()); @@ -132,17 +119,11 @@ public ReactiveHttpSecurityBuilder csrf(Csrf config){ WebSessionServerCsrfTokenRepository sessionCsrfTokenRepository = new WebSessionServerCsrfTokenRepository(); - if(Validate.hasText(session.getParameterName())){ - sessionCsrfTokenRepository.setParameterName(session.getParameterName()); - } - - if(Validate.hasText(session.getHeaderName())){ - sessionCsrfTokenRepository.setHeaderName(session.getHeaderName()); - } - - if(Validate.hasText(session.getSessionAttributeName())){ - sessionCsrfTokenRepository.setSessionAttributeName(session.getSessionAttributeName()); - } + propertyMapper.from(session.getParameterName()) + .to(sessionCsrfTokenRepository::setParameterName); + propertyMapper.from(session.getHeaderName()).to(sessionCsrfTokenRepository::setHeaderName); + propertyMapper.from(session.getSessionAttributeName()) + .to(sessionCsrfTokenRepository::setSessionAttributeName); csrfSpec.csrfTokenRepository(sessionCsrfTokenRepository); break; @@ -158,7 +139,7 @@ public ReactiveHttpSecurityBuilder csrf(Csrf config){ } @Override - public ReactiveHttpSecurityBuilder cors(Cors config){ + public ReactiveHttpSecurityBuilder cors(Cors config) { ServerHttpSecurity.CorsSpec corsSpec = serverHttpSecurity.cors(); if(config.isEnabled()){ @@ -174,7 +155,7 @@ public ReactiveHttpSecurityBuilder cors(Cors config){ } @Override - public ReactiveHttpSecurityBuilder frameOptions(FrameOptions config){ + public ReactiveHttpSecurityBuilder frameOptions(FrameOptions config) { ServerHttpSecurity.HeaderSpec.FrameOptionsSpec frameOptionsSpec = serverHttpSecurity.headers().frameOptions(); if(config.isEnabled()){ @@ -201,7 +182,7 @@ public ReactiveHttpSecurityBuilder frameOptions(FrameOptions config){ } @Override - public ReactiveHttpSecurityBuilder hsts(Hsts config){ + public ReactiveHttpSecurityBuilder hsts(Hsts config) { ServerHttpSecurity.HeaderSpec.HstsSpec hstsSpec = serverHttpSecurity.headers().hsts(); if(config.isEnabled()){ @@ -222,12 +203,12 @@ public ReactiveHttpSecurityBuilder hsts(Hsts config){ } @Override - public ReactiveHttpSecurityBuilder hpkp(Hpkp config){ + public ReactiveHttpSecurityBuilder hpkp(Hpkp config) { return this; } @Override - public ReactiveHttpSecurityBuilder contentSecurityPolicy(ContentSecurityPolicy config){ + public ReactiveHttpSecurityBuilder contentSecurityPolicy(ContentSecurityPolicy config) { if(config.isEnabled() && Validate.hasText(config.getPolicyDirectives())){ ServerHttpSecurity.HeaderSpec.ContentSecurityPolicySpec contentSecurityPolicySpec = serverHttpSecurity.headers() .contentSecurityPolicy(config.getPolicyDirectives()); @@ -241,7 +222,7 @@ public ReactiveHttpSecurityBuilder contentSecurityPolicy(ContentSecurityPolicy c } @Override - public ReactiveHttpSecurityBuilder referrerPolicy(ReferrerPolicy config){ + public ReactiveHttpSecurityBuilder referrerPolicy(ReferrerPolicy config) { if(config.isEnabled() && config.getPolicy() != null){ ReferrerPolicyConverter.ToNativeReferrerPolicyConverter toNativeReferrerPolicyConverter = new ReferrerPolicyConverter.ToNativeReferrerPolicyConverter(); ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy referrerPolicy = toNativeReferrerPolicyConverter.convert( @@ -256,12 +237,12 @@ public ReactiveHttpSecurityBuilder referrerPolicy(ReferrerPolicy config){ } @Override - public ReactiveHttpSecurityBuilder xss(Xss config){ + public ReactiveHttpSecurityBuilder xss(Xss config) { ServerHttpSecurity.HeaderSpec.XssProtectionSpec xssProtectionSpec = serverHttpSecurity.headers() .xssProtection(); if(config.isEnabled()){ - + }else{ xssProtectionSpec.disable(); } @@ -270,7 +251,7 @@ public ReactiveHttpSecurityBuilder xss(Xss config){ } @Override - public ReactiveHttpSecurityBuilder formLogin(FormLogin config){ + public ReactiveHttpSecurityBuilder formLogin(FormLogin config) { ServerHttpSecurity.FormLoginSpec formLoginSpec = serverHttpSecurity.formLogin(); if(config.isEnabled()){ diff --git a/buession-security-web/src/main/java/com/buession/security/web/builder/servlet/ServletHttpSecurityBuilder.java b/buession-security-web/src/main/java/com/buession/security/web/builder/servlet/ServletHttpSecurityBuilder.java index a71da9a..1eb9eca 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/builder/servlet/ServletHttpSecurityBuilder.java +++ b/buession-security-web/src/main/java/com/buession/security/web/builder/servlet/ServletHttpSecurityBuilder.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.builder.servlet; @@ -51,7 +51,6 @@ import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import java.time.Duration; import java.util.Objects; /** @@ -75,7 +74,7 @@ public class ServletHttpSecurityBuilder implements HttpSecurityBuilder { * @param httpSecurity * HttpSecurity 实例 */ - protected ServletHttpSecurityBuilder(final HttpSecurity httpSecurity){ + protected ServletHttpSecurityBuilder(final HttpSecurity httpSecurity) { this.httpSecurity = httpSecurity; } @@ -87,12 +86,12 @@ protected ServletHttpSecurityBuilder(final HttpSecurity httpSecurity){ * * @return ServletHttpSecurityBuilder 实例 */ - public static ServletHttpSecurityBuilder getInstance(final HttpSecurity httpSecurity){ + public static ServletHttpSecurityBuilder getInstance(final HttpSecurity httpSecurity) { return new ServletHttpSecurityBuilder(httpSecurity); } @Override - public ServletHttpSecurityBuilder httpBasic(final HttpBasic config){ + public ServletHttpSecurityBuilder httpBasic(final HttpBasic config) { if(config.isEnabled() == false){ try{ httpSecurity.httpBasic().disable(); @@ -107,9 +106,10 @@ public ServletHttpSecurityBuilder httpBasic(final HttpBasic config){ } @Override - public ServletHttpSecurityBuilder csrf(final Csrf config){ + public ServletHttpSecurityBuilder csrf(final Csrf config) { try{ CsrfConfigurer csrfConfigurer = httpSecurity.csrf(); + PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenHasText(); if(config.isEnabled()){ if(config.getMode() != null){ @@ -119,25 +119,13 @@ public ServletHttpSecurityBuilder csrf(final Csrf config){ CookieCsrfTokenRepository cookieCsrfTokenRepository = new CookieCsrfTokenRepository(); - if(Validate.hasText(cookie.getParameterName())){ - cookieCsrfTokenRepository.setParameterName(cookie.getParameterName()); - } - - if(Validate.hasText(cookie.getHeaderName())){ - cookieCsrfTokenRepository.setHeaderName(cookie.getHeaderName()); - } - - if(Validate.hasText(cookie.getCookieName())){ - cookieCsrfTokenRepository.setCookieName(cookie.getCookieName()); - } - - if(Validate.hasText(cookie.getCookieDomain())){ - cookieCsrfTokenRepository.setCookieDomain(cookie.getCookieDomain()); - } - - if(Validate.hasText(cookie.getCookiePath())){ - cookieCsrfTokenRepository.setCookiePath(cookie.getCookiePath()); - } + propertyMapper.from(cookie.getParameterName()) + .to(cookieCsrfTokenRepository::setParameterName); + propertyMapper.from(cookie.getHeaderName()).to(cookieCsrfTokenRepository::setHeaderName); + propertyMapper.from(cookie.getCookieName()).to(cookieCsrfTokenRepository::setCookieName); + propertyMapper.from(cookie.getCookieDomain()) + .to(cookieCsrfTokenRepository::setCookieDomain); + propertyMapper.from(cookie.getCookiePath()).to(cookieCsrfTokenRepository::setCookiePath); cookieCsrfTokenRepository.setCookieHttpOnly(cookie.getCookieHttpOnly()); @@ -148,17 +136,11 @@ public ServletHttpSecurityBuilder csrf(final Csrf config){ HttpSessionCsrfTokenRepository sessionCsrfTokenRepository = new HttpSessionCsrfTokenRepository(); - if(Validate.hasText(session.getParameterName())){ - sessionCsrfTokenRepository.setParameterName(session.getParameterName()); - } - - if(Validate.hasText(session.getHeaderName())){ - sessionCsrfTokenRepository.setHeaderName(session.getHeaderName()); - } - - if(Validate.hasText(session.getSessionAttributeName())){ - sessionCsrfTokenRepository.setSessionAttributeName(session.getSessionAttributeName()); - } + propertyMapper.from(session.getParameterName()) + .to(sessionCsrfTokenRepository::setParameterName); + propertyMapper.from(session.getHeaderName()).to(sessionCsrfTokenRepository::setHeaderName); + propertyMapper.from(session.getSessionAttributeName()) + .to(sessionCsrfTokenRepository::setSessionAttributeName); csrfConfigurer.csrfTokenRepository(new LazyCsrfTokenRepository(sessionCsrfTokenRepository)); break; @@ -179,7 +161,7 @@ public ServletHttpSecurityBuilder csrf(final Csrf config){ } @Override - public ServletHttpSecurityBuilder cors(final Cors config){ + public ServletHttpSecurityBuilder cors(final Cors config) { try{ CorsConfigurer corsConfigurer = httpSecurity.cors(); @@ -201,7 +183,7 @@ public ServletHttpSecurityBuilder cors(final Cors config){ } @Override - public ServletHttpSecurityBuilder frameOptions(final FrameOptions config){ + public ServletHttpSecurityBuilder frameOptions(final FrameOptions config) { try{ HeadersConfigurer.FrameOptionsConfig frameOptionsConfig = httpSecurity.headers() .frameOptions(); @@ -235,7 +217,7 @@ public ServletHttpSecurityBuilder frameOptions(final FrameOptions config){ } @Override - public ServletHttpSecurityBuilder hsts(final Hsts config){ + public ServletHttpSecurityBuilder hsts(final Hsts config) { try{ HeadersConfigurer.HstsConfig hstsConfig = httpSecurity.headers() .httpStrictTransportSecurity(); @@ -263,7 +245,7 @@ public ServletHttpSecurityBuilder hsts(final Hsts config){ } @Override - public ServletHttpSecurityBuilder hpkp(final Hpkp config){ + public ServletHttpSecurityBuilder hpkp(final Hpkp config) { try{ HeadersConfigurer.HpkpConfig hpkpConfig = httpSecurity.headers().httpPublicKeyPinning(); @@ -289,7 +271,7 @@ public ServletHttpSecurityBuilder hpkp(final Hpkp config){ } @Override - public ServletHttpSecurityBuilder contentSecurityPolicy(final ContentSecurityPolicy config){ + public ServletHttpSecurityBuilder contentSecurityPolicy(final ContentSecurityPolicy config) { try{ if(config.isEnabled() && Validate.hasText(config.getPolicyDirectives())){ HeadersConfigurer.ContentSecurityPolicyConfig contentSecurityPolicyConfig = httpSecurity.headers() @@ -309,7 +291,7 @@ public ServletHttpSecurityBuilder contentSecurityPolicy(final ContentSecurityPol } @Override - public ServletHttpSecurityBuilder referrerPolicy(final ReferrerPolicy config){ + public ServletHttpSecurityBuilder referrerPolicy(final ReferrerPolicy config) { if(config.isEnabled() && config.getPolicy() != null){ try{ ReferrerPolicyConverter.ToNativeReferrerPolicyConverter toNativeReferrerPolicyConverter = new ReferrerPolicyConverter.ToNativeReferrerPolicyConverter(); @@ -330,7 +312,7 @@ public ServletHttpSecurityBuilder referrerPolicy(final ReferrerPolicy config){ } @Override - public ServletHttpSecurityBuilder xss(final Xss config){ + public ServletHttpSecurityBuilder xss(final Xss config) { try{ HeadersConfigurer.XXssConfig xssConfig = httpSecurity.headers().xssProtection(); @@ -352,7 +334,7 @@ public ServletHttpSecurityBuilder xss(final Xss config){ } @Override - public ServletHttpSecurityBuilder formLogin(FormLogin config){ + public ServletHttpSecurityBuilder formLogin(FormLogin config) { try{ FormLoginConfigurer formLoginConfigurer = httpSecurity.formLogin(); diff --git a/buession-security-web/src/main/java/com/buession/security/web/config/Configurer.java b/buession-security-web/src/main/java/com/buession/security/web/config/Configurer.java index 790cc07..63cef8a 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/config/Configurer.java +++ b/buession-security-web/src/main/java/com/buession/security/web/config/Configurer.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.config; @@ -87,7 +87,7 @@ public class Configurer { /** * 构造函数 */ - public Configurer(){ + public Configurer() { } /** @@ -116,7 +116,7 @@ public Configurer(){ */ public Configurer(HttpBasic httpBasic, Csrf csrf, Cors cors, FrameOptions frameOptions, Hsts hsts, Hpkp hpkp, ContentSecurityPolicy contentSecurityPolicy, - ReferrerPolicy referrerPolicy, Xss xss, FormLogin formLogin){ + ReferrerPolicy referrerPolicy, Xss xss, FormLogin formLogin) { this.httpBasic = httpBasic; this.csrf = csrf; this.cors = cors; @@ -134,7 +134,7 @@ public Configurer(HttpBasic httpBasic, Csrf csrf, Cors cors, FrameOptions frameO * * @return Http Basic 配置 */ - public HttpBasic getHttpBasic(){ + public HttpBasic getHttpBasic() { return httpBasic; } @@ -144,7 +144,7 @@ public HttpBasic getHttpBasic(){ * @param httpBasic * Http Basic 配置 */ - public void setHttpBasic(HttpBasic httpBasic){ + public void setHttpBasic(HttpBasic httpBasic) { this.httpBasic = httpBasic; } @@ -153,7 +153,7 @@ public void setHttpBasic(HttpBasic httpBasic){ * * @return Csrf 配置 */ - public Csrf getCsrf(){ + public Csrf getCsrf() { return csrf; } @@ -163,7 +163,7 @@ public Csrf getCsrf(){ * @param csrf * Csrf 配置 */ - public void setCsrf(Csrf csrf){ + public void setCsrf(Csrf csrf) { this.csrf = csrf; } @@ -172,7 +172,7 @@ public void setCsrf(Csrf csrf){ * * @return Cors 配置 */ - public Cors getCors(){ + public Cors getCors() { return cors; } @@ -182,7 +182,7 @@ public Cors getCors(){ * @param cors * Cors 配置 */ - public void setCors(Cors cors){ + public void setCors(Cors cors) { this.cors = cors; } @@ -191,7 +191,7 @@ public void setCors(Cors cors){ * * @return Frame Options 配置 */ - public FrameOptions getFrameOptions(){ + public FrameOptions getFrameOptions() { return frameOptions; } @@ -201,7 +201,7 @@ public FrameOptions getFrameOptions(){ * @param frameOptions * Frame Options 配置 */ - public void setFrameOptions(FrameOptions frameOptions){ + public void setFrameOptions(FrameOptions frameOptions) { this.frameOptions = frameOptions; } @@ -210,7 +210,7 @@ public void setFrameOptions(FrameOptions frameOptions){ * * @return Hsts 配置 */ - public Hsts getHsts(){ + public Hsts getHsts() { return hsts; } @@ -220,7 +220,7 @@ public Hsts getHsts(){ * @param hsts * Hsts 配置 */ - public void setHsts(Hsts hsts){ + public void setHsts(Hsts hsts) { this.hsts = hsts; } @@ -229,7 +229,7 @@ public void setHsts(Hsts hsts){ * * @return Hpkp 配置 */ - public Hpkp getHpkp(){ + public Hpkp getHpkp() { return hpkp; } @@ -239,7 +239,7 @@ public Hpkp getHpkp(){ * @param hpkp * Hpkp 配置 */ - public void setHpkp(Hpkp hpkp){ + public void setHpkp(Hpkp hpkp) { this.hpkp = hpkp; } @@ -248,7 +248,7 @@ public void setHpkp(Hpkp hpkp){ * * @return Content Security Policy 配置 */ - public ContentSecurityPolicy getContentSecurityPolicy(){ + public ContentSecurityPolicy getContentSecurityPolicy() { return contentSecurityPolicy; } @@ -258,7 +258,7 @@ public ContentSecurityPolicy getContentSecurityPolicy(){ * @param contentSecurityPolicy * Content Security Policy 配置 */ - public void setContentSecurityPolicy(ContentSecurityPolicy contentSecurityPolicy){ + public void setContentSecurityPolicy(ContentSecurityPolicy contentSecurityPolicy) { this.contentSecurityPolicy = contentSecurityPolicy; } @@ -267,7 +267,7 @@ public void setContentSecurityPolicy(ContentSecurityPolicy contentSecurityPolicy * * @return Referrer Policy 配置 */ - public ReferrerPolicy getReferrerPolicy(){ + public ReferrerPolicy getReferrerPolicy() { return referrerPolicy; } @@ -277,7 +277,7 @@ public ReferrerPolicy getReferrerPolicy(){ * @param referrerPolicy * Referrer Policy 配置 */ - public void setReferrerPolicy(ReferrerPolicy referrerPolicy){ + public void setReferrerPolicy(ReferrerPolicy referrerPolicy) { this.referrerPolicy = referrerPolicy; } @@ -286,7 +286,7 @@ public void setReferrerPolicy(ReferrerPolicy referrerPolicy){ * * @return XSS 配置 */ - public Xss getXss(){ + public Xss getXss() { return xss; } @@ -296,7 +296,7 @@ public Xss getXss(){ * @param xss * XSS 配置 */ - public void setXss(Xss xss){ + public void setXss(Xss xss) { this.xss = xss; } @@ -305,7 +305,7 @@ public void setXss(Xss xss){ * * @return 登录表单配置 */ - public FormLogin getFormLogin(){ + public FormLogin getFormLogin() { return formLogin; } @@ -315,13 +315,13 @@ public FormLogin getFormLogin(){ * @param formLogin * 登录表单配置 */ - public void setFormLogin(FormLogin formLogin){ + public void setFormLogin(FormLogin formLogin) { this.formLogin = formLogin; } @Override - public String toString(){ - return new StringJoiner(", ", "{", "}") + public String toString() { + return new StringJoiner(", ", "Configurer = {", "}") .add("httpBasic=" + httpBasic) .add("csrf=" + csrf) .add("frameOptions=" + frameOptions) diff --git a/buession-security-web/src/main/java/com/buession/security/web/config/Cors.java b/buession-security-web/src/main/java/com/buession/security/web/config/Cors.java index 985749a..ac2d51a 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/config/Cors.java +++ b/buession-security-web/src/main/java/com/buession/security/web/config/Cors.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.config; @@ -30,6 +30,7 @@ import java.util.ArrayList; import java.util.Set; +import java.util.StringJoiner; import java.util.stream.Collectors; /** @@ -81,7 +82,7 @@ public class Cors { * * @return 是否启用 Cors */ - public boolean isEnabled(){ + public boolean isEnabled() { return getEnabled(); } @@ -90,7 +91,7 @@ public boolean isEnabled(){ * * @return 是否启用 Cors */ - public boolean getEnabled(){ + public boolean getEnabled() { return enabled; } @@ -100,7 +101,7 @@ public boolean getEnabled(){ * @param enabled * 是否启用 Cors */ - public void setEnabled(boolean enabled){ + public void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -109,7 +110,7 @@ public void setEnabled(boolean enabled){ * * @return 允许请求的域 */ - public Set getOrigins(){ + public Set getOrigins() { return origins; } @@ -119,7 +120,7 @@ public Set getOrigins(){ * @param origins * 允许请求的域 */ - public void setOrigins(Set origins){ + public void setOrigins(Set origins) { this.origins = origins; } @@ -128,7 +129,7 @@ public void setOrigins(Set origins){ * * @return 允许请求的方法 */ - public Set getAllowedMethods(){ + public Set getAllowedMethods() { return allowedMethods; } @@ -138,7 +139,7 @@ public Set getAllowedMethods(){ * @param allowedMethods * 允许请求的方法 */ - public void setAllowedMethods(Set allowedMethods){ + public void setAllowedMethods(Set allowedMethods) { this.allowedMethods = allowedMethods; } @@ -147,7 +148,7 @@ public void setAllowedMethods(Set allowedMethods){ * * @return 实际请求中允许携带的首部字段 */ - public Set getAllowedHeaders(){ + public Set getAllowedHeaders() { return allowedHeaders; } @@ -157,7 +158,7 @@ public Set getAllowedHeaders(){ * @param allowedHeaders * 实际请求中允许携带的首部字段 */ - public void setAllowedHeaders(Set allowedHeaders){ + public void setAllowedHeaders(Set allowedHeaders) { this.allowedHeaders = allowedHeaders; } @@ -166,7 +167,7 @@ public void setAllowedHeaders(Set allowedHeaders){ * * @return 允许浏览器访问的头 */ - public Set getExposedHeaders(){ + public Set getExposedHeaders() { return exposedHeaders; } @@ -176,7 +177,7 @@ public Set getExposedHeaders(){ * @param exposedHeaders * 允许浏览器访问的头 */ - public void setExposedHeaders(Set exposedHeaders){ + public void setExposedHeaders(Set exposedHeaders) { this.exposedHeaders = exposedHeaders; } @@ -185,7 +186,7 @@ public void setExposedHeaders(Set exposedHeaders){ * * @return 当浏览器的 credentials 设置为 true 时是否允许浏览器读取 response 的内容 */ - public Boolean getAllowCredentials(){ + public Boolean getAllowCredentials() { return allowCredentials; } @@ -195,7 +196,7 @@ public Boolean getAllowCredentials(){ * @param allowCredentials * 是否允许浏览器读取 response 的内容 */ - public void setAllowCredentials(Boolean allowCredentials){ + public void setAllowCredentials(Boolean allowCredentials) { this.allowCredentials = allowCredentials; } @@ -204,7 +205,7 @@ public void setAllowCredentials(Boolean allowCredentials){ * * @return preflight 请求的结果能够被缓存时间 */ - public Long getMaxAge(){ + public Long getMaxAge() { return maxAge; } @@ -214,7 +215,7 @@ public Long getMaxAge(){ * @param maxAge * preflight 请求的结果能够被缓存时间(单位:秒) */ - public void setMaxAge(Long maxAge){ + public void setMaxAge(Long maxAge) { this.maxAge = maxAge; } @@ -223,7 +224,7 @@ public void setMaxAge(Long maxAge){ * * @return {@link CorsConfiguration} 实例 */ - public CorsConfiguration toCorsConfiguration(){ + public CorsConfiguration toCorsConfiguration() { final CorsConfiguration configuration = new CorsConfiguration(); if(Validate.isNotEmpty(getOrigins())){ @@ -255,4 +256,17 @@ public CorsConfiguration toCorsConfiguration(){ return configuration; } + @Override + public String toString() { + return new StringJoiner(", ", "Cors = {", "}") + .add("enabled=" + enabled) + .add("origins=" + origins) + .add("allowedMethods=" + allowedMethods) + .add("allowedHeaders=" + allowedHeaders) + .add("exposedHeaders=" + exposedHeaders) + .add("allowCredentials=" + allowCredentials) + .add("maxAge=" + maxAge) + .toString(); + } + } diff --git a/buession-security-web/src/main/java/com/buession/security/web/config/FormLogin.java b/buession-security-web/src/main/java/com/buession/security/web/config/FormLogin.java index a699906..7d893c1 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/config/FormLogin.java +++ b/buession-security-web/src/main/java/com/buession/security/web/config/FormLogin.java @@ -19,11 +19,13 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.config; +import java.util.StringJoiner; + /** * 登录表单 * @@ -47,7 +49,7 @@ public class FormLogin { * * @return 是否启动登录表单 */ - public boolean isEnabled(){ + public boolean isEnabled() { return enabled; } @@ -57,7 +59,7 @@ public boolean isEnabled(){ * @param enabled * 是否启动登录表单 */ - public void setEnabled(boolean enabled){ + public void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -66,7 +68,7 @@ public void setEnabled(boolean enabled){ * * @return 登录页地址 */ - public String getLoginPage(){ + public String getLoginPage() { return loginPage; } @@ -76,8 +78,16 @@ public String getLoginPage(){ * @param loginPage * 登录页地址 */ - public void setLoginPage(String loginPage){ + public void setLoginPage(String loginPage) { this.loginPage = loginPage; } - + + @Override + public String toString() { + return new StringJoiner(", ", "FormLogin = {", "}") + .add("enabled=" + enabled) + .add("loginPage='" + loginPage + "'") + .toString(); + } + } diff --git a/buession-security-web/src/main/java/com/buession/security/web/config/FrameOptions.java b/buession-security-web/src/main/java/com/buession/security/web/config/FrameOptions.java index 70cf8c9..1a91eda 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/config/FrameOptions.java +++ b/buession-security-web/src/main/java/com/buession/security/web/config/FrameOptions.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.config; @@ -51,7 +51,7 @@ public class FrameOptions { * * @return 是否启用 Frame Options */ - public boolean isEnabled(){ + public boolean isEnabled() { return getEnabled(); } @@ -60,7 +60,7 @@ public boolean isEnabled(){ * * @return 是否启用 Frame Options */ - public boolean getEnabled(){ + public boolean getEnabled() { return enabled; } @@ -70,7 +70,7 @@ public boolean getEnabled(){ * @param enabled * 是否启用 Frame Options */ - public void setEnabled(boolean enabled){ + public void setEnabled(boolean enabled) { this.enabled = enabled; } @@ -79,7 +79,7 @@ public void setEnabled(boolean enabled){ * * @return Frame Options 模式 */ - public XFrameOptionsMode getMode(){ + public XFrameOptionsMode getMode() { return mode; } @@ -89,12 +89,12 @@ public XFrameOptionsMode getMode(){ * @param mode * Frame Options 模式 */ - public void setMode(XFrameOptionsMode mode){ + public void setMode(XFrameOptionsMode mode) { this.mode = mode; } @Override - public String toString(){ + public String toString() { return new StringJoiner(", ", "FrameOptions = {", "}") .add("enabled=" + enabled) .add("mode=" + mode) @@ -111,18 +111,19 @@ public enum XFrameOptionsMode { private final String mode; - XFrameOptionsMode(final String mode){ + XFrameOptionsMode(final String mode) { this.mode = mode; } - private String getMode(){ + private String getMode() { return mode; } @Override - public String toString(){ + public String toString() { return getMode(); } + } } diff --git a/buession-security-web/src/main/java/com/buession/security/web/reactive/config/ReactiveWebSecurityConfigurerAdapterConfiguration.java b/buession-security-web/src/main/java/com/buession/security/web/reactive/config/ReactiveWebSecurityConfigurerAdapterConfiguration.java index 737490d..6fd59a4 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/reactive/config/ReactiveWebSecurityConfigurerAdapterConfiguration.java +++ b/buession-security-web/src/main/java/com/buession/security/web/reactive/config/ReactiveWebSecurityConfigurerAdapterConfiguration.java @@ -19,7 +19,7 @@ * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng | - * | Copyright @ 2013-2022 Buession.com Inc. | + * | Copyright @ 2013-2023 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.security.web.reactive.config; @@ -50,7 +50,7 @@ public class ReactiveWebSecurityConfigurerAdapterConfiguration { /** * 构造函数 */ - public ReactiveWebSecurityConfigurerAdapterConfiguration(){ + public ReactiveWebSecurityConfigurerAdapterConfiguration() { this.configurer = new Configurer(); } @@ -60,7 +60,7 @@ public ReactiveWebSecurityConfigurerAdapterConfiguration(){ * @param httpSecurity * {@link ServerHttpSecurity} 实例 */ - public ReactiveWebSecurityConfigurerAdapterConfiguration(final ServerHttpSecurity httpSecurity){ + public ReactiveWebSecurityConfigurerAdapterConfiguration(final ServerHttpSecurity httpSecurity) { this(new Configurer(), httpSecurity); } @@ -73,18 +73,18 @@ public ReactiveWebSecurityConfigurerAdapterConfiguration(final ServerHttpSecurit * {@link ServerHttpSecurity} 实例 */ public ReactiveWebSecurityConfigurerAdapterConfiguration(final Configurer configurer, - final ServerHttpSecurity httpSecurity){ + final ServerHttpSecurity httpSecurity) { this.configurer = configurer; initialize(httpSecurity); } - protected void initialize(ServerHttpSecurity httpSecurity){ + protected void initialize(ServerHttpSecurity httpSecurity) { if(httpSecurity == null){ return; } - PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); - ReactiveHttpSecurityBuilder builder = ReactiveHttpSecurityBuilder.getInstance(httpSecurity); + final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); + final ReactiveHttpSecurityBuilder builder = ReactiveHttpSecurityBuilder.getInstance(httpSecurity); propertyMapper.from(configurer::getHttpBasic).to(builder::httpBasic); propertyMapper.from(configurer::getCsrf).to(builder::csrf); diff --git a/buession-security-web/src/main/java/com/buession/security/web/servlet/config/ServletWebSecurityConfigurerAdapterConfiguration.java b/buession-security-web/src/main/java/com/buession/security/web/servlet/config/ServletWebSecurityConfigurerAdapterConfiguration.java index a961abe..62d6b11 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/servlet/config/ServletWebSecurityConfigurerAdapterConfiguration.java +++ b/buession-security-web/src/main/java/com/buession/security/web/servlet/config/ServletWebSecurityConfigurerAdapterConfiguration.java @@ -51,7 +51,7 @@ public class ServletWebSecurityConfigurerAdapterConfiguration extends WebSecurit /** * 构造函数 */ - public ServletWebSecurityConfigurerAdapterConfiguration(){ + public ServletWebSecurityConfigurerAdapterConfiguration() { this(new Configurer()); } @@ -61,7 +61,7 @@ public ServletWebSecurityConfigurerAdapterConfiguration(){ * @param configurer * Web 安全适配配置 */ - public ServletWebSecurityConfigurerAdapterConfiguration(final Configurer configurer){ + public ServletWebSecurityConfigurerAdapterConfiguration(final Configurer configurer) { super(); this.configurer = configurer; } @@ -74,19 +74,20 @@ public ServletWebSecurityConfigurerAdapterConfiguration(final Configurer configu * @param disableDefaults * 是否禁用默认配置 */ - public ServletWebSecurityConfigurerAdapterConfiguration(final Configurer configurer, final boolean disableDefaults){ + public ServletWebSecurityConfigurerAdapterConfiguration(final Configurer configurer, + final boolean disableDefaults) { super(disableDefaults); this.configurer = configurer; } @Override - protected void configure(HttpSecurity httpSecurity) throws Exception{ + protected void configure(HttpSecurity httpSecurity) throws Exception { if(httpSecurity == null){ return; } - PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); - ServletHttpSecurityBuilder builder = ServletHttpSecurityBuilder.getInstance(httpSecurity); + final PropertyMapper propertyMapper = PropertyMapper.get().alwaysApplyingWhenNonNull(); + final ServletHttpSecurityBuilder builder = ServletHttpSecurityBuilder.getInstance(httpSecurity); propertyMapper.from(configurer::getHttpBasic).to(builder::httpBasic); propertyMapper.from(configurer::getCsrf).to(builder::csrf); diff --git a/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Encoder.java b/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Encoder.java index f796019..0653d4a 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Encoder.java +++ b/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Encoder.java @@ -28,6 +28,7 @@ * @author Yong.Teng * @since 2.2.0 */ +@FunctionalInterface public interface Encoder { T runtime(); diff --git a/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Jackson2Encoder.java b/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Jackson2Encoder.java index e8b6e85..c5fb150 100644 --- a/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Jackson2Encoder.java +++ b/buession-security-web/src/main/java/com/buession/security/web/xss/encoder/Jackson2Encoder.java @@ -39,26 +39,26 @@ */ public class Jackson2Encoder extends AbstractEncoder> { - public Jackson2Encoder() throws FileNotFoundException{ + public Jackson2Encoder() throws FileNotFoundException { super(); } - public Jackson2Encoder(final Policy policy) throws FileNotFoundException{ + public Jackson2Encoder(final Policy policy) throws FileNotFoundException { super(policy); } @Override - public JsonDeserializer runtime(){ + public JsonDeserializer runtime() { return new JsonDeserializer() { @Override - public Class handledType(){ + public Class handledType() { return String.class; } @Override public String deserialize(JsonParser parser, DeserializationContext cxt) - throws IOException, JacksonException{ + throws IOException, JacksonException { String value = parser.getValueAsString(); if(value != null){ @@ -67,6 +67,7 @@ public String deserialize(JsonParser parser, DeserializationContext cxt) return value; } + }; }