serialRedisTemplate) {
+ this.serialRedisTemplate = serialRedisTemplate;
+ }
+
+ @Override public String nextId() {
+ return "SOME_PREFIX" + serialRedisTemplate.opsForValue().get("some_serial_key");
+ }
+
+}
```
-## Contact
-
-If you have any suggestions, ideas, don't hesitate contacting us via [GitHub Issues](https://github.com/CodeCraftersCN/jdevkit/issues/new) or [Discord Community](https://discord.gg/NQK9tjcBB8).
-
-If you face any bugs while using our library and you are able to fix any bugs in our library, we would be happy to accept pull requests from you on [GitHub](https://github.com/CodeCraftersCN/jdevkit/compare).
\ No newline at end of file
diff --git a/key-pair-loader/README.md b/key-pair-loader/README.md
new file mode 100644
index 0000000..2a8186d
--- /dev/null
+++ b/key-pair-loader/README.md
@@ -0,0 +1,64 @@
+# KeyLoader
+
+KeyLoader provides utility methods to load keys from pem-formatted key texts.
+
+## ECDSA-based algorithm
+
+### Generate key pair
+
+#### Generate private key
+
+Generate a private key by `genpkey` command provided by OpenSSL:
+
+```shell
+openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec_private_key.pem
+```
+
+The output of this command is a file called `ec_private_key.pem` and its content looks like the
+following:
+
+```text
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
++PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
+Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
+-----END PRIVATE KEY-----
+```
+
+#### Generate public key by private key
+
+Export public key from private key with `ec` command provided by OpenSSL:
+
+```shell
+openssl ec -in ec_private_key.pem -pubout -out ec_public_key.pem
+```
+
+The output of this command is a file called `ec_public_key.pem` and its content looks like the
+following:
+
+```text
+-----BEGIN PUBLIC KEY-----
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZAOxkWNouIIPKsdF1YgF1D/XD8Pa
+ZyYNcH60ONRWjMqlQXozWMb2i7WphKxf8kopp42nzCflWQod+JQY+hM/EQ==
+-----END PUBLIC KEY-----
+```
+
+#### Convert private key to EC formats which could be acceptable by Java
+
+Java's `PKCS8EncodedKeySpec` requires the private key to be in PKCS#8 format, while OpenSSL by
+default generates private keys in traditional PEM format. To convert the private key, run the
+following command:
+
+```shell
+openssl pkcs8 -topk8 -inform PEM -outform PEM -in ec_private_key.pem -out ec_private_key_pkcs8.pem -nocrypt
+```
+
+The converted private key will look like this:
+
+```text
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
++PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
+Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
+-----END PRIVATE KEY-----
+```
\ No newline at end of file
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java b/key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java
index b8fb3f1..0fa6a63 100644
--- a/key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java
+++ b/key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java
@@ -17,106 +17,36 @@
package com.onixbyte.security;
-import com.onixbyte.security.exception.KeyLoadingException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.security.KeyFactory;
-import java.security.NoSuchAlgorithmException;
-import java.security.interfaces.ECPrivateKey;
-import java.security.interfaces.ECPublicKey;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-import java.security.spec.X509EncodedKeySpec;
-import java.util.Base64;
+import java.security.PrivateKey;
+import java.security.PublicKey;
/**
- * The {@code KeyLoader} class provides utility methods for loading ECDSA keys from PEM-formatted
+ * The {@code KeyLoader} class provides utility methods for loading keys pairs from PEM-formatted
* key text. This class supports loading both private and public keys.
*
* The utility methods in this class are useful for scenarios where ECDSA keys need to be loaded
* from PEM-formatted strings for cryptographic operations.
- *
- *
- * Example usage:
- * {@code
- * String pemPrivateKey = """
- * -----BEGIN PRIVATE KEY-----
- * ...
- * -----END PRIVATE KEY-----""";
- * ECPrivateKey privateKey = KeyLoader.loadEcdsaPrivateKey(pemPrivateKey);
- *
- * String pemPublicKey = """
- * -----BEGIN PUBLIC KEY-----
- * ...
- * -----END PUBLIC KEY-----""";
- * ECPublicKey publicKey = KeyLoader.loadEcdsaPublicKey(pemPublicKey);
- * }
*
* @author zihluwang
- * @version 1.6.0
+ * @version 2.0.0
* @since 1.6.0
*/
-public class KeyLoader {
-
- private final static Logger log = LoggerFactory.getLogger(KeyLoader.class);
-
- /**
- * Private constructor prevents from being initialised.
- */
- private KeyLoader() {
- }
+public interface KeyLoader {
/**
- * Load ECDSA private key from pem-formatted key text.
+ * Load private key from pem-formatted key text.
*
* @param pemKeyText pem-formatted key text
* @return loaded private key
- * @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
- * or EC Key Factory is not loaded, or key spec is invalid
*/
- public static ECPrivateKey loadEcdsaPrivateKey(String pemKeyText) {
- try {
- var decodedKeyString = Base64.getDecoder().decode(pemKeyText);
- var keySpec = new PKCS8EncodedKeySpec(decodedKeyString);
- var keyFactory = KeyFactory.getInstance("EC");
- var _key = keyFactory.generatePrivate(keySpec);
- if (_key instanceof ECPrivateKey privateKey) {
- return privateKey;
- } else {
- throw new KeyLoadingException("Unable to load private key from pem-formatted key text.");
- }
- } catch (NoSuchAlgorithmException e) {
- throw new KeyLoadingException("Cannot get EC Key Factory.", e);
- } catch (InvalidKeySpecException e) {
- throw new KeyLoadingException("Key spec is invalid.", e);
- }
- }
+ PrivateKey loadPrivateKey(String pemKeyText);
/**
- * Load ECDSA public key from pem-formatted key text.
+ * Load public key from pem-formatted key text.
*
* @param pemKeyText pem-formatted key text
* @return loaded private key
- * @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
- * or EC Key Factory is not loaded, or key spec is invalid
*/
- public static ECPublicKey loadEcdsaPublicKey(String pemKeyText) {
- try {
- var keyBytes = Base64.getDecoder().decode(pemKeyText);
- var spec = new X509EncodedKeySpec(keyBytes);
- var keyFactory = KeyFactory.getInstance("EC");
- var key = keyFactory.generatePublic(spec);
- if (key instanceof ECPublicKey publicKey) {
- return publicKey;
- } else {
- throw new KeyLoadingException("Unable to load private key from pem-formatted key text.");
- }
- } catch (NoSuchAlgorithmException e) {
- throw new KeyLoadingException("Cannot get EC Key Factory.", e);
- } catch (InvalidKeySpecException e) {
- throw new KeyLoadingException("Key spec is invalid.", e);
- }
- }
+ PublicKey loadPublicKey(String pemKeyText);
}
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java b/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java
index 853f203..3c4cabc 100644
--- a/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java
+++ b/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java
@@ -29,7 +29,8 @@
* Example usage:
* {@code
* try {
- * ECPrivateKey privateKey = KeyLoader.loadEcdsaPrivateKey(pemPrivateKey);
+ * KeyLoader keyLoader = new EcKeyLoader();
+ * ECPrivateKey privateKey = keyLoader.loadPrivateKey(pemPrivateKey);
* } catch (KeyLoadingException e) {
* // Handle the exception
* e.printStackTrace();
@@ -37,7 +38,7 @@
* }
*
* @author zihluwang
- * @version 1.6.0
+ * @version 2.0.0
* @since 1.6.0
*/
public class KeyLoadingException extends RuntimeException {
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/impl/EcKeyLoader.java b/key-pair-loader/src/main/java/com/onixbyte/security/impl/EcKeyLoader.java
new file mode 100644
index 0000000..b94b1f7
--- /dev/null
+++ b/key-pair-loader/src/main/java/com/onixbyte/security/impl/EcKeyLoader.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2024-2025 OnixByte.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.onixbyte.security.impl;
+
+import com.onixbyte.security.KeyLoader;
+import com.onixbyte.security.exception.KeyLoadingException;
+
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Base64;
+
+/**
+ * Key pair loader for loading key pairs for ECDSA-based algorithms.
+ *
+ *
+ * Example usage for ECDSA:
+ *
{@code
+ * KeyLoader keyLoader = new EcKeyLoader();
+ * String pemPrivateKey = """
+ * -----BEGIN EC PRIVATE KEY-----
+ * ...
+ * -----END EC PRIVATE KEY-----""";
+ * ECPrivateKey privateKey = KeyLoader.loadEcdsaPrivateKey(pemPrivateKey);
+ *
+ * String pemPublicKey = """
+ * -----BEGIN EC PUBLIC KEY-----
+ * ...
+ * -----END EC PUBLIC KEY-----""";
+ * ECPublicKey publicKey = KeyLoader.loadPublicKey(pemPublicKey);
+ * }
+ *
+ * @author zihluwang
+ * @version 2.0.0
+ * @since 2.0.0
+ */
+public class EcKeyLoader implements KeyLoader {
+
+ private final KeyFactory keyFactory;
+
+ private final Base64.Decoder decoder;
+
+ /**
+ * Initialise a key loader for EC-based algorithms.
+ */
+ public EcKeyLoader() {
+ try {
+ this.keyFactory = KeyFactory.getInstance("EC");
+ this.decoder = Base64.getDecoder();
+ } catch (NoSuchAlgorithmException e) {
+ throw new KeyLoadingException(e);
+ }
+ }
+
+ /**
+ * Load ECDSA private key from pem-formatted key text.
+ *
+ * @param pemKeyText pem-formatted key text
+ * @return loaded private key
+ * @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
+ * or EC Key Factory is not loaded, or key spec is invalid
+ */
+ @Override
+ public ECPrivateKey loadPrivateKey(String pemKeyText) {
+ try {
+ // remove all unnecessary parts of the pem key text
+ pemKeyText = pemKeyText
+ .replaceAll("-----BEGIN (EC )?PRIVATE KEY-----", "")
+ .replaceAll("-----END (EC )?PRIVATE KEY-----", "")
+ .replaceAll("\n", "");
+ var decodedKeyString = decoder.decode(pemKeyText);
+ var keySpec = new PKCS8EncodedKeySpec(decodedKeyString);
+
+ var _key = keyFactory.generatePrivate(keySpec);
+ if (_key instanceof ECPrivateKey privateKey) {
+ return privateKey;
+ } else {
+ throw new KeyLoadingException("Unable to load private key from pem-formatted key text.");
+ }
+ } catch (InvalidKeySpecException e) {
+ throw new KeyLoadingException("Key spec is invalid.", e);
+ }
+ }
+
+ /**
+ * Load public key from pem-formatted key text.
+ *
+ * @param pemKeyText pem-formatted key text
+ * @return loaded private key
+ * @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
+ * or EC Key Factory is not loaded, or key spec is invalid
+ */
+ @Override
+ public ECPublicKey loadPublicKey(String pemKeyText) {
+ try {
+ // remove all unnecessary parts of the pem key text
+ pemKeyText = pemKeyText
+ .replaceAll("-----BEGIN (EC )?PUBLIC KEY-----", "")
+ .replaceAll("-----END (EC )?PUBLIC KEY-----", "")
+ .replaceAll("\n", "");
+ var keyBytes = decoder.decode(pemKeyText);
+ var spec = new X509EncodedKeySpec(keyBytes);
+ var key = keyFactory.generatePublic(spec);
+ if (key instanceof ECPublicKey publicKey) {
+ return publicKey;
+ } else {
+ throw new KeyLoadingException("Unable to load public key from pem-formatted key text.");
+ }
+ } catch (InvalidKeySpecException e) {
+ throw new KeyLoadingException("Key spec is invalid.", e);
+ }
+ }
+
+}
diff --git a/key-pair-loader/src/test/java/com/onixbyte/security/KeyPairLoaderTest.java b/key-pair-loader/src/test/java/com/onixbyte/security/KeyPairLoaderTest.java
index edfc670..ca57f74 100644
--- a/key-pair-loader/src/test/java/com/onixbyte/security/KeyPairLoaderTest.java
+++ b/key-pair-loader/src/test/java/com/onixbyte/security/KeyPairLoaderTest.java
@@ -17,13 +17,29 @@
package com.onixbyte.security;
+import com.onixbyte.security.impl.EcKeyLoader;
import org.junit.jupiter.api.Test;
public class KeyPairLoaderTest {
@Test
public void test() {
-
+ var keyLoader = new EcKeyLoader();
+ // The following key pair is only used for test only, and is already exposed to public.
+ // DO NOT USE THEM FOR PRODUCTION!
+ var privateKey = keyLoader.loadPrivateKey("""
+ -----BEGIN PRIVATE KEY-----
+ MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
+ +PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
+ Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
+ -----END PRIVATE KEY-----
+ """);
+ var publicKey = keyLoader.loadPublicKey("""
+ -----BEGIN PUBLIC KEY-----
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZAOxkWNouIIPKsdF1YgF1D/XD8Pa
+ ZyYNcH60ONRWjMqlQXozWMb2i7WphKxf8kopp42nzCflWQod+JQY+hM/EQ==
+ -----END PUBLIC KEY-----
+ """);
}
}
diff --git a/key-pair-loader/src/test/resources/ec_private_key.pem b/key-pair-loader/src/test/resources/ec_private_key.pem
new file mode 100644
index 0000000..02dfcc8
--- /dev/null
+++ b/key-pair-loader/src/test/resources/ec_private_key.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
++PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
+Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
+-----END PRIVATE KEY-----
diff --git a/key-pair-loader/src/test/resources/ec_private_key_pkcs8.pem b/key-pair-loader/src/test/resources/ec_private_key_pkcs8.pem
new file mode 100644
index 0000000..02dfcc8
--- /dev/null
+++ b/key-pair-loader/src/test/resources/ec_private_key_pkcs8.pem
@@ -0,0 +1,5 @@
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
++PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
+Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
+-----END PRIVATE KEY-----
diff --git a/key-pair-loader/src/test/resources/ec_public_key.pem b/key-pair-loader/src/test/resources/ec_public_key.pem
new file mode 100644
index 0000000..ff0054e
--- /dev/null
+++ b/key-pair-loader/src/test/resources/ec_public_key.pem
@@ -0,0 +1,4 @@
+-----BEGIN PUBLIC KEY-----
+MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZAOxkWNouIIPKsdF1YgF1D/XD8Pa
+ZyYNcH60ONRWjMqlQXozWMb2i7WphKxf8kopp42nzCflWQod+JQY+hM/EQ==
+-----END PUBLIC KEY-----
diff --git a/map-util-unsafe/README.md b/map-util-unsafe/README.md
new file mode 100644
index 0000000..e5de9cb
--- /dev/null
+++ b/map-util-unsafe/README.md
@@ -0,0 +1,5 @@
+# Map Util Unsafe
+
+`map-util-unsafe` provides a set of more convenient utilities for converting Java bean to Map or Map to Java bean, but which are less safe than the `MapUtil` provided in `devkit-utils`.
+
+This `MapUtil` is implemented with Reflect API, which might be removed in later JDKs.
\ No newline at end of file
diff --git a/num4j/README.md b/num4j/README.md
new file mode 100644
index 0000000..7745ec1
--- /dev/null
+++ b/num4j/README.md
@@ -0,0 +1,3 @@
+# Num4j
+
+`num4j` provides some mathematical algorithms and utilities such as chained high-precision mathematical calculator and percentile statistic algorithm.
\ No newline at end of file
diff --git a/property-guard-spring-boot-starter/README.md b/property-guard-spring-boot-starter/README.md
index 51e9e52..32cc31f 100644
--- a/property-guard-spring-boot-starter/README.md
+++ b/property-guard-spring-boot-starter/README.md
@@ -1,97 +1,37 @@
# Property Guard
-## Introduction
+`property-guard-spring-boot-starter` is a utility that can help you protect secret values in Spring Boot configurations.
-This feature is designed to protect the security of configurations and data, to a certain extent, to control the flow of developers leading to the leakage of sensitive information.
+## Example usage
-## Prerequisites
+### 1. Implementation this module
-This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience. Except this, this module is designed for Spring Boot framework, so you have to install Spring Boot (v3) in your application.
-
-## Installation
-
-### If you are using `Maven`
-
-It is quite simple to install this module by `Maven`. The only thing you need to do is find your `pom.xml` file in the project, then find the `` node in the `` node, and add the following codes to `` node:
-
-```xml
-
- cn.org.codecrafters
- property-guard-spring-boot-starter
- ${property-guard-spring-boot-starter.version}
-
-```
-
-And run `mvn dependency:get` in your project root folder(i.e., if your `pom.xml` is located at `/path/to/your/project/pom.xml`, then your current work folder should be `/path/to/your/project`), then `Maven` will automatically download the `jar` archive from `Maven Central Repository`. This could be **MUCH EASIER** if you are using IDE(i.e., IntelliJ IDEA), the only thing you need to do is click the refresh button of `Maven`.
-
-If you are restricted using the Internet, and have to make `Maven` offline, you could follow the following steps.
-
-1. Download the `jar` file from any place you can get and transfer the `jar` files to your work computer.
-2. Move the `jar` files to your local `Maven` Repository as the path of `/path/to/maven_local_repo/cn/org/codecrafters/property-guard-spring-boot-starter/`.
-
-### If you are using `Gradle`
-
-Add this module to your project with `Gradle` is much easier than doing so with `Maven`.
-
-Find `build.gradle` in the needed project, and add the following code to the `dependencies` closure in the build script:
-
-```groovy
-implementation 'cn.org.codecrafters:property-guard-spring-boot-starter:${property-guard-spring-boot-starter.version}'
-```
-
-### If you are not using `Maven` or `Gradle`
-
-1. Download the `jar` file from the Internet.
-2. Create a folder in your project and name it as a name you like(i.e., for me, I prefer `vendor`).
-3. Put the `jar` file to the folder you just created in Step 2.
-4. Add this folder to your project `classpath`.
-
-## Usage
-
-First, you need a 16-bit-long secret. If you don't have a good way to get a secret, you could consider using our `utils.com.onixbyte.devkit.AesUtil` or `com.onixbyte.simplejwt.SecretCreator` to create a secret.
-
-For example:
-```java
-import utils.com.onixbyte.devkit.AesUtil;
-import com.onixbyte.simplejwt.SecretCreator;
-
-class GenerateRandomKeySample {
- public static void main(String[] args) {
- var secret1 = AesUtil.generateRandomSecret();
- var secret2 = SecretCreator.createSecret(16, true, true, true);
- }
+```kotlin
+dependencies {
+ implementation(platform("com.onixbyte:devkit-bom:$devKitVersion"))
+ implementation("com.onixbyte:devkit-utils")
+ implementation("com.onixbyte:property-guard-spring-boot-starter")
}
```
-Then, remember this secret and encrypt the configuration properties that are required high security. For example:
+### 2. Generate a secret
-```java
-import utils.com.onixbyte.devkit.AesUtil;
+Use the following codes to get a random secret.
-class EncryptSample {
- public static void main(String[] args) {
- var dataNeedEncryption = "Sample Value";
- var key = "3856faef0d2d4f33";
- var encryptedData = AesUtil.encrypt(dataNeedEncryption, key);
+```java
+@SpringBootTest
+class SpringBootApplicationTest {
+
+ @Test
+ void contextLoads() {
+ System.out.println(AesUtil.generateRandomSecret()); // Output: a 16-char long secret
}
}
```
-After that, copy the encrypted data to `application.properties` or `application.yml`.
-
-For `yml`:
-```yaml
-app:
- sample-configuration: pe:t4YBfv8M9ZmTzWgTi2gJqg== # "pe:" is the prefix that declare that this property is encrypted.
-```
-
-For `properties`:
-```properties
-app.sample-configuration=pe:t4YBfv8M9ZmTzWgTi2gJqg==
-```
+Or you can write a 16-char long secret by yourself.
-## Contact
+### 3. Encrypt your secret properties and place them into your configuration file
-If you have any suggestions, ideas, don't hesitate contacting us via [GitHub Issues](https://github.com/CodeCraftersCN/jdevkit/issues/new) or [Discord Community](https://discord.gg/NQK9tjcBB8).
+### 4. Run application with parameter `--pg.key=$your_secret`
-If you face any bugs while using our library and you are able to fix any bugs in our library, we would be happy to accept pull requests from you on [GitHub](https://github.com/CodeCraftersCN/jdevkit/compare).
\ No newline at end of file
diff --git a/settings.gradle.kts b/settings.gradle.kts
index 1a7eb27..084a020 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -27,5 +27,6 @@ include(
"simple-jwt-facade",
"simple-jwt-authzero",
"simple-jwt-spring-boot-starter",
- "property-guard-spring-boot-starter"
+ "property-guard-spring-boot-starter",
+ "simple-serial"
)
diff --git a/simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java b/simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java
index 51e0267..759054c 100644
--- a/simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java
+++ b/simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java
@@ -20,6 +20,7 @@
import com.onixbyte.devkit.utils.Base64Util;
import com.onixbyte.guid.GuidCreator;
import com.onixbyte.security.KeyLoader;
+import com.onixbyte.security.impl.EcKeyLoader;
import com.onixbyte.simplejwt.TokenPayload;
import com.onixbyte.simplejwt.TokenResolver;
import com.onixbyte.simplejwt.annotations.ExcludeFromPayload;
@@ -42,6 +43,7 @@
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
+import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.time.Duration;
@@ -178,8 +180,9 @@ public Builder secret(String secret) {
* @return the builder instance
*/
public Builder keyPair(String publicKey, String privateKey) {
- this.publicKey = KeyLoader.loadEcdsaPublicKey(publicKey);
- this.privateKey = KeyLoader.loadEcdsaPrivateKey(privateKey);
+ var keyLoader = new EcKeyLoader();
+ this.publicKey = keyLoader.loadPublicKey(publicKey);
+ this.privateKey = keyLoader.loadPrivateKey(privateKey);
return this;
}
diff --git a/simple-jwt-spring-boot-starter/README.md b/simple-jwt-spring-boot-starter/README.md
index 772be19..8b3a8ca 100644
--- a/simple-jwt-spring-boot-starter/README.md
+++ b/simple-jwt-spring-boot-starter/README.md
@@ -29,7 +29,7 @@ It is quite simple to install this module by `Maven`. The only thing you need to
${simple-jwt-${any-implementation}.version}
- cn.org.codecrafters
+ com.onixbyte
simple-jwt-spring-boot-starter
${simple-jwt-spring-boot-starter.version}
@@ -50,7 +50,7 @@ Find `build.gradle` in the needed project, and add the following code to the `de
```groovy
implementation '${implementation-builder-group-id}:simple-jwt-${any-implementation}:${simple-jwt-${any-implementation}.version}'
-implementation 'cn.org.codecrafters:simple-jwt-spring-boot-starter:${simple-jwt-spring-boot-starter.version}'
+implementation 'com.onixbyte:simple-jwt-spring-boot-starter:${simple-jwt-spring-boot-starter.version}'
```
### If you are not using `Maven` or `Gradle`
diff --git a/simple-serial/README.md b/simple-serial/README.md
new file mode 100644
index 0000000..8a4d20c
--- /dev/null
+++ b/simple-serial/README.md
@@ -0,0 +1,14 @@
+# Simple Serial
+
+> Thanks to [@siujamo](https://github.com/siujamo)'s donation.
+
+Simple Serial reuses the configuration of Redis connections to provide am easy-to-use serial
+service.
+
+## Configuration
+
+Simple Serial reused the redis configuration of Spring Boot to provide redis support for the
+service.
+
+Besides, **Simple Serial** provides a configuration property `onixbyte.serial.start-serial` to
+specify the start value of a serial, and default to `0`.
\ No newline at end of file
diff --git a/simple-serial/build.gradle.kts b/simple-serial/build.gradle.kts
new file mode 100644
index 0000000..36f1eda
--- /dev/null
+++ b/simple-serial/build.gradle.kts
@@ -0,0 +1,99 @@
+import java.net.URI
+
+plugins {
+ id("java")
+}
+
+val artefactVersion: String by project
+val projectUrl: String by project
+val projectGithubUrl: String by project
+val licenseName: String by project
+val licenseUrl: String by project
+
+val jacksonVersion: String by project
+val springBootVersion: String by project
+
+group = "com.onixbyte"
+version = artefactVersion
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion")
+ implementation("org.springframework.boot:spring-boot-autoconfigure:$springBootVersion")
+ implementation("org.springframework.boot:spring-boot-starter-logging:$springBootVersion")
+ implementation("org.springframework.boot:spring-boot-configuration-processor:$springBootVersion")
+ implementation("org.springframework.boot:spring-boot-starter-data-redis:$springBootVersion")
+ annotationProcessor("org.springframework.boot:spring-boot-configuration-processor:$springBootVersion")
+ testImplementation("org.springframework.boot:spring-boot-starter-test:$springBootVersion")
+ testImplementation(platform("org.junit:junit-bom:5.10.0"))
+ testImplementation("org.junit.jupiter:junit-jupiter")
+}
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ withSourcesJar()
+ withJavadocJar()
+}
+
+tasks.test {
+ useJUnitPlatform()
+}
+
+publishing {
+ publications {
+ create("simpleSerialSpringBootStarter") {
+ groupId = group.toString()
+ artifactId = "simple-serial-spring-boot-starter"
+ version = artefactVersion
+
+ pom {
+ name = "Simple Serial :: Spring Boot Starter"
+ description = "A Redis based easy-to-use serial service."
+ url = projectUrl
+
+ licenses {
+ license {
+ name = licenseName
+ url = licenseUrl
+ }
+ }
+
+ scm {
+ connection = "scm:git:git://github.com:OnixByte/JDevKit.git"
+ developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git"
+ url = projectGithubUrl
+ }
+
+ developers {
+ developer {
+ id = "zihluwang"
+ name = "Zihlu Wang"
+ email = "really@zihlu.wang"
+ timezone = "Asia/Hong_Kong"
+ }
+ }
+ }
+
+ from(components["java"])
+
+ signing {
+ sign(publishing.publications["simpleSerialSpringBootStarter"])
+ }
+ }
+
+ repositories {
+ maven {
+ name = "sonatypeNexus"
+ url = URI(providers.gradleProperty("repo.maven-central.host").get())
+ credentials {
+ username = providers.gradleProperty("repo.maven-central.username").get()
+ password = providers.gradleProperty("repo.maven-central.password").get()
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/simple-serial/src/main/java/com/onixbyte/serial/RedisConfig.java b/simple-serial/src/main/java/com/onixbyte/serial/RedisConfig.java
new file mode 100644
index 0000000..99a4527
--- /dev/null
+++ b/simple-serial/src/main/java/com/onixbyte/serial/RedisConfig.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2024-2025 OnixByte.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.onixbyte.serial;
+
+import org.springframework.boot.autoconfigure.AutoConfiguration;
+import org.springframework.context.annotation.Bean;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+import org.springframework.data.redis.serializer.RedisSerializer;
+
+/**
+ * Redis Configuration provides redis templates for operations to serial.
+ *
+ * @author siujamo
+ */
+@AutoConfiguration
+public class RedisConfig {
+
+ /**
+ * RedisTemplate for serial service.
+ *
+ * @param redisConnectionFactory redis connection factory
+ * @return a configured redis template for serial service
+ */
+ @Bean
+ public RedisTemplate serialRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
+ var redisTemplate = new RedisTemplate();
+ redisTemplate.setConnectionFactory(redisConnectionFactory);
+ redisTemplate.setKeySerializer(RedisSerializer.string());
+ redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(Long.class));
+ redisTemplate.afterPropertiesSet();
+ return redisTemplate;
+ }
+
+}
diff --git a/simple-serial/src/main/java/com/onixbyte/serial/SerialService.java b/simple-serial/src/main/java/com/onixbyte/serial/SerialService.java
new file mode 100644
index 0000000..55d6fbf
--- /dev/null
+++ b/simple-serial/src/main/java/com/onixbyte/serial/SerialService.java
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2024-2025 OnixByte.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.onixbyte.serial;
+
+import com.onixbyte.serial.properties.SerialProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.util.Optional;
+
+/**
+ * {@code SerialService} provides simple serial operations.
+ *
+ * @author siujamo
+ */
+@Service
+@EnableConfigurationProperties(SerialProperties.class)
+public class SerialService {
+
+ private static final Logger log = LoggerFactory.getLogger(SerialService.class);
+
+ private final String appName;
+ private final RedisTemplate serialRedisTemplate;
+ private final SerialProperties serialProperties;
+
+ /**
+ * Default constructor.
+ *
+ * @param appName the name of this application
+ * @param serialRedisTemplate serial redis template
+ * @param serialProperties serial properties
+ */
+ public SerialService(@Value("${spring.application.name}") String appName,
+ RedisTemplate serialRedisTemplate,
+ SerialProperties serialProperties) {
+ this.appName = appName;
+ this.serialRedisTemplate = serialRedisTemplate;
+ this.serialProperties = serialProperties;
+ }
+
+ /**
+ * Build a serial key.
+ *
+ * @param tag tag of the serial
+ * @return key of a serial
+ */
+ public String buildKey(String tag) {
+ return appName + ":serial:" + tag;
+ }
+
+ /**
+ * Get the next available serial for specific tag.
+ *
+ * @param tag tag of the serial
+ * @return next available serial
+ */
+ public Long nextSerial(String tag) {
+ var key = buildKey(tag);
+ var next = Optional.ofNullable(serialRedisTemplate.opsForValue().get(key))
+ .orElse(serialProperties.getStartSerial());
+ serialRedisTemplate.opsForValue().set(key, next + 1);
+ return next;
+ }
+
+ /**
+ * Reset all serial values.
+ */
+ public void reset() {
+ var keys = serialRedisTemplate.keys(buildKey("*"));
+ var startSerial = serialProperties.getStartSerial();
+
+ if (!keys.isEmpty()) {
+ for (var key : keys) {
+ serialRedisTemplate.opsForValue().set(key, startSerial);
+ log.debug("Serial {} has been reset to {}", key, startSerial);
+ }
+ }
+ }
+
+}
diff --git a/simple-serial/src/main/java/com/onixbyte/serial/properties/SerialProperties.java b/simple-serial/src/main/java/com/onixbyte/serial/properties/SerialProperties.java
new file mode 100644
index 0000000..cb2552d
--- /dev/null
+++ b/simple-serial/src/main/java/com/onixbyte/serial/properties/SerialProperties.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2024-2025 OnixByte.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.onixbyte.serial.properties;
+
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * SerialProperties can modify the start value of a serial.
+ *
+ * @author siujamo
+ */
+@ConfigurationProperties(prefix = "onixbyte.serial")
+public class SerialProperties {
+
+ /**
+ * The start of the serial, default to 0.
+ */
+ private Long startSerial = 0L;
+
+ /**
+ * Get the start of the serial.
+ *
+ * @return start of the serial
+ */
+ public Long getStartSerial() {
+ return startSerial;
+ }
+
+ /**
+ * Set the start of the serial.
+ *
+ * @param startSerial start of the serial
+ */
+ public void setStartSerial(Long startSerial) {
+ this.startSerial = startSerial;
+ }
+
+ /**
+ * Default constructor.
+ */
+ public SerialProperties() {
+ }
+
+}
diff --git a/simple-serial/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/simple-serial/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
new file mode 100644
index 0000000..7fd0a37
--- /dev/null
+++ b/simple-serial/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
@@ -0,0 +1,19 @@
+#
+# Copyright (C) 2024-2025 OnixByte.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+com.onixbyte.serial.RedisConfig
+com.onixbyte.serial.SerialService
\ No newline at end of file
diff --git a/simple-serial/src/main/resources/logback.xml b/simple-serial/src/main/resources/logback.xml
new file mode 100644
index 0000000..fd31eac
--- /dev/null
+++ b/simple-serial/src/main/resources/logback.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
+
+ ${COLOURFUL_OUTPUT}
+
+
+
+
+
+
\ No newline at end of file