Skip to content

Commit 62b8cb8

Browse files
author
zihluwang
committed
refactor: moved MapUtil implemented by reflect API to another package
1 parent 7e4fdd5 commit 62b8cb8

File tree

16 files changed

+204
-130
lines changed

16 files changed

+204
-130
lines changed

devkit-utils/src/main/java/com/onixbyte/devkit/utils/AesUtil.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,7 @@
3434
import java.util.UUID;
3535

3636
/**
37-
* {@link AesUtil} can help you encrypt and decrypt data with specified secret
38-
* by AES algorithm.
37+
* {@link AesUtil} can help you encrypt and decrypt data with specified secret by AES algorithm.
3938
*
4039
* @author hubin@baomidou
4140
* @version 1.1.0
@@ -81,8 +80,9 @@ public static byte[] decrypt(byte[] data, byte[] secret) {
8180
var cipher = Cipher.getInstance(AES_CBC_CIPHER);
8281
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(secret));
8382
return cipher.doFinal(data);
84-
} catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedOperationException |
85-
InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException |
83+
} catch (NoSuchAlgorithmException | NoSuchPaddingException |
84+
UnsupportedOperationException | InvalidKeyException |
85+
InvalidAlgorithmParameterException | IllegalBlockSizeException |
8686
BadPaddingException exception) {
8787
log.error(exception.getMessage());
8888
for (var stackTraceElement : exception.getStackTrace()) {
@@ -100,7 +100,8 @@ public static byte[] decrypt(byte[] data, byte[] secret) {
100100
* @return the encryption result or {@code null} if encryption failed
101101
*/
102102
public static String encrypt(String data, String secret) {
103-
return Base64.getEncoder().encodeToString(encrypt(data.getBytes(StandardCharsets.UTF_8), secret.getBytes(StandardCharsets.UTF_8)));
103+
return Base64.getEncoder().encodeToString(encrypt(data.getBytes(StandardCharsets.UTF_8),
104+
secret.getBytes(StandardCharsets.UTF_8)));
104105
}
105106

106107
/**

devkit-utils/src/main/java/com/onixbyte/devkit/utils/Base64Util.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
* provided. It is recommended to specify the charset explicitly to ensure consistent
5050
* encoding and decoding.
5151
*
52-
* @author Zihlu Wang
52+
* @author zihluwang
5353
* @version 1.1.0
5454
* @since 1.0.0
5555
*/

