diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index d13e3e2..b18c455 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -2,7 +2,10 @@
## Our Pledge
-We as members, contributors, and leaders pledge to make participation in our project a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
+We as members, contributors, and leaders pledge to make participation in our project
+a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity,
+gender identity and expression, level of experience, nationality, personal appearance, race,
+religion, or sexual identity and orientation.
## Our Standards
@@ -20,26 +23,40 @@ Examples of unacceptable behaviour by participants include:
- Trolling, insulting, or derogatory comments
- Personal or political attacks
- Public or private harassment
-- Publishing others’ private information, such as a physical or electronic address, without explicit permission
+- Publishing others’ private information, such as a physical or electronic address, without
+ explicit permission
- Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
-Project maintainers are responsible for clarifying the standards of acceptable behaviour and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour.
+Project maintainers are responsible for clarifying the standards of acceptable behaviour and are
+expected to take appropriate and fair corrective action in response to any instances of
+unacceptable behaviour.
-Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that do not align with this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits,
+code, wiki edits, issues, and other contributions that do not align with this Code of Conduct, and
+will communicate reasons for moderation decisions when appropriate.
## Scope
-This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
+This Code of Conduct applies both within project spaces and in public spaces when an individual is
+representing the project or its community. Examples of representing a project or community include
+using an official project email address, posting via an official social media account, or acting as
+an appointed representative at an online or offline event.
## Enforcement
-Instances of abusive, harassing, or unacceptable behaviour may be reported by contacting the project team at [your-email@example.com]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident.
+Instances of abusive, harassing, or unacceptable behaviour may be reported by contacting the
+project team at [opensource@onixbyte.com](mailto:opensource@onixbyte.com). All complaints will be
+reviewed and investigated and will result in a response that is deemed necessary and appropriate to
+the circumstances. The project team is obligated to maintain confidentiality with regard to the
+reporter of an incident.
-Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face
+temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
-This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 1.4, available at https://www.contributor-covenant.org/version/1/4/
+This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/),
+version 1.4, available at https://www.contributor-covenant.org/version/1/4/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2fd937c..5ed8874 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,18 +1,18 @@
-# Contributing to Java Dev Kit
+# Contributing to OnixByte Toolbox
-We appreciate your interest in contributing to our Java Enterprise Utility Library. Contributions are welcome in various
-forms such as code, documentation, bug reports, and test cases. To ensure a smooth collaboration, please follow the
-guidelines outlined below.
+We appreciate your interest in contributing to our Java Enterprise Utility Library. Contributions
+are welcome in various forms such as code, documentation, bug reports, and test cases. To ensure a
+smooth collaboration, please follow the guidelines outlined below.
## Getting Started
-The Java Dev Kit is an open-source Java library designed to ease Java enterprise application development. It is built
-with Java 17, and we require contributors to use OpenJDK 17.
+The OnixByte Toolbox is an open-source Java library designed to ease Java enterprise
+application development. It is built with Java 17, and we require contributors to use OpenJDK 17.
## Development Setup
-There is no need for manual setup beyond ensuring you have JDK 17 and a stable internet connection. Our project uses
-Gradle Wrapper for building, simplifying the setup process.
+There is no need for manual setup beyond ensuring you have JDK 17 and a stable internet connection.
+Our project uses Gradle Wrapper for building, simplifying the setup process.
```shell
./gradlew build
@@ -20,13 +20,13 @@ Gradle Wrapper for building, simplifying the setup process.
## Branching Strategy
-We follow the `git-flow` branching model. Contributors should fork this repository and create their work on separate
-branches prefixed with `feature/` or `hotfix/` as appropriate.
+We follow the `git-flow` branching model. Contributors should fork this repository and create their
+work on separate branches prefixed with `feature/` or `hotfix/` as appropriate.
## Code Style
-Please adhere to the coding standards specified in our `.editorconfig` file in the root of the repository. Consistent
-style helps in maintaining readability and uniformity across the codebase.
+Please adhere to the coding standards specified in our `.editorconfig` file in the root of
+the repository. Consistent style helps in maintaining readability and uniformity across the codebase.
## Commit Messages
@@ -52,8 +52,10 @@ This format helps in auto-generating changelogs and understanding the purpose be
## Testing
-We encourage using JUnit Jupiter for unit and integration tests. Pull Requests with accompanying test reports are prioritised for review and merging.
+We encourage using JUnit Jupiter for unit and integration tests. Pull Requests with accompanying
+test reports are prioritised for review and merging.
## License
-By contributing to the Java Dev Kit, you agree that your contributions will be licensed under the Apache 2.0 license. If you do not agree to this, please refrain from contributing.
\ No newline at end of file
+By contributing to the OnixByte Toolbox, you agree that your contributions will be licensed under the
+MIT license. If you do not agree to this, please refrain from contributing.
diff --git a/LICENSE b/LICENSE
index 5548015..8c2f4a4 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,202 +1,21 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "[]"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 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.
\ No newline at end of file
+MIT License
+
+Copyright (c) 2024-2025 OnixByte
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/build.gradle.kts b/build.gradle.kts
index b76a169..533233b 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -1,16 +1,21 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
- */
\ No newline at end of file
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
diff --git a/devkit-utils/README.md b/common-toolbox/README.md
similarity index 65%
rename from devkit-utils/README.md
rename to common-toolbox/README.md
index 6d2b02f..46be06b 100644
--- a/devkit-utils/README.md
+++ b/common-toolbox/README.md
@@ -1,8 +1,9 @@
-# Module `devkit-utils`
+# Common Toolbox
## Introduction
-This module provides a set of utilities to streamline Java codes.
+Common Toolbox is a Java SE utility library, that provides a collection of utility to streamline
+your Java coding experience.
## Features
diff --git a/devkit-utils/build.gradle.kts b/common-toolbox/build.gradle.kts
similarity index 66%
rename from devkit-utils/build.gradle.kts
rename to common-toolbox/build.gradle.kts
index 3d6bcd2..12d83a9 100644
--- a/devkit-utils/build.gradle.kts
+++ b/common-toolbox/build.gradle.kts
@@ -1,19 +1,25 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
+
import java.net.URI
plugins {
@@ -64,14 +70,14 @@ tasks.test {
publishing {
publications {
- create
Example usage:
- *
- * {@code
+ * {@code
* boolean result1 = BoolUtil.and(true, true, false); // false
* boolean result2 = BoolUtil.or(true, false, false); // true
* boolean result3 = BoolUtil.not(false); // true
- * }
- *
+ * }
*
* @author zihluwang
- * @version 1.6.2
- * @since 1.6.2
+ * @version 3.0.0
*/
public final class BoolUtil {
+ /**
+ * Private constructor to prevent instantiation of this utility class.
+ */
+ private BoolUtil() {
+ }
+
/**
* Logical and calculation.
*
@@ -91,10 +99,4 @@ public static boolean or(BooleanSupplier... valueSuppliers) {
.filter(Objects::nonNull)
.anyMatch(BooleanSupplier::getAsBoolean);
}
-
- /**
- * Private constructor to prevent instantiation of this utility class.
- */
- private BoolUtil() {}
-
}
diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/BranchUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/BranchUtil.java
similarity index 84%
rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/BranchUtil.java
rename to common-toolbox/src/main/java/com/onixbyte/common/util/BranchUtil.java
index f493a70..c3e5dc1 100644
--- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/BranchUtil.java
+++ b/common-toolbox/src/main/java/com/onixbyte/common/util/BranchUtil.java
@@ -1,21 +1,26 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import java.util.Objects;
import java.util.function.BooleanSupplier;
@@ -64,11 +69,10 @@
* expressions.
*
* @author zihluwang
- * @version 2.1.3
+ * @version 3.0.0
* @see java.util.function.Supplier
* @see java.util.function.BooleanSupplier
* @see java.lang.Runnable
- * @since 1.0.0
*/
public final class BranchUtil {
@@ -167,7 +171,8 @@ public Example usage:
- *
- * {@code
+ * {@code
+ * // User.java
* public class User {
* private String name;
* private int age;
*
* // getters and setters
* }
- *
+ *
+ * // UserMapAdapter.java
* public class UserMapAdapter implements ObjectMapAdapter {
* @Override
* public Map toMap(User user) {
@@ -73,15 +79,19 @@
* System.out.println(newUser.getAge()); // Output: 30
* }
* }
- * }
- *
+ * }
*
* @author zihluwang
- * @version 1.7.0
- * @since 1.0.0
+ * @version 3.0.0
*/
public final class MapUtil {
+ /**
+ * Private constructor to prevent instantiation of this utility class.
+ */
+ private MapUtil() {
+ }
+
/**
* Converts an object to a map by mapping the field names to their corresponding values.
*
@@ -106,10 +116,4 @@ public static Example usage:
- *
- * {@code
+ * {@code
* public class User {
* private String name;
* private int age;
@@ -54,13 +58,11 @@
* return user;
* }
* }
- * }
- *
+ * }
*
* @param * If {@code start} is less than {@code end}, an ascending range (exclusive of {@code end}) - * is generated. If {@code start} is greater than {@code end}, a descending range (exclusive of {@code end}) - * is generated. If {@code start} equals {@code end}, an empty stream is returned. + * is generated. If {@code start} is greater than {@code end}, a descending range (exclusive + * of {@code end}) is generated. If {@code start} equals {@code end}, an empty stream + * is returned. *
* Example Usage: *
{@code
@@ -103,7 +110,8 @@ public static IntStream range(int end) {
*
* @param start the starting value of the range (inclusive)
* @param end upper-bound of the range (exclusive)
- * @return an {@code IntStream} of integers in ascending or descending order, exclusive of {@code end}
+ * @return an {@code IntStream} of integers in ascending or descending order, exclusive
+ * of {@code end}
* @see IntStream
*/
public static IntStream range(int start, int end) {
@@ -114,7 +122,7 @@ public static IntStream range(int start, int end) {
return IntStream.range(start, end);
} else {
// Descending range (exclusive of end)
- return IntStream.iterate(start, n -> n > end, n -> n - 1);
+ return IntStream.iterate(start, (n) -> n > end, (n) -> n - 1);
}
}
@@ -150,8 +158,8 @@ public static IntStream rangeClosed(int start, int end) {
}
/**
- * Generates a stream of integers starting from the specified {@code start} value, incremented by
- * the specified {@code step}, up to the specified {@code end} value.
+ * Generates a stream of integers starting from the specified {@code start} value, incremented
+ * by the specified {@code step}, up to the specified {@code end} value.
*
* It creates a sequential, ordered {@code IntStream} that can be used for iteration or
* further processing.
@@ -180,9 +188,10 @@ public static IntStream rangeClosed(int start, int end) {
* @param start the starting value of the range (inclusive)
* @param end upper-bound of the range (exclusive)
* @param step the increment or decrement between each value (non-zero)
- * @return an {@code IntStream} of integers from {@code start} to {@code end} exclusive stepping by {@code step}
- * @throws IllegalArgumentException if {@code step} is zero or if {@code start} and {@code end} are inconsistent
- * with the direction imposed by {@code step}
+ * @return an {@code IntStream} of integers from {@code start} to {@code end} exclusive stepping
+ * by {@code step}
+ * @throws IllegalArgumentException if {@code step} is zero or if {@code start} and {@code end}
+ * are inconsistent with the direction imposed by {@code step}
* @see IntStream
*/
public static IntStream range(int start, int end, int step) {
diff --git a/common-toolbox/src/main/resources/logback.xml b/common-toolbox/src/main/resources/logback.xml
new file mode 100644
index 0000000..288ac4a
--- /dev/null
+++ b/common-toolbox/src/main/resources/logback.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+ ${COLOURFUL_OUTPUT}
+
+
+
+
+
+
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/AesUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/AesUtilTest.java
similarity index 98%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/AesUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/AesUtilTest.java
index c8390d1..2e69401 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/AesUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/AesUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/Base64UtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/Base64UtilTest.java
similarity index 98%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/Base64UtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/Base64UtilTest.java
index e044098..732b4c1 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/Base64UtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/Base64UtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/BoolUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/BoolUtilTest.java
similarity index 99%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/BoolUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/BoolUtilTest.java
index 23d38de..f6302b5 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/BoolUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/BoolUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/BranchUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/BranchUtilTest.java
similarity index 99%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/BranchUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/BranchUtilTest.java
index 05a2f14..f90f058 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/BranchUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/BranchUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/CollectionUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/CollectionUtilTest.java
similarity index 99%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/CollectionUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/CollectionUtilTest.java
index 4c7f197..7807753 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/CollectionUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/CollectionUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/HashUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/HashUtilTest.java
similarity index 99%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/HashUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/HashUtilTest.java
index 6b9cb6b..9bb1fef 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/HashUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/HashUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/RangeUtilTest.java b/common-toolbox/src/test/java/com/onixbyte/common/util/RangeUtilTest.java
similarity index 99%
rename from devkit-utils/src/test/java/com/onixbyte/devkit/utils/RangeUtilTest.java
rename to common-toolbox/src/test/java/com/onixbyte/common/util/RangeUtilTest.java
index 13db7fb..a53ed6d 100644
--- a/devkit-utils/src/test/java/com/onixbyte/devkit/utils/RangeUtilTest.java
+++ b/common-toolbox/src/test/java/com/onixbyte/common/util/RangeUtilTest.java
@@ -15,7 +15,7 @@
* limitations under the License.
*/
-package com.onixbyte.devkit.utils;
+package com.onixbyte.common.util;
import org.junit.jupiter.api.Test;
diff --git a/key-pair-loader/README.md b/crypto-toolbox/README.md
similarity index 97%
rename from key-pair-loader/README.md
rename to crypto-toolbox/README.md
index 3d32826..8e287e8 100644
--- a/key-pair-loader/README.md
+++ b/crypto-toolbox/README.md
@@ -1,6 +1,6 @@
-# KeyLoader
+# Crypto Toolbox
-KeyLoader provides utility methods to load keys from pem-formatted key texts.
+Crypto Toolbox provides methods to simplify your codes on key pairs.
## ECDSA-based algorithm
@@ -110,4 +110,4 @@ pzDq72a2Rhws+dbrH0gqsg1lsLDfhhui2FomuBpDZUtHq0Jz/IEvd3X45XvegSH8
t8+yL/pFK3+YpDVtj/IzMSwL+izvnXFALvZOO+8CABeyKuSjLh/6LbAzrvoftql5
gQIDAQAB
-----END PUBLIC KEY-----
-```
\ No newline at end of file
+```
diff --git a/key-pair-loader/build.gradle.kts b/crypto-toolbox/build.gradle.kts
similarity index 69%
rename from key-pair-loader/build.gradle.kts
rename to crypto-toolbox/build.gradle.kts
index 0ecec51..81139e1 100644
--- a/key-pair-loader/build.gradle.kts
+++ b/crypto-toolbox/build.gradle.kts
@@ -1,19 +1,25 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
+
import java.net.URI
plugins {
@@ -68,9 +74,9 @@ tasks.test {
publishing {
publications {
- create("keyPairLoader") {
+ create("cryptoToolbox") {
groupId = group.toString()
- artifactId = "key-pair-loader"
+ artifactId = "crypto-toolbox"
version = artefactVersion
pom {
@@ -112,7 +118,7 @@ publishing {
from(components["java"])
signing {
- sign(publishing.publications["keyPairLoader"])
+ sign(publishing.publications["cryptoToolbox"])
}
}
diff --git a/crypto-toolbox/src/main/java/com/onixbyte/crypto/PrivateKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/PrivateKeyLoader.java
new file mode 100644
index 0000000..9f3f8c7
--- /dev/null
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/PrivateKeyLoader.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.crypto;
+
+import java.security.PrivateKey;
+
+/**
+ * The {@code PrivateKeyLoader} provides utility methods for loading private keys from
+ * PEM-formatted key text.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ */
+public interface PrivateKeyLoader {
+
+ /**
+ * Load private key from pem-formatted key text.
+ *
+ * @param pemKeyText pem-formatted key text
+ * @return loaded private key
+ */
+ PrivateKey loadPrivateKey(String pemKeyText);
+}
diff --git a/crypto-toolbox/src/main/java/com/onixbyte/crypto/PublicKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/PublicKeyLoader.java
new file mode 100644
index 0000000..943afcc
--- /dev/null
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/PublicKeyLoader.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.crypto;
+
+import com.onixbyte.crypto.exception.KeyLoadingException;
+
+import java.security.PublicKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPublicKey;
+
+/**
+ * The {@code PublicKeyLoader} provides utility methods for loading public keys from PEM-formatted
+ * key text.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ */
+public interface PublicKeyLoader {
+
+ /**
+ * Load public key from PEM-formatted key text.
+ *
+ * @param pemKeyText PEM-formatted key text
+ * @return loaded private key
+ */
+ PublicKey loadPublicKey(String pemKeyText);
+
+ /**
+ * Loads an EC public key using the provided x and y coordinates together with the curve name.
+ *
+ * This default implementation throws a {@link KeyLoadingException} to signify that this key
+ * loader does not support loading an EC public key. Implementing classes are expected to
+ * override this method to supply their own loading logic.
+ *
+ * @param xHex the hexadecimal string representing the x coordinate of the EC point
+ * @param yHex the hexadecimal string representing the y coordinate of the EC point
+ * @param curveName the name of the elliptic curve
+ * @return the loaded {@link ECPublicKey} instance
+ * @throws KeyLoadingException if loading is not supported or fails
+ */
+ default ECPublicKey loadPublicKey(String xHex, String yHex, String curveName) {
+ throw new KeyLoadingException("This key loader does not support loading an EC public key.");
+ }
+
+ /**
+ * Loads an RSA public key using the provided modulus and exponent.
+ *
+ * This default implementation throws a {@link KeyLoadingException} to signify that this key
+ * loader does not support loading an RSA public key. Implementing classes are expected to
+ * override this method to supply their own loading logic.
+ *
+ * @param modulus the modulus value of the RSA public key, usually represented in hexadecimal
+ * or Base64 string format
+ * @param exponent the public exponent value of the RSA public key, usually represented in
+ * hexadecimal or Base64 string format
+ * @return the loaded {@link RSAPublicKey} instance
+ * @throws KeyLoadingException if loading is not supported or fails
+ */
+ default RSAPublicKey loadPublicKey(String modulus, String exponent) {
+ throw new KeyLoadingException("This key loader does not support loading an RSA public key.");
+ }
+}
diff --git a/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPrivateKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPrivateKeyLoader.java
new file mode 100644
index 0000000..99adf89
--- /dev/null
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPrivateKeyLoader.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.crypto.algorithm.ecdsa;
+
+import com.onixbyte.crypto.PrivateKeyLoader;
+import com.onixbyte.crypto.exception.KeyLoadingException;
+import com.onixbyte.crypto.util.CryptoUtil;
+
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.interfaces.ECPrivateKey;
+import java.security.spec.*;
+import java.util.Base64;
+
+/**
+ * A class responsible for loading private ECDSA keys from PEM formatted text.
+ *
+ * This class implements the {@link PrivateKeyLoader} interface and provides methods to load private
+ * RSA keys. The keys are expected to be in the standard PEM format, which includes Base64-encoded
+ * key content surrounded by header and footer lines. The class handles the decoding of Base64
+ * content and the generation of keys using the RSA key factory.
+ *
+ * Any exceptions encountered during the loading process are encapsulated in a
+ * {@link KeyLoadingException}, allowing for flexible error handling.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ * @see PrivateKeyLoader
+ * @see KeyLoadingException
+ */
+public class ECPrivateKeyLoader implements PrivateKeyLoader {
+
+ private final KeyFactory keyFactory;
+
+ private final Base64.Decoder decoder;
+
+ /**
+ * Initialise a key loader for EC-based algorithms.
+ */
+ public ECPrivateKeyLoader() {
+ 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 {
+ pemKeyText = CryptoUtil.getRawContent(pemKeyText);
+ 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);
+ }
+ }
+}
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/impl/ECKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPublicKeyLoader.java
similarity index 63%
rename from key-pair-loader/src/main/java/com/onixbyte/security/impl/ECKeyLoader.java
rename to crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPublicKeyLoader.java
index e482c0f..e3e0ef3 100644
--- a/key-pair-loader/src/main/java/com/onixbyte/security/impl/ECKeyLoader.java
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/ecdsa/ECPublicKeyLoader.java
@@ -1,24 +1,31 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.security.impl;
+package com.onixbyte.crypto.algorithm.ecdsa;
-import com.onixbyte.security.KeyLoader;
-import com.onixbyte.security.exception.KeyLoadingException;
+import com.onixbyte.crypto.PrivateKeyLoader;
+import com.onixbyte.crypto.PublicKeyLoader;
+import com.onixbyte.crypto.exception.KeyLoadingException;
+import com.onixbyte.crypto.util.CryptoUtil;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
@@ -32,46 +39,39 @@
import java.util.Set;
/**
- * Key pair loader for loading key pairs for ECDSA-based algorithms.
+ * A class responsible for loading public ECDSA keys from PEM formatted text.
*
- *
- * 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);
- * }
+ * This class implements the {@link PublicKeyLoader} interface and provides methods to load private
+ * RSA keys. The keys are expected to be in the standard PEM format, which includes Base64-encoded
+ * key content surrounded by header and footer lines. The class handles the decoding of Base64
+ * content and the generation of keys using the RSA key factory.
+ *
+ * Any exceptions encountered during the loading process are encapsulated in a
+ * {@link KeyLoadingException}, allowing for flexible error handling.
*
* @author zihluwang
- * @version 2.0.0
- * @since 2.0.0
+ * @author siujamo
+ * @version 3.0.0
+ * @see PrivateKeyLoader
+ * @see KeyLoadingException
*/
-public class ECKeyLoader implements KeyLoader {
-
- private final KeyFactory keyFactory;
-
- private final Base64.Decoder decoder;
+public class ECPublicKeyLoader implements PublicKeyLoader {
/**
* Supported curves.
*/
public static final Set SUPPORTED_CURVES = new HashSet<>(Set.of(
- "secp256r1", "secp384r1", "secp521r1", "secp224r1"
+ "secp256r1", "secp384r1", "secp521r1", "secp224r1"
));
+ private final KeyFactory keyFactory;
+
+ private final Base64.Decoder decoder;
+
/**
* Initialise a key loader for EC-based algorithms.
*/
- public ECKeyLoader() {
+ public ECPublicKeyLoader() {
try {
this.keyFactory = KeyFactory.getInstance("EC");
this.decoder = Base64.getDecoder();
@@ -80,32 +80,6 @@ public ECKeyLoader() {
}
}
- /**
- * 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 {
- pemKeyText = getRawContent(pemKeyText);
- 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.
*
@@ -117,7 +91,7 @@ public ECPrivateKey loadPrivateKey(String pemKeyText) {
@Override
public ECPublicKey loadPublicKey(String pemKeyText) {
try {
- pemKeyText = getRawContent(pemKeyText);
+ pemKeyText = CryptoUtil.getRawContent(pemKeyText);
var keyBytes = decoder.decode(pemKeyText);
var spec = new X509EncodedKeySpec(keyBytes);
var key = keyFactory.generatePublic(spec);
diff --git a/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPrivateKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPrivateKeyLoader.java
new file mode 100644
index 0000000..0d9f475
--- /dev/null
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPrivateKeyLoader.java
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.crypto.algorithm.rsa;
+
+import com.onixbyte.crypto.PrivateKeyLoader;
+import com.onixbyte.crypto.exception.KeyLoadingException;
+import com.onixbyte.crypto.util.CryptoUtil;
+
+import java.math.BigInteger;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.*;
+import java.util.Base64;
+
+/**
+ * A class responsible for loading private RSA keys from PEM formatted text.
+ *
+ * This class implements the {@link PrivateKeyLoader} interface and provides methods to load private
+ * RSA keys. The keys are expected to be in the standard PEM format, which includes Base64-encoded
+ * key content surrounded by header and footer lines. The class handles the decoding of Base64
+ * content and the generation of keys using the RSA key factory.
+ *
+ * Any exceptions encountered during the loading process are encapsulated in a
+ * {@link KeyLoadingException}, allowing for flexible error handling.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ * @see PrivateKeyLoader
+ * @see KeyLoadingException
+ */
+public class RSAPrivateKeyLoader implements PrivateKeyLoader {
+
+ private final Base64.Decoder decoder;
+
+ private final KeyFactory keyFactory;
+
+ /**
+ * Constructs an instance of {@code RsaKeyLoader}.
+ *
+ * This constructor initialises the Base64 decoder and the RSA {@link KeyFactory}. It may throw
+ * a {@link KeyLoadingException} if the RSA algorithm is not available.
+ */
+ public RSAPrivateKeyLoader() {
+ try {
+ this.decoder = Base64.getDecoder();
+ this.keyFactory = KeyFactory.getInstance("RSA");
+ } catch (NoSuchAlgorithmException e) {
+ throw new KeyLoadingException(e);
+ }
+ }
+
+ /**
+ * Loads an RSA private key from a given PEM formatted key text.
+ *
+ * This method extracts the raw key content from the provided PEM text, decodes the
+ * Base64-encoded content, and generates an instance of {@link RSAPrivateKey}. If the key cannot
+ * be loaded due to invalid specifications or types, a {@link KeyLoadingException} is thrown.
+ *
+ * @param pemKeyText the PEM formatted private key text
+ * @return an instance of {@link RSAPrivateKey}
+ * @throws KeyLoadingException if the key loading process encounters an error
+ */
+ @Override
+ public RSAPrivateKey loadPrivateKey(String pemKeyText) {
+ // Extract the raw key content
+ var rawKeyContent = CryptoUtil.getRawContent(pemKeyText);
+
+ // Decode the Base64-encoded content
+ var keyBytes = decoder.decode(rawKeyContent);
+
+ // Create a PKCS8EncodedKeySpec from the decoded bytes
+ var keySpec = new PKCS8EncodedKeySpec(keyBytes);
+
+ try {
+ // Get an RSA KeyFactory and generate the private key
+ var _key = keyFactory.generatePrivate(keySpec);
+ if (_key instanceof RSAPrivateKey key) {
+ return key;
+ } 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);
+ }
+ }
+}
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/impl/RSAKeyLoader.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPublicKeyLoader.java
similarity index 56%
rename from key-pair-loader/src/main/java/com/onixbyte/security/impl/RSAKeyLoader.java
rename to crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPublicKeyLoader.java
index 3cf9324..c1a8810 100644
--- a/key-pair-loader/src/main/java/com/onixbyte/security/impl/RSAKeyLoader.java
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/algorithm/rsa/RSAPublicKeyLoader.java
@@ -1,49 +1,60 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.security.impl;
+package com.onixbyte.crypto.algorithm.rsa;
-import com.onixbyte.security.KeyLoader;
-import com.onixbyte.security.exception.KeyLoadingException;
+import com.onixbyte.crypto.PrivateKeyLoader;
+import com.onixbyte.crypto.PublicKeyLoader;
+import com.onixbyte.crypto.exception.KeyLoadingException;
+import com.onixbyte.crypto.util.CryptoUtil;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
-import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
-import java.security.spec.*;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.KeySpec;
+import java.security.spec.RSAPublicKeySpec;
+import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
- * A class responsible for loading RSA keys from PEM formatted text.
+ * A class responsible for loading public RSA keys from PEM formatted text.
*
- * This class implements the {@link KeyLoader} interface and provides methods to load both private
- * and public RSA keys. The keys are expected to be in the standard PEM format, which includes
- * Base64-encoded key content surrounded by header and footer lines. The class handles the decoding
- * of Base64 content and the generation of keys using the RSA key factory.
+ * This class implements the {@link PublicKeyLoader} interface and provides methods to load public
+ * RSA keys. The keys are expected to be in the standard PEM format, which includes Base64-encoded
+ * key content surrounded by header and footer lines. The class handles the decoding of Base64
+ * content and the generation of keys using the RSA key factory.
*
* Any exceptions encountered during the loading process are encapsulated in a
* {@link KeyLoadingException}, allowing for flexible error handling.
*
+ * @author zihluwang
* @author siujamo
- * @see KeyLoader
+ * @version 3.0.0
+ * @see PrivateKeyLoader
* @see KeyLoadingException
*/
-public class RSAKeyLoader implements KeyLoader {
+public class RSAPublicKeyLoader implements PublicKeyLoader {
private final Base64.Decoder decoder;
@@ -57,7 +68,7 @@ public class RSAKeyLoader implements KeyLoader {
* This constructor initialises the Base64 decoder and the RSA {@link KeyFactory}. It may throw
* a {@link KeyLoadingException} if the RSA algorithm is not available.
*/
- public RSAKeyLoader() {
+ public RSAPublicKeyLoader() {
try {
this.decoder = Base64.getDecoder();
this.urlDecoder = Base64.getUrlDecoder();
@@ -67,41 +78,6 @@ public RSAKeyLoader() {
}
}
- /**
- * Loads an RSA private key from a given PEM formatted key text.
- *
- * This method extracts the raw key content from the provided PEM text, decodes the
- * Base64-encoded content, and generates an instance of {@link RSAPrivateKey}. If the key cannot
- * be loaded due to invalid specifications or types, a {@link KeyLoadingException} is thrown.
- *
- * @param pemKeyText the PEM formatted private key text
- * @return an instance of {@link RSAPrivateKey}
- * @throws KeyLoadingException if the key loading process encounters an error
- */
- @Override
- public RSAPrivateKey loadPrivateKey(String pemKeyText) {
- // Extract the raw key content
- var rawKeyContent = getRawContent(pemKeyText);
-
- // Decode the Base64-encoded content
- var keyBytes = decoder.decode(rawKeyContent);
-
- // Create a PKCS8EncodedKeySpec from the decoded bytes
- var keySpec = new PKCS8EncodedKeySpec(keyBytes);
-
- try {
- // Get an RSA KeyFactory and generate the private key
- var _key = keyFactory.generatePrivate(keySpec);
- if (_key instanceof RSAPrivateKey key) {
- return key;
- } 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);
- }
- }
-
/**
* Loads an RSA public key from a given PEM formatted key text.
*
@@ -116,7 +92,7 @@ public RSAPrivateKey loadPrivateKey(String pemKeyText) {
@Override
public RSAPublicKey loadPublicKey(String pemKeyText) {
// Extract the raw key content
- var rawKeyContent = getRawContent(pemKeyText);
+ var rawKeyContent = CryptoUtil.getRawContent(pemKeyText);
// Decode the Base64-encoded content
var keyBytes = decoder.decode(rawKeyContent);
diff --git a/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/exception/KeyLoadingException.java
similarity index 66%
rename from key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java
rename to crypto-toolbox/src/main/java/com/onixbyte/crypto/exception/KeyLoadingException.java
index 3c4cabc..648182c 100644
--- a/key-pair-loader/src/main/java/com/onixbyte/security/exception/KeyLoadingException.java
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/exception/KeyLoadingException.java
@@ -1,21 +1,26 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.security.exception;
+package com.onixbyte.crypto.exception;
/**
* The {@code KeyLoadingException} class represents an exception that is thrown when there is an
@@ -29,7 +34,7 @@
*
Example usage:
* {@code
* try {
- * KeyLoader keyLoader = new EcKeyLoader();
+ * PrivateKeyLoader keyLoader = new ECPrivateKeyLoader();
* ECPrivateKey privateKey = keyLoader.loadPrivateKey(pemPrivateKey);
* } catch (KeyLoadingException e) {
* // Handle the exception
@@ -38,8 +43,7 @@
* }
*
* @author zihluwang
- * @version 2.0.0
- * @since 1.6.0
+ * @version 3.0.0
*/
public class KeyLoadingException extends RuntimeException {
diff --git a/crypto-toolbox/src/main/java/com/onixbyte/crypto/util/CryptoUtil.java b/crypto-toolbox/src/main/java/com/onixbyte/crypto/util/CryptoUtil.java
new file mode 100644
index 0000000..9951af5
--- /dev/null
+++ b/crypto-toolbox/src/main/java/com/onixbyte/crypto/util/CryptoUtil.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.crypto.util;
+
+/**
+ * Utility class for cryptographic operations.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ */
+public final class CryptoUtil {
+
+ /**
+ * Private constructor to prevent instantiation of this utility class.
+ */
+ private CryptoUtil() {
+ }
+
+ /**
+ * Extracts the raw content from a PEM-formatted key by removing any headers, footers,
+ * and newline characters.
+ *
+ *
+ * This method processes the given PEM key text and returns a cleaned string containing only
+ * the key material. It removes the lines matching the
+ * {@code "-----BEGIN (EC )?(RSA )?(PRIVATE|PUBLIC) KEY-----"} and
+ * {@code "-----END (EC )?(RSA )?(PRIVATE|PUBLIC) KEY-----"} patterns,
+ * as well as any newline characters,
+ * resulting in a continuous string that can be used directly for cryptographic operations.
+ *
+ * @param pemKeyText the PEM-formatted key as a string, which may include headers, footers,
+ * and line breaks
+ * @return a string containing the raw key content without any unnecessary formatting or whitespace
+ */
+ public static String getRawContent(String pemKeyText) {
+ return pemKeyText
+ .replaceAll("-----BEGIN ((EC )|(RSA ))?(PRIVATE|PUBLIC) KEY-----", "")
+ .replaceAll("-----END ((EC )|(RSA ))?(PRIVATE|PUBLIC) KEY-----", "")
+ .replaceAll("\n", "");
+ }
+}
diff --git a/crypto-toolbox/src/main/resources/logback.xml b/crypto-toolbox/src/main/resources/logback.xml
new file mode 100644
index 0000000..288ac4a
--- /dev/null
+++ b/crypto-toolbox/src/main/resources/logback.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+ ${COLOURFUL_OUTPUT}
+
+
+
+
+
+
diff --git a/key-pair-loader/src/test/resources/ec_private_key.pem b/crypto-toolbox/src/test/resources/ec_private_key.pem
similarity index 100%
rename from key-pair-loader/src/test/resources/ec_private_key.pem
rename to crypto-toolbox/src/test/resources/ec_private_key.pem
diff --git a/key-pair-loader/src/test/resources/ec_public_key.pem b/crypto-toolbox/src/test/resources/ec_public_key.pem
similarity index 100%
rename from key-pair-loader/src/test/resources/ec_public_key.pem
rename to crypto-toolbox/src/test/resources/ec_public_key.pem
diff --git a/key-pair-loader/src/test/resources/rsa_private_key.pem b/crypto-toolbox/src/test/resources/rsa_private_key.pem
similarity index 100%
rename from key-pair-loader/src/test/resources/rsa_private_key.pem
rename to crypto-toolbox/src/test/resources/rsa_private_key.pem
diff --git a/key-pair-loader/src/test/resources/rsa_public_key.pem b/crypto-toolbox/src/test/resources/rsa_public_key.pem
similarity index 100%
rename from key-pair-loader/src/test/resources/rsa_public_key.pem
rename to crypto-toolbox/src/test/resources/rsa_public_key.pem
diff --git a/devkit-bom/README.md b/devkit-bom/README.md
deleted file mode 100644
index 5cfbbb6..0000000
--- a/devkit-bom/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# DevKit BOM
-
-The devkit-bom (Bill of Materials) is a Maven POM file provided by OnixByte to manage dependency versions for the DevKit suite of libraries. By incorporating this BOM into your build configuration, you can ensure consistent versioning across all included dependencies without needing to specify versions explicitly in your project files. Published with Gradle metadata, this BOM supports both Maven and Gradle projects, and this document outlines how to integrate and use it effectively in both ecosystems.
-
-## Using in Maven
-
-Add the `devkit-bom` to your `pom.xml` under ``:
-
-```xml
-
-
-
- com.onixbyte
- devkit-bom
- ${devkit-version}
- pom
- import
-
-
-
-```
-
-Then reference dependencies like `devkit-core` without a version.
-
-## Using in Gradle
-
-In your `build.gradle[.kts]`, apply the BOM using the `platform` dependency:
-
-```groovy
-dependencies {
- implementation platform('com.onixbyte:devkit-bom:2.0.0')
- implementation 'com.onixbyte:devkit-core'
- implementation 'com.onixbyte:devkit-utils'
-}
-```
-
-If you are using Kotlin DSL:
-
-```kotlin
-dependencies {
- implementation(platform("com.onixbyte:devkit-bom:2.0.0"))
- implementation("com.onixbyte:devkit-core")
- implementation("com.onixbyte:devkit-utils")
-}
-```
-
diff --git a/devkit-utils/src/main/resources/logback.xml b/devkit-utils/src/main/resources/logback.xml
deleted file mode 100644
index 56cd5b7..0000000
--- a/devkit-utils/src/main/resources/logback.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ${COLOURFUL_OUTPUT}
-
-
-
-
-
-
\ No newline at end of file
diff --git a/gradle.properties b/gradle.properties
index 29c0ce1..00e3c6a 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -1,22 +1,27 @@
#
-# Copyright (C) 2024-2025 OnixByte.
+# 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
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
#
-# http://www.apache.org/licenses/LICENSE-2.0
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
#
-# 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.
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
#
-artefactVersion=2.4.0
+artefactVersion=3.0.0
projectUrl=https://onixbyte.com/projects/onixbyte-toolbox
projectGithubUrl=https://github.com/onixbyte/onixbyte-toolbox
-licenseName=The Apache License, Version 2.0
+licenseName=MIT
licenseUrl=https://onixbyte.com/projects/onixbyte-toolbox/LICENSE.txt
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index d64cd49..e69de29 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradlew b/gradlew
index 1aa94a4..447618b 100755
--- a/gradlew
+++ b/gradlew
@@ -1,19 +1,25 @@
#!/bin/sh
#
-# Copyright © 2015-2021 the original authors.
-#
-# 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
-#
-# https://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.
+# Copyright (c) 2024-2025 OnixByte
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
#
##############################################################################
diff --git a/gradlew.bat b/gradlew.bat
index 25da30d..e2b0bab 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -1,17 +1,23 @@
@rem
-@rem Copyright 2015 the original author or authors.
+@rem Copyright (c) 2024-2025 OnixByte
@rem
-@rem Licensed under the Apache License, Version 2.0 (the "License");
-@rem you may not use this file except in compliance with the License.
-@rem You may obtain a copy of the License at
+@rem Permission is hereby granted, free of charge, to any person obtaining a copy
+@rem of this software and associated documentation files (the "Software"), to deal
+@rem in the Software without restriction, including without limitation the rights
+@rem to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+@rem copies of the Software, and to permit persons to whom the Software is
+@rem furnished to do so, subject to the following conditions:
@rem
-@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem The above copyright notice and this permission notice shall be included in all
+@rem copies or substantial portions of the Software.
@rem
-@rem Unless required by applicable law or agreed to in writing, software
-@rem distributed under the License is distributed on an "AS IS" BASIS,
-@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-@rem See the License for the specific language governing permissions and
-@rem limitations under the License.
+@rem THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+@rem IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+@rem FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+@rem AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+@rem LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+@rem OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+@rem SOFTWARE.
@rem
@if "%DEBUG%"=="" @echo off
diff --git a/guid/src/main/java/com/onixbyte/guid/GuidCreator.java b/guid/src/main/java/com/onixbyte/guid/GuidCreator.java
deleted file mode 100644
index 266c85f..0000000
--- a/guid/src/main/java/com/onixbyte/guid/GuidCreator.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.guid;
-
-/**
- * The {@code GuidCreator} is a generic interface for generating globally unique identifiers (GUIDs)
- * of a specific type.
- *
- * The type of ID is determined by the class implementing this interface.
- *
- *
- * Example usage:
- * {@code
- * public class StringGuidCreator implements GuidCreator {
- * private final AtomicLong counter = new AtomicLong();
- *
- * @Override
- * public String nextId() {
- * return UUID.randomUUID().toString() + "-" + counter.incrementAndGet();
- * }
- * }
- *
- * public class Example {
- * public static void main(String[] args) {
- * GuidCreator guidCreator = new StringGuidCreator();
- * String guid = guidCreator.nextId();
- * System.out.println("Generated GUID: " + guid);
- * }
- * }
- * }
- *
- * @param this represents the type of the Global Unique Identifier
- * @author Zihlu Wang
- * @version 1.1.0
- * @since 1.0.0
- */
-public interface GuidCreator {
-
- /**
- * Generates and returns the next globally unique ID.
- *
- * @return the next globally unique ID
- */
- IdType nextId();
-
-}
\ No newline at end of file
diff --git a/guid/src/main/java/com/onixbyte/guid/impl/SequentialUuidCreator.java b/guid/src/main/java/com/onixbyte/guid/impl/SequentialUuidCreator.java
deleted file mode 100644
index 88b35f3..0000000
--- a/guid/src/main/java/com/onixbyte/guid/impl/SequentialUuidCreator.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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.guid.impl;
-
-import com.onixbyte.guid.GuidCreator;
-
-import java.nio.ByteBuffer;
-import java.security.SecureRandom;
-import java.util.UUID;
-
-/**
- * A {@code SequentialUuidCreator} is responsible for generating UUIDs following the UUID version 7 specification, which
- * combines a timestamp with random bytes to create time-ordered unique identifiers.
- *
- * This implementation utilises a cryptographically strong {@link SecureRandom} instance to produce the random
- * component of the UUID. The first 6 bytes of the UUID encode the current timestamp in milliseconds, ensuring that
- * generated UUIDs are roughly ordered by creation time.
- *
- * The generated UUID adheres strictly to the layout and variant bits of UUID version 7 as defined in the specification.
- *
- */
-public class SequentialUuidCreator implements GuidCreator {
-
- private final SecureRandom random;
-
- /**
- * Constructs a new {@code SequentialUuidCreator} with its own {@link SecureRandom} instance.
- */
- public SequentialUuidCreator() {
- this.random = new SecureRandom();
- }
-
- /**
- * Generates and returns the next UUID version 7 identifier.
- *
- * @return a {@link UUID} instance representing a unique, time-ordered identifier
- */
- @Override
- public UUID nextId() {
- var value = randomBytes();
- var buf = ByteBuffer.wrap(value);
- var high = buf.getLong();
- var low = buf.getLong();
- return new UUID(high, low);
- }
-
- /**
- * Produces a byte array representation of a UUID version 7,
- * combining the current timestamp with random bytes.
- *
- * @return a 16-byte array conforming to UUIDv7 layout and variant bits
- */
- private byte[] randomBytes() {
- var value = new byte[16];
- random.nextBytes(value);
-
- var timestamp = ByteBuffer.allocate(Long.BYTES);
- timestamp.putLong(System.currentTimeMillis());
-
- System.arraycopy(timestamp.array(), 2, value, 0, 6);
-
- // Set version to 7 (UUIDv7)
- value[6] = (byte) ((value[6] & 0x0F) | 0x70);
-
- // Set variant bits as per RFC 4122
- value[8] = (byte) ((value[8] & 0x3F) | 0x80);
-
- return value;
- }
-}
diff --git a/guid/src/main/resources/logback.xml b/guid/src/main/resources/logback.xml
deleted file mode 100644
index 7beaa9d..0000000
--- a/guid/src/main/resources/logback.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
- ${COLOURFUL_OUTPUT}
-
-
-
-
-
-
\ No newline at end of file
diff --git a/guid/README.md b/identity-generator/README.md
similarity index 96%
rename from guid/README.md
rename to identity-generator/README.md
index 501a1f5..d77c49d 100644
--- a/guid/README.md
+++ b/identity-generator/README.md
@@ -4,7 +4,7 @@
Module `guid` serves as a guid creator for other `JDevKit` modules. You can also use this module as a guid creator standards.
-We have already implemented `SnowflakeGuidCreator`, you can also implement a custom guid creations by implementing `com.onixbyte.guid.GuidCreator`.
+We have already implemented `SnowflakeGuidCreator`, you can also implement a custom guid creations by implementing `com.onixbyte.identitygenerator.IdentityGenerator`.
## Example usage
diff --git a/guid/build.gradle.kts b/identity-generator/build.gradle.kts
similarity index 64%
rename from guid/build.gradle.kts
rename to identity-generator/build.gradle.kts
index 6f357b2..d3c7471 100644
--- a/guid/build.gradle.kts
+++ b/identity-generator/build.gradle.kts
@@ -1,19 +1,25 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
+
import java.net.URI
plugins {
@@ -64,9 +70,9 @@ tasks.test {
publishing {
publications {
- create("guid") {
+ create("identityGenerator") {
groupId = group.toString()
- artifactId = "guid"
+ artifactId = "identity-generator"
version = artefactVersion
pom {
@@ -82,8 +88,8 @@ publishing {
}
scm {
- connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
- developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
+ connection = "scm:git:git://github.com:OnixByte/JDevKit.git"
+ developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git"
url = projectGithubUrl
}
@@ -107,7 +113,7 @@ publishing {
from(components["java"])
signing {
- sign(publishing.publications["guid"])
+ sign(publishing.publications["identityGenerator"])
}
}
diff --git a/identity-generator/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java b/identity-generator/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java
new file mode 100644
index 0000000..2232c43
--- /dev/null
+++ b/identity-generator/src/main/java/com/onixbyte/identitygenerator/IdentityGenerator.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.identitygenerator;
+
+/**
+ * The {@code IdentityGenerator} is a generic interface for generating globally unique identifiers
+ * (GUIDs) of a specific type.
+ *
+ * The type of ID is determined by the class implementing this interface.
+ *
+ *
+ * Example usage:
+ * {@code
+ * public class StringGuidCreator implements IdentityGenerator {
+ * private final AtomicLong counter = new AtomicLong();
+ *
+ * @Override
+ * public String nextId() {
+ * return UUID.randomUUID().toString() + "-" + counter.incrementAndGet();
+ * }
+ * }
+ *
+ * public class Example {
+ * public static void main(String[] args) {
+ * IdentityGenerator guidCreator = new StringGuidCreator();
+ * String guid = guidCreator.nextId();
+ * System.out.println("Generated GUID: " + guid);
+ * }
+ * }
+ * }
+ *
+ * @param this represents the type of the Global Unique Identifier
+ * @author zihluwang
+ * @version 3.0.0
+ */
+public interface IdentityGenerator {
+
+ /**
+ * Generates and returns the next globally unique ID.
+ *
+ * @return the next globally unique ID
+ */
+ IdType nextId();
+
+}
diff --git a/guid/src/main/java/com/onixbyte/guid/exceptions/TimingException.java b/identity-generator/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java
similarity index 55%
rename from guid/src/main/java/com/onixbyte/guid/exceptions/TimingException.java
rename to identity-generator/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java
index 611e5fb..4746a04 100644
--- a/guid/src/main/java/com/onixbyte/guid/exceptions/TimingException.java
+++ b/identity-generator/src/main/java/com/onixbyte/identitygenerator/exceptions/TimingException.java
@@ -1,21 +1,26 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.guid.exceptions;
+package com.onixbyte.identitygenerator.exceptions;
/**
* The {@code TimingException} class represents an exception that is thrown when there is an error
@@ -25,8 +30,8 @@
* provides a description of the exception, while the cause represents the underlying cause of the
* exception and provides additional information about the error.
*
- * @author Zihlu Wang
- * @since 1.0.0
+ * @author zihluwang
+ * @since 3.0.0
*/
public class TimingException extends RuntimeException {
diff --git a/identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java b/identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java
new file mode 100644
index 0000000..48efd8f
--- /dev/null
+++ b/identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SequentialUuidGenerator.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2024-2025 OnixByte
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.onixbyte.identitygenerator.impl;
+
+import com.onixbyte.identitygenerator.IdentityGenerator;
+
+import java.nio.ByteBuffer;
+import java.security.SecureRandom;
+import java.util.UUID;
+
+/**
+ * A {@code SequentialUuidGenerator} is responsible for generating UUIDs following the
+ * UUID version 7 specification, which combines a timestamp with random bytes to create time-ordered
+ * unique identifiers.
+ *
+ * This implementation utilises a cryptographically strong {@link SecureRandom} instance to produce
+ * the random component of the UUID. The first 6 bytes of the UUID encode the current timestamp in
+ * milliseconds, ensuring that generated UUIDs are roughly ordered by creation time.
+ *
+ * The generated UUID adheres strictly to the layout and variant bits of UUID version 7 as defined
+ * in the specification.
+ *
+ * @author zihluwang
+ * @author siujamo
+ * @version 3.0.0
+ */
+public class SequentialUuidGenerator implements IdentityGenerator {
+
+ private final SecureRandom random;
+
+ /**
+ * Constructs a new {@code SequentialUuidGenerator} with its own {@link SecureRandom} instance.
+ */
+ public SequentialUuidGenerator() {
+ this.random = new SecureRandom();
+ }
+
+ /**
+ * Generates and returns the next UUID version 7 identifier.
+ *
+ * @return a {@link UUID} instance representing a unique, time-ordered identifier
+ */
+ @Override
+ public UUID nextId() {
+ var value = randomBytes();
+ var buf = ByteBuffer.wrap(value);
+ var high = buf.getLong();
+ var low = buf.getLong();
+ return new UUID(high, low);
+ }
+
+ /**
+ * Produces a byte array representation of a UUID version 7,
+ * combining the current timestamp with random bytes.
+ *
+ * @return a 16-byte array conforming to UUIDv7 layout and variant bits
+ */
+ private byte[] randomBytes() {
+ var value = new byte[16];
+ random.nextBytes(value);
+
+ var timestamp = ByteBuffer.allocate(Long.BYTES);
+ timestamp.putLong(System.currentTimeMillis());
+
+ System.arraycopy(timestamp.array(), 2, value, 0, 6);
+
+ // Set version to 7 (UUIDv7)
+ value[6] = (byte) ((value[6] & 0x0F) | 0x70);
+
+ // Set variant bits as per RFC 4122
+ value[8] = (byte) ((value[8] & 0x3F) | 0x80);
+
+ return value;
+ }
+}
diff --git a/guid/src/main/java/com/onixbyte/guid/impl/SnowflakeGuidCreator.java b/identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java
similarity index 69%
rename from guid/src/main/java/com/onixbyte/guid/impl/SnowflakeGuidCreator.java
rename to identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java
index 4df7203..f3def6d 100644
--- a/guid/src/main/java/com/onixbyte/guid/impl/SnowflakeGuidCreator.java
+++ b/identity-generator/src/main/java/com/onixbyte/identitygenerator/impl/SnowflakeIdentityGenerator.java
@@ -1,30 +1,35 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.guid.impl;
+package com.onixbyte.identitygenerator.impl;
-import com.onixbyte.guid.GuidCreator;
-import com.onixbyte.guid.exceptions.TimingException;
+import com.onixbyte.identitygenerator.IdentityGenerator;
+import com.onixbyte.identitygenerator.exceptions.TimingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
/**
- * The {@code SnowflakeGuidCreator} generates unique identifiers using the Snowflake algorithm,
+ * The {@code SnowflakeIdentityGenerator} generates unique identifiers using the Snowflake algorithm,
* which combines a timestamp, worker ID, and data centre ID to create 64-bit long integers. The bit
* distribution for the generated IDs is as follows:
*
@@ -35,17 +40,58 @@
* - 12 bits for sequence number (per millisecond)
*
*
- * When initializing a {@link SnowflakeGuidCreator}, you must provide the worker ID and data centre
- * ID, ensuring they are within the valid range defined by the bit size. The generator maintains an
- * internal sequence number that increments for IDs generated within the same millisecond. If the
- * system clock moves backward, an exception is thrown to prevent generating IDs with
- * repeated timestamps.
+ * When initializing a {@link SnowflakeIdentityGenerator}, you must provide the worker ID and data
+ * centre ID, ensuring they are within the valid range defined by the bit size. The generator
+ * maintains an internal sequence number that increments for IDs generated within the
+ * same millisecond. If the system clock moves backward, an exception is thrown to prevent
+ * generating IDs with repeated timestamps.
*
- * @author Zihlu Wang
- * @version 1.1.0
- * @since 1.0.0
+ * @author zihluwang
+ * @version 3.0.0
*/
-public final class SnowflakeGuidCreator implements GuidCreator {
+public final class SnowflakeIdentityGenerator implements IdentityGenerator {
+
+ /**
+ * Default custom epoch.
+ *
+ * @value 2015-01-01T00:00:00Z
+ */
+ private static final long DEFAULT_CUSTOM_EPOCH = 1_420_070_400_000L;
+
+ /**
+ * The start epoch timestamp to generate IDs from.
+ */
+ private final long startEpoch;
+
+ /**
+ * The number of bits reserved for the worker ID.
+ */
+ private final long workerIdBits = 5L;
+
+ /**
+ * The number of bits reserved for the data centre ID.
+ */
+ private final long dataCentreIdBits = 5L;
+
+ /**
+ * The worker ID assigned to this generator.
+ */
+ private final long workerId;
+
+ /**
+ * The data centre ID assigned to this generator.
+ */
+ private final long dataCentreId;
+
+ /**
+ * The current sequence number.
+ */
+ private long sequence = 0L;
+
+ /**
+ * The timestamp of the last generated ID.
+ */
+ private long lastTimestamp = -1L;
/**
* Constructs a SnowflakeGuidGenerator with the default start epoch and custom worker ID, data
@@ -54,7 +100,7 @@ public final class SnowflakeGuidCreator implements GuidCreator {
* @param dataCentreId the data centre ID (between 0 and 31)
* @param workerId the worker ID (between 0 and 31)
*/
- public SnowflakeGuidCreator(long dataCentreId, long workerId) {
+ public SnowflakeIdentityGenerator(long dataCentreId, long workerId) {
this(dataCentreId, workerId, DEFAULT_CUSTOM_EPOCH);
}
@@ -67,7 +113,7 @@ public SnowflakeGuidCreator(long dataCentreId, long workerId) {
* @throws IllegalArgumentException if the start epoch is greater than the current timestamp,
* or if the worker ID or data centre ID is out of range
*/
- public SnowflakeGuidCreator(long dataCentreId, long workerId, long startEpoch) {
+ public SnowflakeIdentityGenerator(long dataCentreId, long workerId, long startEpoch) {
if (startEpoch > currentTimestamp()) {
throw new IllegalArgumentException("Start Epoch can not be greater than current timestamp!");
}
@@ -75,13 +121,13 @@ public SnowflakeGuidCreator(long dataCentreId, long workerId, long startEpoch) {
var maxWorkerId = ~(-1L << workerIdBits);
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("Worker Id can't be greater than %d or less than 0",
- maxWorkerId));
+ maxWorkerId));
}
var maxDataCentreId = ~(-1L << dataCentreIdBits);
if (dataCentreId > maxDataCentreId || dataCentreId < 0) {
throw new IllegalArgumentException(String.format("Data Centre Id can't be greater than %d or less than 0",
- maxDataCentreId));
+ maxDataCentreId));
}
this.startEpoch = startEpoch;
@@ -104,7 +150,7 @@ public synchronized Long nextId() {
// the system clock has been set back and an exception should be thrown
if (timestamp < lastTimestamp) {
throw new TimingException("Clock moved backwards. Refusing to generate id for %d milliseconds"
- .formatted(lastTimestamp - timestamp));
+ .formatted(lastTimestamp - timestamp));
}
// if generated at the same time, perform intra-millisecond sequences
@@ -130,9 +176,9 @@ public synchronized Long nextId() {
var timestampLeftShift = sequenceBits + workerIdBits + dataCentreIdBits;
var dataCentreIdShift = sequenceBits + workerIdBits;
return ((timestamp - startEpoch) << timestampLeftShift)
- | (dataCentreId << dataCentreIdShift)
- | (workerId << sequenceBits)
- | sequence;
+ | (dataCentreId << dataCentreIdShift)
+ | (workerId << sequenceBits)
+ | sequence;
}
/**
@@ -158,47 +204,5 @@ private long currentTimestamp() {
return LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
- /**
- * Default custom epoch.
- *
- * @value 2015-01-01T00:00:00Z
- */
- private static final long DEFAULT_CUSTOM_EPOCH = 1_420_070_400_000L;
-
- /**
- * The start epoch timestamp to generate IDs from.
- */
- private final long startEpoch;
-
- /**
- * The number of bits reserved for the worker ID.
- */
- private final long workerIdBits = 5L;
-
- /**
- * The number of bits reserved for the data centre ID.
- */
- private final long dataCentreIdBits = 5L;
-
- /**
- * The worker ID assigned to this generator.
- */
- private final long workerId;
-
- /**
- * The data centre ID assigned to this generator.
- */
- private final long dataCentreId;
-
- /**
- * The current sequence number.
- */
- private long sequence = 0L;
-
- /**
- * The timestamp of the last generated ID.
- */
- private long lastTimestamp = -1L;
-
}
diff --git a/identity-generator/src/main/resources/logback.xml b/identity-generator/src/main/resources/logback.xml
new file mode 100644
index 0000000..288ac4a
--- /dev/null
+++ b/identity-generator/src/main/resources/logback.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+ ${COLOURFUL_OUTPUT}
+
+
+
+
+
+
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
deleted file mode 100644
index 7476c8f..0000000
--- a/key-pair-loader/src/main/java/com/onixbyte/security/KeyLoader.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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;
-
-import com.onixbyte.security.exception.KeyLoadingException;
-
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.interfaces.ECPublicKey;
-import java.security.interfaces.RSAPublicKey;
-
-/**
- * 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.
- *
- * @author zihluwang
- * @version 2.0.0
- * @since 1.6.0
- */
-public interface KeyLoader {
-
- /**
- * Load private key from pem-formatted key text.
- *
- * @param pemKeyText pem-formatted key text
- * @return loaded private key
- */
- PrivateKey loadPrivateKey(String pemKeyText);
-
- /**
- * Load public key from pem-formatted key text.
- *
- * @param pemKeyText pem-formatted key text
- * @return loaded private key
- */
- PublicKey loadPublicKey(String pemKeyText);
-
- /**
- * Loads an RSA public key using the provided modulus and exponent.
- *
- * This default implementation throws a {@link KeyLoadingException} to signify that this key loader does not support
- * loading an RSA public key. Implementing classes are expected to override this method to supply their own
- * loading logic.
- *
- * @param modulus the modulus value of the RSA public key, usually represented in hexadecimal or Base64
- * string format
- * @param exponent the public exponent value of the RSA public key, usually represented in hexadecimal or Base64
- * string format
- * @return the loaded {@link RSAPublicKey} instance
- * @throws KeyLoadingException if loading is not supported or fails
- */
- default RSAPublicKey loadPublicKey(String modulus, String exponent) {
- throw new KeyLoadingException("This key loader does not support loading an RSA public key.");
- }
-
- /**
- * Loads an EC public key using the provided x and y coordinates together with the curve name.
- *
- * This default implementation throws a {@link KeyLoadingException} to signify that this key loader does not support
- * loading an EC public key. Implementing classes are expected to override this method to supply their own
- * loading logic.
- *
- * @param xHex the hexadecimal string representing the x coordinate of the EC point
- * @param yHex the hexadecimal string representing the y coordinate of the EC point
- * @param curveName the name of the elliptic curve
- * @return the loaded {@link ECPublicKey} instance
- * @throws KeyLoadingException if loading is not supported or fails
- */
- default ECPublicKey loadPublicKey(String xHex, String yHex, String curveName) {
- throw new KeyLoadingException("This key loader does not support loading an EC public key.");
- }
-
- /**
- * Retrieves the raw content of a PEM formatted key by removing unnecessary headers, footers,
- * and new line characters.
- *
- *
- * This method processes the provided PEM key text to return a cleaned string that contains
- * only the key content. The method strips away the
- * {@code "-----BEGIN (EC )?(PRIVATE|PUBLIC) KEY-----"} and
- * {@code "-----END (EC )?(PRIVATE|PUBLIC) KEY-----"} lines, as well as any new line characters,
- * resulting in a continuous string representation of the key, which can be used for further
- * cryptographic operations.
- *
- * @param pemKeyText the PEM formatted key as a string, which may include headers, footers and
- * line breaks
- * @return a string containing the raw key content devoid of any unnecessary formatting
- * or whitespace
- */
- default String getRawContent(String pemKeyText) {
- // remove all unnecessary parts of the pem key text
- return pemKeyText
- .replaceAll("-----BEGIN ((EC )|(RSA ))?(PRIVATE|PUBLIC) KEY-----", "")
- .replaceAll("-----END ((EC )|(RSA ))?(PRIVATE|PUBLIC) KEY-----", "")
- .replaceAll("\n", "");
- }
-
-}
diff --git a/key-pair-loader/src/main/resources/logback.xml b/key-pair-loader/src/main/resources/logback.xml
deleted file mode 100644
index 1cf5a50..0000000
--- a/key-pair-loader/src/main/resources/logback.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ${COLOURFUL_OUTPUT}
-
-
-
-
-
-
\ No newline at end of file
diff --git a/math-toolbox/README.md b/math-toolbox/README.md
new file mode 100644
index 0000000..72b11d8
--- /dev/null
+++ b/math-toolbox/README.md
@@ -0,0 +1,4 @@
+# Math Toolkit
+
+**Math Toolkit** provides some mathematical algorithms and utilities such as chained high-precision
+mathematical calculator and percentile statistic algorithm.
diff --git a/num4j/build.gradle.kts b/math-toolbox/build.gradle.kts
similarity index 68%
rename from num4j/build.gradle.kts
rename to math-toolbox/build.gradle.kts
index c1cf949..9226aa3 100644
--- a/num4j/build.gradle.kts
+++ b/math-toolbox/build.gradle.kts
@@ -1,19 +1,25 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
+
import java.net.URI
plugins {
@@ -64,9 +70,9 @@ tasks.test {
publishing {
publications {
- create("num4j") {
+ create("mathToolbox") {
groupId = group.toString()
- artifactId = "num4j"
+ artifactId = "math-toolbox"
version = artefactVersion
pom {
@@ -108,7 +114,7 @@ publishing {
from(components["java"])
signing {
- sign(publishing.publications["num4j"])
+ sign(publishing.publications["mathToolbox"])
}
}
diff --git a/num4j/src/main/java/com/onixbyte/nums/ChainedCalcUtil.java b/math-toolbox/src/main/java/com/onixbyte/math/ChainedCalcUtil.java
similarity index 91%
rename from num4j/src/main/java/com/onixbyte/nums/ChainedCalcUtil.java
rename to math-toolbox/src/main/java/com/onixbyte/math/ChainedCalcUtil.java
index 62a7f61..51d31fd 100644
--- a/num4j/src/main/java/com/onixbyte/nums/ChainedCalcUtil.java
+++ b/math-toolbox/src/main/java/com/onixbyte/math/ChainedCalcUtil.java
@@ -1,24 +1,26 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.nums;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+package com.onixbyte.math;
import java.math.BigDecimal;
import java.math.RoundingMode;
@@ -87,14 +89,12 @@
* and may have performance implications for extremely large numbers or complex calculations.
*
* @author sunzsh
- * @version 1.1.0
+ * @version 3.0.0
* @see BigDecimal
* @since 1.0.0
*/
public final class ChainedCalcUtil {
- private final static Logger log = LoggerFactory.getLogger(ChainedCalcUtil.class);
-
/**
* Creates a {@code ChainedCalcUtil} instance with the specified initial value.
*
diff --git a/num4j/src/main/java/com/onixbyte/nums/PercentileCalculator.java b/math-toolbox/src/main/java/com/onixbyte/math/PercentileCalculator.java
similarity index 63%
rename from num4j/src/main/java/com/onixbyte/nums/PercentileCalculator.java
rename to math-toolbox/src/main/java/com/onixbyte/math/PercentileCalculator.java
index 3578ec5..50b624c 100644
--- a/num4j/src/main/java/com/onixbyte/nums/PercentileCalculator.java
+++ b/math-toolbox/src/main/java/com/onixbyte/math/PercentileCalculator.java
@@ -1,25 +1,28 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.nums;
+package com.onixbyte.math;
-import com.onixbyte.nums.model.QuartileBounds;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import com.onixbyte.math.model.QuartileBounds;
import java.util.List;
@@ -29,30 +32,30 @@
*
* This class contains static methods to:
*
- * - Calculate a specified percentile from a list of double values using linear interpolation.
- * - Calculate interquartile bounds (Q1, Q3) and the corresponding lower and upper bounds,
- * which can be used to identify outliers in the dataset.
+ * -
+ * Calculate a specified percentile from a list of double values using linear interpolation.
+ *
+ * -
+ * Calculate interquartile bounds (Q1, Q3) and the corresponding lower and upper bounds,
+ * which can be used to identify outliers in the dataset.
+ *
*
*
* This class is final, meaning it cannot be subclassed, and it only contains static methods,
* so instances of the class cannot be created.
*
Example usage:
- *
- * {@code
+ * {@code
* List data = Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0);
* Double percentileValue = PercentileCalculator.calculatePercentile(data, 50.0); // Calculates median
* QuartileBounds bounds = PercentileCalculator.calculatePercentileBounds(data); // Calculates IQR bounds
- * }
- *
+ * }
*
* @author zihluwang
- * @version 1.6.5
+ * @version 3.0.0
* @since 1.6.5
*/
public final class PercentileCalculator {
- private final static Logger log = LoggerFactory.getLogger(PercentileCalculator.class);
-
/**
* Private constructor to prevent instantiation of this utility class.
*/
@@ -100,18 +103,18 @@ public static Double calculatePercentile(List values, Double percentile)
*/
public static QuartileBounds calculatePercentileBounds(List data) {
var sorted = data.stream().sorted().toList();
- var Q1 = calculatePercentile(sorted, 25.);
- var Q3 = calculatePercentile(sorted, 75.);
+ var q1 = calculatePercentile(sorted, 25.);
+ var q3 = calculatePercentile(sorted, 75.);
- var IQR = Q3 - Q1;
+ var iqr = q3 - q1;
- var lowerBound = Q1 - 1.5 * IQR;
- var upperBound = Q3 + 1.5 * IQR;
+ var lowerBound = q1 - 1.5 * iqr;
+ var upperBound = q3 + 1.5 * iqr;
return QuartileBounds.builder()
- .upperBound(upperBound)
- .lowerBound(lowerBound)
- .build();
+ .upperBound(upperBound)
+ .lowerBound(lowerBound)
+ .build();
}
}
diff --git a/num4j/src/main/java/com/onixbyte/nums/model/QuartileBounds.java b/math-toolbox/src/main/java/com/onixbyte/math/model/QuartileBounds.java
similarity index 67%
rename from num4j/src/main/java/com/onixbyte/nums/model/QuartileBounds.java
rename to math-toolbox/src/main/java/com/onixbyte/math/model/QuartileBounds.java
index 60b9470..44140be 100644
--- a/num4j/src/main/java/com/onixbyte/nums/model/QuartileBounds.java
+++ b/math-toolbox/src/main/java/com/onixbyte/math/model/QuartileBounds.java
@@ -1,21 +1,26 @@
/*
- * Copyright (C) 2024-2025 OnixByte.
+ * 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
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
*
- * 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.
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
*/
-package com.onixbyte.nums.model;
+package com.onixbyte.math.model;
/**
* A record representing the quartile bounds of a dataset.
@@ -26,27 +31,31 @@
*
* Quartile bounds consist of:
*
- * - {@code lowerBound} - The lower bound of the dataset, typically {@code Q1 - 1.5 * IQR}.
- * - {@code upperBound} - The upper bound of the dataset, typically {@code Q3 + 1.5 * IQR}.
+ * -
+ * {@code lowerBound} - The lower bound of the dataset, typically {@code Q1 - 1.5 * IQR}.
+ *
+ * -
+ * {@code upperBound} - The upper bound of the dataset, typically {@code Q3 + 1.5 * IQR}.
+ *
*
*
* Example usage:
- *
+ * {@code
* QuartileBounds bounds = QuartileBounds.builder()
- * .lowerBound(1.5)
- * .upperBound(7.5)
- * .build();
- *
+ * .lowerBound(1.5)
+ * .upperBound(7.5)
+ * .build();
+ * }
*
* @param upperBound the upper bound of the dataset
* @param lowerBound the lower bound of the dataset
* @author zihluwang
- * @version 1.6.5
+ * @version 3.0.0
* @since 1.6.5
*/
public record QuartileBounds(
- Double upperBound,
- Double lowerBound
+ Double upperBound,
+ Double lowerBound
) {
/**
diff --git a/math-toolbox/src/main/resources/logback.xml b/math-toolbox/src/main/resources/logback.xml
new file mode 100644
index 0000000..288ac4a
--- /dev/null
+++ b/math-toolbox/src/main/resources/logback.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+ ${COLOURFUL_OUTPUT}
+
+
+
+
+
+
diff --git a/num4j/README.md b/num4j/README.md
deleted file mode 100644
index 7745ec1..0000000
--- a/num4j/README.md
+++ /dev/null
@@ -1,3 +0,0 @@
-# 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/num4j/src/main/resources/logback.xml b/num4j/src/main/resources/logback.xml
deleted file mode 100644
index 1cf5a50..0000000
--- a/num4j/src/main/resources/logback.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-
-
-
-
-
-
-
-
-
-
- ${COLOURFUL_OUTPUT}
-
-
-
-
-
-
\ No newline at end of file
diff --git a/settings.gradle.kts b/settings.gradle.kts
index a87eb97..d5b4d12 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -18,12 +18,9 @@
rootProject.name = "onixbyte-toolbox"
include(
- "devkit-bom",
- "devkit-utils",
- "guid",
- "key-pair-loader",
- "num4j",
- "simple-jwt-facade",
- "simple-jwt-authzero",
- "simple-jwt-spring-boot-starter",
+ "version-catalogue",
+ "common-toolbox",
+ "identity-generator",
+ "crypto-toolbox",
+ "math-toolbox",
)
diff --git a/simple-jwt-authzero/README.md b/simple-jwt-authzero/README.md
deleted file mode 100644
index fbebcda..0000000
--- a/simple-jwt-authzero/README.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# Module `simple-jwt-authzero`
-
-## Introduction
-
-The `simple-jwt-authzero` module is an implementation of module `simple-jwt-facade` which uses the third-party library `com.auth0:java-jwt`. By using this module can help you use JWT to help you in your application.
-
-## Prerequisites
-
-This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience.
-
-## Installation
-
-> This module has already imported `simple-jwt-facade`, there is no need to import it again.
-
-### 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
- simple-jwt-authzero
- ${simple-jwt-authzero.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/simple-jwt-facade/`.
-
-### 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:simple-jwt-authzero:${simple-jwt-authzero.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`.
-
-## Use the `AuthzeroTokenResolver`
-
-We have implemented `TokenResolver` to make sure you can add JWT to your Java application as soon as possible. All you need to do is to create an instance of `com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver` and other operations to JWT could follow our instruction in [`simple-jwt-facade`](../simple-jwt-facade/README.md).
-
-## 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).
diff --git a/simple-jwt-authzero/build.gradle.kts b/simple-jwt-authzero/build.gradle.kts
deleted file mode 100644
index ccf4367..0000000
--- a/simple-jwt-authzero/build.gradle.kts
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.
- */
-import java.net.URI
-
-plugins {
- java
- id("java-library")
- id("maven-publish")
- id("signing")
-}
-
-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
-
-group = "com.onixbyte"
-version = artefactVersion
-
-repositories {
- mavenCentral()
-}
-
-java {
- sourceCompatibility = JavaVersion.VERSION_17
- targetCompatibility = JavaVersion.VERSION_17
- withSourcesJar()
- withJavadocJar()
-}
-
-tasks.withType {
- options.encoding = "UTF-8"
-}
-
-tasks.withType {
- exclude("logback.xml")
-}
-
-dependencies {
- compileOnly(libs.slf4j)
- implementation(libs.logback)
-
- api(project(":devkit-utils"))
- api(project(":guid"))
- api(project(":key-pair-loader"))
- api(project(":simple-jwt-facade"))
- api(libs.jackson.databind)
- api(libs.jwt.core)
-
- testImplementation(platform(libs.junit.bom))
- testImplementation(libs.junit.jupiter)
-}
-
-tasks.test {
- useJUnitPlatform()
-}
-
-publishing {
- publications {
- create("simpleJwtAuthzero") {
- groupId = group.toString()
- artifactId = "simple-jwt-authzero"
- version = artefactVersion
-
- pom {
- name = "OnixByte JWT Toolbox :: Auth0 Implementation"
- description = "Simple JWT implemented with com.auth0:java-jwt."
- url = projectUrl
-
- licenses {
- license {
- name = licenseName
- url = licenseUrl
- }
- }
-
- scm {
- connection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
- developerConnection = "scm:git:git://github.com:onixbyte/onixbyte-toolbox.git"
- url = projectGithubUrl
- }
-
- developers {
- developer {
- id = "zihluwang"
- name = "Zihlu Wang"
- email = "really@zihlu.wang"
- timezone = "Asia/Hong_Kong"
- }
-
- developer {
- id = "siujamo"
- name = "Siu Jam'o"
- email = "jamo.siu@outlook.com"
- timezone = "Asia/Shanghai"
- }
- }
- }
-
- from(components["java"])
-
- signing {
- sign(publishing.publications["simpleJwtAuthzero"])
- }
- }
-
- 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()
- }
- }
- }
- }
-}
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
deleted file mode 100644
index 790700c..0000000
--- a/simple-jwt-authzero/src/main/java/com/onixbyte/simplejwt/authzero/AuthzeroTokenResolver.java
+++ /dev/null
@@ -1,658 +0,0 @@
-/*
- * 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.simplejwt.authzero;
-
-import com.onixbyte.devkit.utils.Base64Util;
-import com.onixbyte.guid.GuidCreator;
-import com.onixbyte.security.impl.ECKeyLoader;
-import com.onixbyte.simplejwt.TokenPayload;
-import com.onixbyte.simplejwt.TokenResolver;
-import com.onixbyte.simplejwt.annotations.ExcludeFromPayload;
-import com.onixbyte.simplejwt.annotations.TokenEnum;
-import com.onixbyte.simplejwt.constants.PredefinedKeys;
-import com.onixbyte.simplejwt.constants.TokenAlgorithm;
-import com.auth0.jwt.JWT;
-import com.auth0.jwt.JWTCreator;
-import com.auth0.jwt.algorithms.Algorithm;
-import com.auth0.jwt.interfaces.DecodedJWT;
-import com.auth0.jwt.interfaces.JWTVerifier;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.type.TypeReference;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.onixbyte.simplejwt.exceptions.IllegalKeyPairException;
-import com.onixbyte.simplejwt.exceptions.IllegalSecretException;
-import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.InvocationTargetException;
-import java.security.interfaces.ECPrivateKey;
-import java.security.interfaces.ECPublicKey;
-import java.time.Duration;
-import java.time.LocalDateTime;
-import java.time.ZoneId;
-import java.util.*;
-import java.util.function.BiFunction;
-import java.util.function.Function;
-
-/**
- * The {@code AuthzeroTokenResolver} class is an implementation of the {@link TokenResolver}
- * interface. It uses the {@code com.auth0:java-jwt} library to handle JSON Web Token (JWT)
- * resolution. This resolver provides functionality to create, extract, verify, and renew JWT
- * tokens using various algorithms and custom payload data.
- *
- * Usage:
- * To use the {@code AuthzeroTokenResolver}, first, create an instance of this class:
- *
{@code
- * TokenResolver tokenResolver =
- * new AuthzeroTokenResolver(TokenAlgorithm.HS256,
- * "Token Subject",
- * "Token Issuer",
- * "Token Secret");
- * }
- *
- * Then, you can utilize the various methods provided by this resolver to handle JWT tokens:
- *
{@code
- * // Creating a new JWT token
- * String token =
- * tokenResolver.createToken(Duration.ofHours(1),
- * "your_subject",
- * "your_audience",
- * customPayloads);
- *
- * // Extracting payload data from a JWT token
- * DecodedJWT decodedJWT = tokenResolver.resolve(token);
- * T payloadData = decodedJWT.extract(token, T.class);
- *
- * // Renewing an existing JWT token
- * String renewedToken =
- * tokenResolver.renew(token, Duration.ofMinutes(30), customPayloads);
- * }
- *
- * Note:
- * It is essential to configure the appropriate algorithms, secret, and issuer according to your
- * specific use case when using this resolver. Additionally, ensure that the
- * {@code com.auth0:java-jwt} library is correctly configured in your project's dependencies.
- *
- * @author Zihlu Wang
- * @version 1.1.1
- * @see GuidCreator
- * @see Algorithm
- * @see JWTVerifier
- * @see JWTCreator
- * @see JWTCreator.Builder
- * @since 1.0.0
- */
-public class AuthzeroTokenResolver implements TokenResolver {
-
- private final static Logger log = LoggerFactory.getLogger(AuthzeroTokenResolver.class);
-
- /**
- * Create a builder of {@link AuthzeroTokenResolver}.
- *
- * @return a builder instance
- */
- public static Builder builder() {
- return new Builder();
- }
-
- /**
- * Builder for {@link AuthzeroTokenResolver}
- */
- public static class Builder {
-
- /**
- * GuidCreator used for generating unique identifiers for "jti" claim in JWT tokens.
- */
- private GuidCreator> jtiCreator;
-
- /**
- * The algorithm used for signing and verifying JWT tokens.
- */
- private Algorithm algorithm;
-
- /**
- * The issuer claim value to be included in JWT tokens.
- */
- private String issuer;
-
- /**
- * Jackson JSON handler.
- */
- private ObjectMapper objectMapper;
-
- /**
- * The secret to sign a JWT with HMAC based algorithm.
- */
- private String secret;
-
- /**
- * The private key to sign a JWT with ECDSA based algorithm.
- */
- private ECPrivateKey privateKey;
-
- /**
- * The public key to read a JWT with ECDSA based algorithm.
- */
- private ECPublicKey publicKey;
-
- /**
- * Private constructor to prevent instantiation of this utility class.
- */
- private Builder() {
- }
-
- /**
- * Set the secret to sign a JWT.
- *
- * @param secret the secret
- * @return the builder instance
- */
- public Builder secret(String secret) {
- this.secret = secret;
- return this;
- }
-
- /**
- * Set the key pair to sign a JWT.
- *
- * @param publicKey the pem formatted public key text
- * @param privateKey the pem formatted private key text
- * @return the builder instance
- */
- public Builder keyPair(String publicKey, String privateKey) {
- var keyLoader = new ECKeyLoader();
- this.publicKey = keyLoader.loadPublicKey(publicKey);
- this.privateKey = keyLoader.loadPrivateKey(privateKey);
- return this;
- }
-
- /**
- * Set the algorithm to sign a JWT.
- *
- * A secret required by HMAC-based algorithms, or key pair required by ECDSA-based
- * algorithms need to be set before initialise an algorithm.
- *
- * @param algorithm an {@link TokenAlgorithm} value
- * @return the builder instance
- */
- public Builder algorithm(TokenAlgorithm algorithm) {
- // check the secret or key pair before algorithm initialised
- if (HMAC_ALGORITHMS.containsKey(algorithm)) {
- if (Objects.isNull(secret) || secret.isBlank()) {
- throw new IllegalSecretException("""
- Please specify a secret before define an algorithm.""");
- }
- } else if (ECDSA_ALGORITHMS.containsKey(algorithm)) {
- if (Objects.isNull(publicKey) || Objects.isNull(privateKey)) {
- throw new IllegalKeyPairException("""
- Please specify a ECDSA key pair before define an algorithm.""");
- }
- }
-
- // initialise algorithm
- this.algorithm = switch (algorithm) {
- case HS256, HS384, HS512 -> HMAC_ALGORITHMS.get(algorithm).apply(secret);
- case ES256, ES384, ES512 -> ECDSA_ALGORITHMS.get(algorithm)
- .apply(publicKey, privateKey);
- default -> throw new UnsupportedAlgorithmException("""
- This algorithm is not supported yet.""");
- };
- return this;
- }
-
- /**
- * Set the object mapper.
- *
- * @param objectMapper an object mapper
- * @return the builder instance
- */
- public Builder objectMapper(ObjectMapper objectMapper) {
- this.objectMapper = objectMapper;
- return this;
- }
-
- /**
- * Set the creator of JWT id.
- *
- * @param jtiCreator a creator to create JWT id
- * @return the builder instance
- */
- public Builder jtiCreator(GuidCreator> jtiCreator) {
- this.jtiCreator = jtiCreator;
- return this;
- }
-
- /**
- * Set the issuer of created JWT.
- *
- * @param issuer the person or organisation issued this JWT
- * @return the builder instance
- */
- public Builder issuer(String issuer) {
- this.issuer = issuer;
- return this;
- }
-
- /**
- * Create an {@link AuthzeroTokenResolver} instance
- *
- * @return created instance
- */
- public AuthzeroTokenResolver build() {
- return new AuthzeroTokenResolver(jtiCreator, algorithm, issuer, objectMapper);
- }
- }
-
- /**
- * Creates a new token with the specified expiration duration, subject, and
- * audience.
- *
- * @param expireAfter the duration after which the token will expire
- * @param subject the subject of the token
- * @param audience the audience for which the token is intended
- * @return the generated token as a {@code String}
- */
- @Override
- public String createToken(Duration expireAfter, String audience, String subject) {
- final var builder = JWT.create();
- buildBasicInfo(builder, expireAfter, subject, audience);
- return buildToken(builder);
- }
-
- /**
- * Creates a new token with the specified expiration time, subject,
- * audience, and custom payload data.
- *
- * @param expireAfter the duration after which the token will expire
- * @param subject the subject of the token
- * @param audience the audience for which the token is intended
- * @param payloads the custom payload data to be included in the token
- * @return the generated token as a {@code String}
- */
- @Override
- public String createToken(Duration expireAfter, String audience, String subject, Map payloads) {
- // Create token.
- final var builder = JWT.create();
- buildBasicInfo(builder, expireAfter, subject, audience);
- buildMapClaims(builder, payloads);
- return buildToken(builder);
- }
-
- /**
- * Creates a new token with the specified expiration time, subject,
- * audience, and strongly-typed payload data.
- *
- * @param expireAfter the duration after which the token will expire
- * @param subject the subject of the token
- * @param audience the audience for which the token is intended
- * @param payload the strongly-typed payload data to be included in the
- * token
- * @return the generated token as a {@code String}
- */
- @Override
- public String createToken(Duration expireAfter, String audience, String subject, T payload) {
- final var builder = JWT.create();
- buildBasicInfo(builder, expireAfter, subject, audience);
-
- var payloadClass = payload.getClass();
- var fields = payloadClass.getDeclaredFields();
-
- for (var field : fields) {
- try {
- var fieldName = field.getName();
- // Skip the fields which are annotated with ExcludeFromPayload
- if (field.isAnnotationPresent(ExcludeFromPayload.class))
- continue;
-
- Object invokeObj = payload;
- var getter = payloadClass.getDeclaredMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
- if (field.isAnnotationPresent(TokenEnum.class)) {
- var tokenEnum = field.getAnnotation(TokenEnum.class);
- invokeObj = getter.invoke(payload);
- getter = field.getType().getDeclaredMethod("get" + tokenEnum.propertyName().substring(0, 1).toUpperCase() + tokenEnum.propertyName().substring(1));
- }
-
- // Build Claims
- addClaim(builder, fieldName, getter.invoke(invokeObj));
- } catch (IllegalAccessException e) {
- log.error("Cannot access field {}!", field.getName());
- } catch (NoSuchMethodException e) {
- log.error("Unable to find setter according to given field name.", e);
- } catch (InvocationTargetException e) {
- log.info("Cannot invoke method.", e);
- }
- }
-
- return buildToken(builder);
- }
-
- /**
- * Resolves the given token into a {@link DecodedJWT} object.
- *
- * @param token the token to be resolved
- * @return a {@link DecodedJWT} object
- */
- @Override
- public DecodedJWT resolve(String token) {
- return jwtVerifier.verify(token);
- }
-
- /**
- * Extracts the payload information from the given token and maps it to the
- * specified target type.
- *
- * @param token the token from which to extract the payload
- * @param targetType the target class representing the payload data type
- * @return an instance of the specified target type with the extracted
- * payload data, or {@code null} when extraction fails
- */
- @Override
- public T extract(String token, Class targetType) {
- try {
- // Get claims from token.
- var payloads = objectMapper.readValue(Base64Util.decodeUrlComponents(resolve(token).getPayload()), new MapTypeReference());
- // Get the no-argument constructor to create an instance.
- var bean = targetType.getConstructor().newInstance();
-
- for (var entry : payloads.entrySet()) {
- // Jump all JWT pre-defined properties and the fields that are annotated to be excluded.
- if (PredefinedKeys.KEYS.contains(entry.getKey()) || targetType.getDeclaredField(entry.getKey()).isAnnotationPresent(ExcludeFromPayload.class))
- continue;
-
- var field = targetType.getDeclaredField(entry.getKey());
- var setter = targetType.getDeclaredMethod("set" + entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1), field.getType());
- var fieldValue = entry.getValue();
- if (field.isAnnotationPresent(TokenEnum.class)) {
- var annotation = field.getAnnotation(TokenEnum.class);
- var enumStaticLoader = field.getType().getDeclaredMethod("loadBy" + annotation.propertyName().substring(0, 1).toUpperCase() + annotation.propertyName().substring(1), annotation.dataType().getMappedClass());
- fieldValue = enumStaticLoader.invoke(null, fieldValue);
- }
-
- if (setter.canAccess(bean)) {
- setter.invoke(bean, fieldValue);
- } else {
- log.error("Setter for field {} can't be accessed.", entry.getKey());
- }
- }
- return bean;
- } catch (JsonProcessingException e) {
- log.error("Unable to read payload as a Map.", e);
- } catch (InvocationTargetException | InstantiationException | IllegalAccessException |
- NoSuchMethodException e) {
- log.error("Unable to load the constructor or setter.", e);
- } catch (NoSuchFieldException e) {
- log.error("Unable to load the field.", e);
- }
- return null;
- }
-
- /**
- * Re-generate a new token with the payload in the old one.
- *
- * @param oldToken the old token
- * @param expireAfter how long the new token can be valid for
- * @return re-generated token with the payload in the old one or
- * {@code null} if an {@link JsonProcessingException} occurred.
- */
- @Override
- public String renew(String oldToken, Duration expireAfter) {
- var resolved = resolve(oldToken);
-
- try {
- var payload = objectMapper.readValue(Base64Util.decodeUrlComponents(resolved.getPayload()), ObjectNode.class);
- payload.remove(PredefinedKeys.KEYS);
-
- var payloadMap = objectMapper.convertValue(payload, new MapTypeReference());
- return createToken(expireAfter, resolved.getAudience().get(0), resolved.getSubject(), payloadMap);
- } catch (JsonProcessingException e) {
- log.error("Cannot read payload content, error details:", e);
- }
-
- return null;
- }
-
- /**
- * Renews the given expired token with the specified custom payload data.
- *
- * @param oldToken the expired token to be renewed
- * @param payload the custom payload data to be included in the renewed
- * token
- * @return the renewed token as a {@code String}
- */
- @Override
- public String renew(String oldToken, Duration expireAfter, Map payload) {
- final var resolvedToken = this.resolve(oldToken);
- var audience = resolvedToken.getAudience().get(0);
-
- return createToken(expireAfter, audience, resolvedToken.getSubject(), payload);
- }
-
- /**
- * Renews the given expired token with the specified custom payload data.
- *
- * @param oldToken the expiring token to be renewed
- * @param payload the custom payload data to be included in the renewed
- * token
- * @return the renewed token as a {@code String}
- */
- @Override
- public String renew(String oldToken, Map payload) {
- return renew(oldToken, Duration.ofMinutes(30), payload);
- }
-
- /**
- * Renews the given expired token with the new specified strongly-typed
- * payload data.
- *
- * @param oldToken the expiring token to be renewed
- * @param payload the strongly-typed payload data to be included in the
- * renewed token
- * @return the renewed token as a {@code String}
- */
- @Override
- public String renew(String oldToken, Duration expireAfter, T payload) {
- final var resolvedToken = this.resolve(oldToken);
- var audience = resolvedToken.getAudience().get(0);
-
- return createToken(expireAfter, audience, resolvedToken.getSubject(), payload);
- }
-
- /**
- * Renews the given expired token with the new specified strongly-typed
- * payload data.
- *
- * @param the type of the payload data, must implement
- * {@link TokenPayload}
- * @param oldToken the expired token to be renewed
- * @param payload the strongly-typed payload data to be included in the
- * renewed token
- * @return the renewed token as a {@link String}
- */
- @Override
- public String renew(String oldToken, T payload) {
- return renew(oldToken, Duration.ofMinutes(30), payload);
- }
-
- /**
- * Builds the basic information of the JSON Web Token (JWT) using the
- * provided parameters and adds it to the JWTCreator.Builder.
- *
- * @param subject the subject claim value to be included in the JWT
- * @param audience an array of audience claim values to be included in
- * the JWT
- * @param expireAfter the duration after which the JWT will expire
- * @param builder the JWTCreator.Builder instance to which the basic
- * information will be added
- */
- private void buildBasicInfo(JWTCreator.Builder builder, Duration expireAfter, String subject, String... audience) {
- var now = LocalDateTime.now();
-
- // bind issuer (iss)
- builder.withIssuer(issuer);
- // bind issued at (iat)
- builder.withIssuedAt(now.atZone(ZoneId.systemDefault()).toInstant());
- // bind not before (nbf)
- builder.withNotBefore(now.atZone(ZoneId.systemDefault()).toInstant());
- // bind audience (aud)
- builder.withAudience(audience);
- // bind subject (sub)
- builder.withSubject(subject);
- // bind expire at (exp)
- builder.withExpiresAt(now.plus(expireAfter).atZone(ZoneId.systemDefault()).toInstant());
- // bind JWT Id (jti)
- builder.withJWTId(jtiCreator.nextId().toString());
- }
-
- /**
- * Add a claim to a builder.
- *
- * @param builder the builder to build this JSON Web Token
- * @param name the property name
- * @param value the property value
- */
- private void addClaim(JWTCreator.Builder builder, String name, Object value) {
- if (Objects.nonNull(value)) {
- if (value instanceof Boolean v) {
- builder.withClaim(name, v);
- } else if (value instanceof Double v) {
- builder.withClaim(name, v);
- } else if (value instanceof Float v) {
- builder.withClaim(name, v.doubleValue());
- } else if (value instanceof Integer v) {
- builder.withClaim(name, v);
- } else if (value instanceof Long v) {
- builder.withClaim(name, v);
- } else if (value instanceof String v) {
- builder.withClaim(name, v);
- } else if (value instanceof Date v) {
- builder.withClaim(name, v);
- } else if (value instanceof List> v) {
- builder.withClaim(name, v);
- } else {
- log.warn("""
- Unable to determine the type of field {}, we will handle it as a String.""", name);
- builder.withClaim(name, value.toString());
- }
- } else {
- builder.withNullClaim(name);
- }
- }
-
- /**
- * Builds the custom claims of the JSON Web Token (JWT) using the provided
- * Map of claims and adds them to the JWTCreator.Builder.
- *
- * This method is used to add custom claims to the JWT. It takes a Map of
- * claims, where each entry represents a custom claim name (key) and its
- * corresponding value (value). The custom claims will be added to the JWT
- * using the JWTCreator.Builder.
- *
- * @param claims a Map containing the custom claims to be added to the JWT
- * @param builder the JWTCreator.Builder instance to which the custom
- * claims will be added
- */
- private void buildMapClaims(JWTCreator.Builder builder, Map claims) {
- if (Objects.nonNull(claims)) {
- for (var e : claims.entrySet()) {
- addClaim(builder, e.getKey(), e.getValue());
- }
- }
- }
-
- /**
- * Finish creating a token.
- *
- * This is the final step of create a token, to sign this token.
- *
- * @param builder the builder to build this JWT
- * @return the generated token as a {@code String}
- */
- private String buildToken(JWTCreator.Builder builder) {
- return builder.sign(algorithm);
- }
-
- /**
- * Default type reference for Map.
- */
- public static class MapTypeReference extends TypeReference