devkit-utils/src/main/java/com/onixbyte/devkit/utils/ChainedCalcUtil.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,9 @@ private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal>
293293
* or null if not applicable
294294
* @return a ChainedCalcUtil instance with the updated value
295295
*/
296-
private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator, Object other, Integer beforeOperateScale) {
296+
private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal> operator,
297+
Object other,
298+
Integer beforeOperateScale) {
297299
return baseOperator((otherValue) ->
298300
operator.apply(this.value, otherValue),
299301
other,
@@ -311,7 +313,8 @@ private ChainedCalcUtil operator(BiFunction<BigDecimal, BigDecimal, BigDecimal>
311313
* @return a ChainedCalcUtil instance with the updated value
312314
*/
313315
private synchronized ChainedCalcUtil baseOperator(Function<BigDecimal, BigDecimal> operatorFunction,
314-
Object anotherValue, Integer beforeOperateScale) {
316+
Object anotherValue,
317+
Integer beforeOperateScale) {
315318
if (Objects.isNull(anotherValue)) {
316319
return this;
317320
}

devkit-utils/src/main/java/com/onixbyte/devkit/utils/HashUtil.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
* for data integrity checks and password storage, but they should not be used for
6262
* encryption purposes.
6363
*
64-
* @author Zihlu Wang
64+
* @author zihluwang
6565
* @version 1.1.0
6666
* @see java.security.MessageDigest
6767
* @since 1.0.0

devkit-utils/src/main/java/com/onixbyte/devkit/utils/MapUtil.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,8 @@
3030
* Note: Since version 1.4.2, this util class removed reflection API and transferred to a safer API.
3131
* Please see documentation for more information.
3232
*
33-
* @author Zihlu Wang
33+
* @author zihluwang
3434
* @version 1.4.2
35-
* @see com.onixbyte.devkit.utils.unsafe.ReflectMapUtil
3635
* @since 1.0.0
3736
*/
3837
@Slf4j

key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ private KeyLoader() {
5050
*
5151
* @param pemKeyText pem-formatted key text
5252
* @return loaded private key
53-
* @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance, or EC Key Factory is
54-
* not loaded, or key spec is invalid
53+
* @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
54+
* or EC Key Factory is not loaded, or key spec is invalid
5555
*/
56-
public ECPrivateKey loadEcdsaPrivateKey(String pemKeyText) {
56+
public static ECPrivateKey loadEcdsaPrivateKey(String pemKeyText) {
5757
try {
5858
var decodedKeyString = Base64.getDecoder().decode(pemKeyText);
5959
var keySpec = new PKCS8EncodedKeySpec(decodedKeyString);
@@ -76,10 +76,10 @@ public ECPrivateKey loadEcdsaPrivateKey(String pemKeyText) {
7676
*
7777
* @param pemKeyText pem-formatted key text
7878
* @return loaded private key
79-
* @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance, or EC Key Factory is
80-
* not loaded, or key spec is invalid
79+
* @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
80+
* or EC Key Factory is not loaded, or key spec is invalid
8181
*/
82-
public ECPublicKey loadEcdsaPublicKey(String pemKeyText) {
82+
public static ECPublicKey loadEcdsaPublicKey(String pemKeyText) {
8383
try {
8484
var keyBytes = Base64.getDecoder().decode(pemKeyText);
8585
var spec = new X509EncodedKeySpec(keyBytes);

key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,63 @@
1717

1818
package com.onixbyte.security.exception;
1919

20+
/**
21+
* {@code KeyLoadingException} is an exception indicating an error occurred while loading a key.
22+
*
23+
* @author zihluwang
24+
* @version 1.6.0
25+
* @since 1.6.0
26+
*/
2027
public class KeyLoadingException extends RuntimeException {
2128

29+
/**
30+
* Creates a new instance of {@code KeyLoadingException} without a specific message or cause.
31+
*/
2232
public KeyLoadingException() {
2333
}
2434

35+
/**
36+
* Creates a new instance of {@code KeyLoadingException} with the specified detail message.
37+
*
38+
* @param message the detail message
39+
*/
2540
public KeyLoadingException(String message) {
2641
super(message);
2742
}
2843

44+
/**
45+
* Creates a new instance of {@code KeyLoadingException} with the specified detail message
46+
* and cause.
47+
*
48+
* @param message the detail message
49+
* @param cause the cause of this exception
50+
*/
2951
public KeyLoadingException(String message, Throwable cause) {
3052
super(message, cause);
3153
}
3254

55+
/**
56+
* Creates a new instance of {@code KeyLoadingException} with the specified cause.
57+
*
58+
* @param cause the cause of this exception
59+
*/
3360
public KeyLoadingException(Throwable cause) {
3461
super(cause);
3562
}
3663

37-
public KeyLoadingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
64+
/**
65+
* Constructs a new exception with the specified detail message, cause, suppression enabled
66+
* or disabled, and writable stack trace enabled or disabled.
67+
*
68+
* @param message the detail message
69+
* @param cause the cause of this exception
70+
* @param enableSuppression whether suppression is enabled or disabled
71+
* @param writableStackTrace whether the stack trace should be writable
72+
*/
73+
public KeyLoadingException(String message,
74+
Throwable cause,
75+
boolean enableSuppression,
76+
boolean writableStackTrace) {
3877
super(message, cause, enableSuppression, writableStackTrace);
3978
}
4079
}

devkit-utils/src/main/java/com/onixbyte/devkit/utils/unsafe/ReflectMapUtil.java renamed to map-util-unsafe/src/main/java/com/onixbyte/devkit/utils/unsafe/ReflectMapUtil.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessEx
5353
var declaredFields = obj.getClass().getDeclaredFields();
5454
for (var field : declaredFields) {
5555
field.setAccessible(true);
56-
Object result = field.get(obj);
56+
var result = field.get(obj);
5757
if (result != null) {
5858
map.put(field.getName(), result);
5959
}
@@ -157,7 +157,8 @@ public static <T> T getFieldValue(Object obj, String fieldName, Class<T> fieldTy
157157
* @throws IllegalAccessException if an error occurs while accessing the field
158158
* @throws NoSuchMethodException if the specific setter is not present
159159
*/
160-
public static void setFieldValue(Object obj, String fieldName, Object fieldValue) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
160+
public static void setFieldValue(Object obj, String fieldName, Object fieldValue)
161+
throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
161162
var objectClass = obj.getClass();
162163
var methodName = getMethodName("set", fieldName);
163164
var method = objectClass.getDeclaredMethod(methodName, fieldValue.getClass());

simple-jwt-authzero/build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ version = buildVersion
3333
dependencies {
3434
implementation(project(":devkit-utils"))
3535
implementation(project(":guid"))
36+
implementation(project(":key-pair-loader"))
3637
implementation(project(":simple-jwt-facade"))
3738
implementation("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
3839
implementation("com.auth0:java-jwt:$javaJwtVersion")

simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java

Lines changed: 57 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import com.onixbyte.simplejwt.annotations.ExcludeFromPayload;
2626
import com.onixbyte.simplejwt.annotations.TokenEnum;
2727
import com.onixbyte.simplejwt.authzero.config.AuthzeroTokenResolverConfig;
28+
import com.onixbyte.simplejwt.config.TokenResolverConfig;
2829
import com.onixbyte.simplejwt.constants.PredefinedKeys;
2930
import com.onixbyte.simplejwt.constants.TokenAlgorithm;
3031
import com.auth0.jwt.JWT;
@@ -45,15 +46,13 @@
4546
import java.util.*;
4647

4748
/**
48-
* The {@code AuthzeroTokenResolver} class is an implementation of the {@link
49-
* TokenResolver} interface. It uses the {@code
50-
* com.auth0:java-jwt} library to handle JSON Web Token (JWT) resolution. This
51-
* resolver provides functionality to create, extract, verify, and renew JWT
49+
* The {@code AuthzeroTokenResolver} class is an implementation of the {@link TokenResolver}
50+
* interface. It uses the {@code com.auth0:java-jwt} library to handle JSON Web Token (JWT)
51+
* resolution. This resolver provides functionality to create, extract, verify, and renew JWT
5252
* tokens using various algorithms and custom payload data.
5353
* <p>
5454
* <b>Usage:</b>
55-
* To use the {@code AuthzeroTokenResolver}, first, create an instance of this
56-
* class:
55+
* To use the {@code AuthzeroTokenResolver}, first, create an instance of this class:
5756
* <pre>{@code
5857
* TokenResolver<DecodedJWT> tokenResolver =
5958
* new AuthzeroTokenResolver(TokenAlgorithm.HS256,
@@ -62,8 +61,7 @@
6261
* "Token Secret");
6362
* }</pre>
6463
* <p>
65-
* Then, you can utilize the various methods provided by this resolver to
66-
* handle JWT tokens:
64+
* Then, you can utilize the various methods provided by this resolver to handle JWT tokens:
6765
* <pre>{@code
6866
* // Creating a new JWT token
6967
* String token =
@@ -82,10 +80,9 @@
8280
* }</pre>
8381
* <p>
8482
* <b>Note:</b>
85-
* It is essential to configure the appropriate algorithms, secret, and issuer
86-
* according to your specific use case when using this resolver.
87-
* Additionally, ensure that the {@code com.auth0:java-jwt} library is
88-
* correctly configured in your project's dependencies.
83+
* It is essential to configure the appropriate algorithms, secret, and issuer according to your
84+
* specific use case when using this resolver. Additionally, ensure that the
85+
* {@code com.auth0:java-jwt} library is correctly configured in your project's dependencies.
8986
*
9087
* @author Zihlu Wang
9188
* @version 1.1.1
@@ -100,61 +97,77 @@
10097
public class AuthzeroTokenResolver implements TokenResolver<DecodedJWT> {
10198

10299
/**
103-
* Creates a new instance of {@code AuthzeroTokenResolver} with the
104-
* provided configurations.
100+
* Creates a new instance of {@code AuthzeroTokenResolver} with the provided configurations.
105101
*
106-
* @param jtiCreator the {@link GuidCreator} used for generating unique
107-
* identifiers for "jti" claim in JWT tokens
108-
* @param algorithm the algorithm used for signing and verifying JWT
109-
* tokens
102+
* @param jtiCreator the {@link GuidCreator} used for generating unique identifiers for "jti"
103+
* claim in JWT tokens
104+
* @param algorithm the algorithm used for signing and verifying JWT tokens
110105
* @param issuer the issuer claim value to be included in JWT tokens
111-
* @param secret the secret used for HMAC-based algorithms (HS256,
112-
* HS384, HS512) for token signing and verification
106+
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
107+
* token signing and verification, or the private key for ECDSA-based
108+
* algorithms
109+
* @param publicKey the public key for ECDSA-based algorithms
113110
* @param objectMapper JSON handler
114111
*/
115-
public AuthzeroTokenResolver(GuidCreator<?> jtiCreator, TokenAlgorithm algorithm, String issuer, String secret, ObjectMapper objectMapper) {
116-
if (secret == null || secret.isBlank()) {
117-
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
118-
}
112+
public AuthzeroTokenResolver(GuidCreator<?> jtiCreator,
113+
TokenAlgorithm algorithm,
114+
String issuer,
115+
String privateKey,
116+
String publicKey,
117+
ObjectMapper objectMapper) {
118+
if (TokenResolverConfig.HMAC_ALGORITHMS.contains(algorithm)) {
119+
if (privateKey == null || privateKey.isBlank()) {
120+
throw new IllegalArgumentException("A secret is required to build a JSON Web Token.");
121+
}
119122

120-
if (secret.length() < 32) {
121-
log.warn("The provided secret which owns {} characters is too weak. Please consider replacing it with a stronger one.", secret.length());
123+
if (privateKey.length() < 32) {
124+
log.warn("The provided secret which owns {} characters is too weak. Please consider" +
125+
" replacing it with a stronger one.", privateKey.length());
126+
}
122127
}
123128

124129
this.jtiCreator = jtiCreator;
125130
this.algorithm = config
126131
.getAlgorithm(algorithm)
127-
.apply(secret);
132+
.apply(privateKey, publicKey);
128133
this.issuer = issuer;
129134
this.verifier = JWT.require(this.algorithm).build();
130135
this.objectMapper = objectMapper;
131136
}
132137

133138
/**
134-
* Creates a new instance of {@link AuthzeroTokenResolver} with the
135-
* provided configurations and a simple UUID GuidCreator.
139+
* Creates a new instance of {@link AuthzeroTokenResolver} with the provided configurations
140+
* and a simple UUID GuidCreator.
136141
*
137142
* @param algorithm the algorithm used for signing and verifying JWT tokens
138143
* @param issuer the issuer claim value to be included in JWT tokens
139-
* @param secret the secret used for HMAC-based algorithms (HS256,
140-
* HS384, HS512) for token signing and verification
144+
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
145+
* token signing and verification, or the private key for ECDSA-based
146+
* algorithms
147+
* @param publicKey the public key for ECDSA-based algorithms
141148
* @param objectMapper Jackson Databind JSON Handler
142149
*/
143-
public AuthzeroTokenResolver(TokenAlgorithm algorithm, String issuer, String secret, ObjectMapper objectMapper) {
144-
this(UUID::randomUUID, algorithm, issuer, secret, objectMapper);
150+
public AuthzeroTokenResolver(TokenAlgorithm algorithm,
151+
String issuer,
152+
String privateKey,
153+
String publicKey,
154+
ObjectMapper objectMapper) {
155+
this(UUID::randomUUID, algorithm, issuer, privateKey, publicKey, objectMapper);
145156
}
146157

147158
/**
148-
* Creates a new instance of {@link AuthzeroTokenResolver} with the
149-
* provided configurations and a simple UUID GuidCreator.
159+
* Creates a new instance of {@link AuthzeroTokenResolver} with the provided configurations
160+
* and a simple UUID GuidCreator.
150161
*
151-
* @param algorithm the algorithm used for signing and verifying JWT tokens
152-
* @param issuer the issuer claim value to be included in JWT tokens
153-
* @param secret the secret used for HMAC-based algorithms (HS256,
154-
* HS384, HS512) for token signing and verification
162+
* @param algorithm the algorithm used for signing and verifying JWT tokens
163+
* @param issuer the issuer claim value to be included in JWT tokens
164+
* @param privateKey the secret used for HMAC-based algorithms (HS256, HS384, HS512) for
165+
* token signing and verification, or the private key for ECDSA-based
166+
* algorithms
167+
* @param publicKey the public key for ECDSA-based algorithms
155168
*/
156-
public AuthzeroTokenResolver(TokenAlgorithm algorithm, String issuer, String secret) {
157-
this(UUID::randomUUID, algorithm, issuer, secret, new ObjectMapper());
169+
public AuthzeroTokenResolver(TokenAlgorithm algorithm, String issuer, String privateKey, String publicKey) {
170+
this(UUID::randomUUID, algorithm, issuer, privateKey, publicKey, new ObjectMapper());
158171
}
159172

160173
/**
@@ -163,11 +176,10 @@ public AuthzeroTokenResolver(TokenAlgorithm algorithm, String issuer, String sec
163176
* UUID GuidCreator.
164177
*
165178
* @param issuer the issuer claim value to be included in JWT tokens
166-
* @param secret the secret used for HMAC-based algorithms (HS256,
167-
* HS384, HS512) for token signing and verification
179+
* @param secret the secret used for HS256 algorithms for token signing and verification
168180
*/
169181
public AuthzeroTokenResolver(String issuer, String secret) {
170-
this(UUID::randomUUID, TokenAlgorithm.HS256, issuer, secret, new ObjectMapper());
182+
this(UUID::randomUUID, TokenAlgorithm.HS256, issuer, secret, "", new ObjectMapper());
171183
}
172184

173185
/**
@@ -183,7 +195,7 @@ public AuthzeroTokenResolver(String issuer) {
183195
this.jtiCreator = UUID::randomUUID;
184196
this.algorithm = config
185197
.getAlgorithm(TokenAlgorithm.HS256)
186-
.apply(secret);
198+
.apply(secret, "");
187199
this.issuer = issuer;
188200
this.verifier = JWT.require(this.algorithm).build();
189201
this.objectMapper = new ObjectMapper();

0 commit comments

Comments
 (0)