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("devkitUtils") { + create("commonToolbox") { groupId = group.toString() - artifactId = "devkit-utils" + artifactId = "common-toolbox" version = artefactVersion pom { name = "OnixByte Common Toolbox" - description = "The utils module of JDevKit." + description = "The utils module of OnixByte toolbox." url = projectUrl licenses { @@ -107,7 +113,7 @@ publishing { from(components["java"]) signing { - sign(publishing.publications["devkitUtils"]) + sign(publishing.publications["commonToolbox"]) } } diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/AesUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/AesUtil.java similarity index 54% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/AesUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/AesUtil.java index 00619a3..62ee697 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/AesUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/AesUtil.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 javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; @@ -54,12 +59,43 @@ * System.out.println(randomSecret); // Output: A randomly generated 16-character long secret * } * - * @author hubin@baomidou - * @version 1.1.0 - * @since 1.1.0 + * @author hubin + * @version 3.0.0 */ public final class AesUtil { + /** + * The algorithm AES. + */ + private static final String AES = "AES"; + + /** + * The algorithm AES/CBC/PKCS5Padding. + */ + private static final String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding"; + + /** + * Private constructor to prevent instantiation of this utility class. + */ + private AesUtil() { + } + + /** + * Encrypts the specified data using the AES algorithm with the provided secret key. + * + * @param data the data to be encrypted + * @param secret the secret key used for encryption + * @param ivParam the iv param + * @return the encrypted data as a byte array + * @throws GeneralSecurityException if any cryptographic error occurs during encryption + */ + public static byte[] encrypt(byte[] data, byte[] secret, byte[] ivParam) throws GeneralSecurityException { + var secretKeySpec = new SecretKeySpec(new SecretKeySpec(secret, AES).getEncoded(), AES); + var cipher = Cipher.getInstance(AES_CBC_CIPHER); + cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivParam)); + return cipher.doFinal(data); + } + /** * Encrypts the specified data using the AES algorithm with the provided secret key. * @@ -69,9 +105,22 @@ public final class AesUtil { * @throws GeneralSecurityException if any cryptographic error occurs during encryption */ public static byte[] encrypt(byte[] data, byte[] secret) throws GeneralSecurityException { + return encrypt(data, secret, secret); + } + + /** + * Decrypts the specified data using the AES algorithm with the provided secret key. + * + * @param data the data to be decrypted + * @param secret the secret key used for decryption + * @param ivParam the iv param + * @return the decrypted data as a byte array + * @throws GeneralSecurityException if any cryptographic error occurs during decryption + */ + public static byte[] decrypt(byte[] data, byte[] secret, byte[] ivParam) throws GeneralSecurityException { var secretKeySpec = new SecretKeySpec(new SecretKeySpec(secret, AES).getEncoded(), AES); var cipher = Cipher.getInstance(AES_CBC_CIPHER); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(secret)); + cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivParam)); return cipher.doFinal(data); } @@ -84,10 +133,24 @@ public static byte[] encrypt(byte[] data, byte[] secret) throws GeneralSecurityE * @throws GeneralSecurityException if any cryptographic error occurs during decryption */ public static byte[] decrypt(byte[] data, byte[] secret) throws GeneralSecurityException { - var secretKeySpec = new SecretKeySpec(new SecretKeySpec(secret, AES).getEncoded(), AES); - var cipher = Cipher.getInstance(AES_CBC_CIPHER); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(secret)); - return cipher.doFinal(data); + return decrypt(data, secret, secret); + } + + /** + * Encrypts the specified string data using the AES algorithm with the provided secret key. + * + * @param data the string data to be encrypted + * @param secret the secret key used for encryption + * @param ivParam the iv param + * @return the encrypted data encoded in Base64 + * @throws GeneralSecurityException if any cryptographic error occurs during encryption + */ + public static String encrypt(String data, String secret, String ivParam) throws GeneralSecurityException { + return Base64.getEncoder().encodeToString(encrypt( + data.getBytes(StandardCharsets.UTF_8), + secret.getBytes(StandardCharsets.UTF_8), + ivParam.getBytes(StandardCharsets.UTF_8) + )); } /** @@ -99,8 +162,7 @@ public static byte[] decrypt(byte[] data, byte[] secret) throws GeneralSecurityE * @throws GeneralSecurityException if any cryptographic error occurs during encryption */ public static String encrypt(String data, String secret) throws GeneralSecurityException { - return Base64.getEncoder().encodeToString(encrypt(data.getBytes(StandardCharsets.UTF_8), - secret.getBytes(StandardCharsets.UTF_8))); + return encrypt(data, secret, secret); } /** @@ -111,35 +173,33 @@ public static String encrypt(String data, String secret) throws GeneralSecurityE * @return the decrypted string data * @throws GeneralSecurityException if any cryptographic error occurs during decryption */ - public static String decrypt(String data, String secret) throws GeneralSecurityException { - var decrypted = decrypt(Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8)), - secret.getBytes(StandardCharsets.UTF_8)); + public static String decrypt(String data, String secret, String ivParam) throws GeneralSecurityException { + var decrypted = decrypt( + Base64.getDecoder().decode(data.getBytes(StandardCharsets.UTF_8)), + secret.getBytes(StandardCharsets.UTF_8), + ivParam.getBytes(StandardCharsets.UTF_8) + ); return new String(decrypted, StandardCharsets.UTF_8); } /** - * Generates 16-character random secret. + * Decrypts the specified Base64-encoded string data using the AES algorithm with the provided secret key. * - * @return the generated secure secret + * @param data the Base64-encoded string data to be decrypted + * @param secret the secret key used for decryption + * @return the decrypted string data + * @throws GeneralSecurityException if any cryptographic error occurs during decryption */ - public static String generateRandomSecret() { - return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16); + public static String decrypt(String data, String secret) throws GeneralSecurityException { + return decrypt(data, secret, secret); } /** - * Private constructor to prevent instantiation of this utility class. + * Generates 16-character random secret. + * + * @return the generated secure secret */ - private AesUtil() { + public static String generateRandomSecret() { + return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16); } - - /** - * The algorithm AES. - */ - private static final String AES = "AES"; - - /** - * The algorithm AES/CBC/PKCS5Padding. - */ - private static final String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding"; - } diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/Base64Util.java b/common-toolbox/src/main/java/com/onixbyte/common/util/Base64Util.java similarity index 83% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/Base64Util.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/Base64Util.java index 93d0347..18214b0 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/Base64Util.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/Base64Util.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.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -50,11 +55,21 @@ * encoding and decoding. * * @author zihluwang - * @version 1.1.0 - * @since 1.0.0 + * @version 3.0.0 */ public final class Base64Util { + /** + * Private constructor to prevent instantiation of this utility class. + */ + private Base64Util() { + } + + private static Base64.Encoder encoder; + private static Base64.Decoder decoder; + private static Base64.Encoder urlEncoder; + private static Base64.Decoder urlDecoder; + /** * Ensure that there is only one Base64 Encoder. * @@ -103,12 +118,6 @@ public static Base64.Decoder getUrlDecoder() { return urlDecoder; } - /** - * Private constructor to prevent instantiation of this utility class. - */ - private Base64Util() { - } - /** * Encodes the given string using the specified charset. * @@ -200,13 +209,4 @@ public static String decodeUrlComponents(String value, Charset charset) { public static String decodeUrlComponents(String value) { return decodeUrlComponents(value, StandardCharsets.UTF_8); } - - private static Base64.Encoder encoder; - - private static Base64.Decoder decoder; - - private static Base64.Encoder urlEncoder; - - private static Base64.Decoder urlDecoder; - -} \ No newline at end of file +} diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/BoolUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/BoolUtil.java similarity index 67% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/BoolUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/BoolUtil.java index 4bf81da..35600ae 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/BoolUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/BoolUtil.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.Arrays; import java.util.Objects; @@ -30,20 +35,23 @@ *

* *

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 T thenSupply(Supplier trueSupplier, Supplier falseSupplier) { * * @param the type of the result to be handled by the methods * @param trueSupplier the supplier to be executed if the result is {@code true} - * @return the result of the executed handler, or {@code null} if result of evaluation is {@code false} + * @return the result of the executed handler, or {@code null} if result of evaluation + * is {@code false} */ public T thenSupply(Supplier trueSupplier) { return thenSupply(trueSupplier, null); @@ -205,5 +210,4 @@ public void then(Runnable trueHandler, Runnable falseHandler) { public void then(Runnable trueHandler) { then(trueHandler, null); } - } diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/CollectionUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/CollectionUtil.java similarity index 71% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/CollectionUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/CollectionUtil.java index fd4534a..615f1ee 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/CollectionUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/CollectionUtil.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.ArrayList; import java.util.Collection; @@ -27,6 +32,7 @@ * A utility class providing static methods for manipulating collections. * * @author zihluwang + * @version 3.0.0 */ public final class CollectionUtil { @@ -55,9 +61,11 @@ private CollectionUtil() { * {@code maxSize} is less than zero, or * {@code collectionFactory} is {@code null} */ - public static > List chunk(C originalCollection, - int maxSize, - Supplier collectionFactory) { + public static > List chunk( + C originalCollection, + int maxSize, + Supplier collectionFactory + ) { // check inputs if (Objects.isNull(originalCollection)) { throw new IllegalArgumentException("Collection must not be null."); diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/HashUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/HashUtil.java similarity index 89% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/HashUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/HashUtil.java index 8fa7156..181a7f7 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/HashUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/HashUtil.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.nio.charset.Charset; import java.nio.charset.StandardCharsets; @@ -60,12 +65,17 @@ * encryption purposes. * * @author zihluwang - * @version 1.1.0 + * @version 3.0.0 * @see java.security.MessageDigest - * @since 1.0.0 */ public final class HashUtil { + /** + * Private constructor to prevent instantiation of this utility class. + */ + private HashUtil() { + } + /** * Calculates the MD2 hash value of the specified string using the given charset. * @@ -222,12 +232,6 @@ public static String sha512(String value) { return hash("SHA-512", value, StandardCharsets.UTF_8); } - /** - * Private constructor to prevent instantiation of this utility class. - */ - private HashUtil() { - } - /** * Calculates the hash value of the specified string using the specified * algorithm and charset. diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/MapUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/MapUtil.java similarity index 71% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/MapUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/MapUtil.java index 4fa5d78..a558cb7 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/MapUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/MapUtil.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.Map; @@ -28,15 +33,16 @@ *

* *

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 Map objectToMap(T entity, ObjectMapAdapter public static T mapToObject(Map objectMap, ObjectMapAdapter adapter) { return adapter.toObject(objectMap); } - - /** - * Private constructor to prevent instantiation of this utility class. - */ - private MapUtil() { - } } diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/ObjectMapAdapter.java b/common-toolbox/src/main/java/com/onixbyte/common/util/ObjectMapAdapter.java similarity index 59% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/ObjectMapAdapter.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/ObjectMapAdapter.java index 9dde1ff..aa66469 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/ObjectMapAdapter.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/ObjectMapAdapter.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.Map; @@ -28,8 +33,7 @@ * {@code T} to a {@link Map} and vice versa.

* *

Example usage:

- *
- * {@code
+ * 
{@code
  * public class User {
  *     private String name;
  *     private int age;
@@ -54,13 +58,11 @@
  *         return user;
  *     }
  * }
- * }
- * 
+ * }
* * @param the type of the object to be converted * @author zihluwang - * @version 1.7.0 - * @since 1.4.2 + * @version 3.0.0 */ public interface ObjectMapAdapter { diff --git a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/RangeUtil.java b/common-toolbox/src/main/java/com/onixbyte/common/util/RangeUtil.java similarity index 75% rename from devkit-utils/src/main/java/com/onixbyte/devkit/utils/RangeUtil.java rename to common-toolbox/src/main/java/com/onixbyte/common/util/RangeUtil.java index 2437e8b..e3a0a4c 100644 --- a/devkit-utils/src/main/java/com/onixbyte/devkit/utils/RangeUtil.java +++ b/common-toolbox/src/main/java/com/onixbyte/common/util/RangeUtil.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.stream.IntStream; @@ -27,6 +32,7 @@ * leverage the {@link IntStream} to provide efficient and versatile integer sequences. * * @author zihluwang + * @version 3.0.0 * @see IntStream */ public final class RangeUtil { @@ -64,7 +70,7 @@ private RangeUtil() { public static IntStream range(int end) { if (end <= 0) { throw new IllegalArgumentException("Parameter [end] should not be less than or equal to 0, provided: " + - end); + end); } return IntStream.range(0, end); } @@ -77,8 +83,9 @@ public static IntStream range(int end) { * further processing. *

* 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> { - MapTypeReference() { - } - } - - /** - * GuidCreator used for generating unique identifiers for "jti" claim in JWT tokens. - */ - private final GuidCreator jtiCreator; - - /** - * The algorithm used for signing and verifying JWT tokens. - */ - private final Algorithm algorithm; - - /** - * The issuer claim value to be included in JWT tokens. - */ - private final String issuer; - - /** - * The JSON Web Token resolver. - */ - private final JWTVerifier jwtVerifier; - - /** - * Jackson JSON handler. - */ - private final ObjectMapper objectMapper; - - /** - * A map contains all HMAC-SHA based algorithms. - */ - public static final Map> HMAC_ALGORITHMS = Map.of( - TokenAlgorithm.HS256, Algorithm::HMAC256, - TokenAlgorithm.HS384, Algorithm::HMAC384, - TokenAlgorithm.HS512, Algorithm::HMAC512 - ); - - /** - * A map contains all ECDSA based algorithms. - */ - public static final Map> ECDSA_ALGORITHMS = Map.of( - TokenAlgorithm.ES256, Algorithm::ECDSA256, - TokenAlgorithm.ES384, Algorithm::ECDSA384, - TokenAlgorithm.ES512, Algorithm::ECDSA512 - ); - - /** - * Private constructor to prevent instantiation of this utility class. - * - * @param jtiCreator a creator that can create JWT id - * @param algorithm an algorithm to sign this JWT - * @param issuer the person or organisation who issued this JWT - * @param objectMapper a mapper for handling JSON serialisation and deserialization - */ - private AuthzeroTokenResolver(GuidCreator jtiCreator, Algorithm algorithm, String issuer, ObjectMapper objectMapper) { - this.jtiCreator = jtiCreator; - this.algorithm = algorithm; - this.issuer = issuer; - this.objectMapper = objectMapper; - this.jwtVerifier = JWT.require(algorithm).build(); - } - -} diff --git a/simple-jwt-authzero/src/main/resources/logback.xml b/simple-jwt-authzero/src/main/resources/logback.xml deleted file mode 100644 index 6d26440..0000000 --- a/simple-jwt-authzero/src/main/resources/logback.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - ${COLOURFUL_OUTPUT} - - - - - - \ No newline at end of file diff --git a/simple-jwt-authzero/src/test/java/com/onixbyte/simplejwt/authzero/test/TestAuthzeroTokenResolver.java b/simple-jwt-authzero/src/test/java/com/onixbyte/simplejwt/authzero/test/TestAuthzeroTokenResolver.java deleted file mode 100644 index dc13543..0000000 --- a/simple-jwt-authzero/src/test/java/com/onixbyte/simplejwt/authzero/test/TestAuthzeroTokenResolver.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (C) 2023 CodeCraftersCN. - * - * 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.test; - -/** - * TestAuthzeroTokenResolver - * - * @author Zihlu Wang - */ -public class TestAuthzeroTokenResolver { - -} diff --git a/simple-jwt-facade/README.md b/simple-jwt-facade/README.md deleted file mode 100644 index 5f5623b..0000000 --- a/simple-jwt-facade/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Module `simple-jwt-facade` - -## Introduction - -The `simple-jwt-facade` module is a lightweight and easy-to-use façade for working with JSON Web Tokens (JWT) in Java applications. It provides a simplified interface and utilities to handle the creation, validation, renewal, and processing of JWTs without the need for complex configurations or third-party dependencies. - -## Prerequisites - -This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience. - -## Installation - -### If you are using `Maven` - -It is quite simple to install this module by `Maven`. The only thing you need to do is find your `pom.xml` file in the project, then find the `` node in the `` node, and add the following codes to `` node: - -```xml - - cn.org.codecrafters - simple-jwt-facade - ${simple-jwt-facade.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-facade:${simple-jwt-facade.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`. - -## Implement a `TokenResolver` - -If you want to use `TokenResolver` to handle with JWTs, you can choose to use any implementation such as `cn.org.codecrafters:simple-jwt-authzero` or any other `simple-jwt-$implementation_artifact`. But if you do choose to use other implementation, it is not the topic we are going to talk about here. We are here for helping you to implement one by yourself. - -First, you are going to choose a third-party library or your own library which is aims to process JWTs(i.e., `com.auth0:java-jwt` and `io.jsonwebtoken:jjwt`). Then, you need to confirm which class they are going to use for a parsed JWT(i.e., `DecodedJWT` is being used in `com.auth0:java-jwt`). And let me use `com.auth0:java-jwt` for example in this tutor. - -Then, you can add these following codes in your project: - -```java -class Auth0TokenResolver implements TokenResolver { - // Dont forget to implement methods in interface TokenResolver. -} -``` - -After doing all these, an implemented `TokenResolver` is ready to process JWTs. - -**Let's pretend that you already implemented a `TokenResolver` and named as `ImplementedTokenResolver`.** - -You will need an instance of the implementation to process JWTs. - -```java -var tokenResolver = new ImplementedTokenResolver(/* arguments you declared */) -``` - -## Create a JSON Web Token with `TokenResolver` - -Then, there are 3 method to create a token: - -```java -String createToken(java.time.Duration expireAfter, String audience, String subject); - -String createToken(java.time.Duration expireAfter, String audience, String subject, Map payloads); - - String createToken(java.time.Duration expireAfter, String audience, String subject, T payload); -``` - -## Read or Verify a JSON Web Token - -There are many ways to read a JWT. - -If you want to read as the data class which is designed by the third-party library, you can just use `resolve(String token)`. If you want know what is contained in this JWT, you can use `extract(String, Class)`. - -Meanwhile, the `resolve(token)` method also serves as a token validation mechanism. If any issues arise, such as token expiration, tampering suspicion, or mismatched token signatures, corresponding exceptions will be thrown. - -## Renew a Token that is About to Expire - -When a token is about to expire, its validity period can be extended using this method, allowing users to obtain a new valid token without the need for re-login. - -**Renew a token** means that the content of the pre-defined properties by JWT, such as the audience (aud) representing the recipient of this token, will not be altered, except for the time-related fields. - -```java -String renew(String oldToken, Map payload); -``` - -This method allows you to pass new custom payload into the updated token. The new token will be available for 30 minutes. - -```java -String renew(String oldToken, Duration expireAfter, Map payload); -``` - -This method allows you to pass new custom payload into the updated token. The new token will be available for the specific duration. - -```java - String renew(String oldToken, Duration expireAfter, T payload); -``` - -This method allows you to pass new custom payload into the updated token. The new token will be available for 30 minutes. - -```java - String renew(String oldToken, Duration expireAfter, T payload); -``` - -This method allows you to pass new custom payload into the updated token. The new token will be available for the specific duration. - -## Contact - -If you have any suggestions, ideas, don't hesitate contacting us via [GitHub Issues](https://github.com/CodeCraftersCN/jdevkit/issues/new) or [Discord Community](https://discord.gg/NQK9tjcBB8). - -If you face any bugs while using our library and you are able to fix any bugs in our library, we would be happy to accept pull requests from you on [GitHub](https://github.com/CodeCraftersCN/jdevkit/compare). \ No newline at end of file diff --git a/simple-jwt-facade/build.gradle.kts b/simple-jwt-facade/build.gradle.kts deleted file mode 100644 index b19f97b..0000000 --- a/simple-jwt-facade/build.gradle.kts +++ /dev/null @@ -1,129 +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")) - - testImplementation(platform(libs.junit.bom)) - testImplementation(libs.junit.jupiter) -} - -tasks.test { - useJUnitPlatform() -} - -publishing { - publications { - create("simpleJwtFacade") { - groupId = group.toString() - artifactId = "simple-jwt-facade" - version = artefactVersion - - pom { - name = "OnixByte JWT Toolbox :: Facade" - description = "Declaration of simple JWT module." - 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["simpleJwtFacade"]) - } - } - - 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-facade/src/main/java/com/onixbyte/simplejwt/SecretCreator.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/SecretCreator.java deleted file mode 100644 index 0b24439..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/SecretCreator.java +++ /dev/null @@ -1,159 +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; - -import com.onixbyte.simplejwt.exceptions.WeakSecretException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Random; - -/** - * {@code SecretCreator} is a utility class that provides methods to generate - * secure secret strings. The generated secrets can be used as cryptographic - * keys or passwords for various security-sensitive purposes. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public final class SecretCreator { - - private final static Logger log = LoggerFactory.getLogger(SecretCreator.class); - - /** - * Generates a secure secret with the specified length and character sets. - * - * @param length the length of the secret to be generated - * @param isContainCapital flag indicating if the secret should contain - * uppercase letters - * @param isContainDigital flag indicating if the secret should contain - * digits - * @param isContainSpecialSign flag indicating if the secret should contain - * special sign characters - * @return the generated secure secret - * @throws WeakSecretException if the requested secret length is less than - * 32 characters - */ - public static String createSecret(int length, - boolean isContainCapital, - boolean isContainDigital, - boolean isContainSpecialSign) { - if (length < 32) { - throw new WeakSecretException(""" - The requested secret, which is only %d characters long, is too weak. \ - Please replace it with a stronger secret.""".formatted(length)); - } - - final var randomiser = new Random(); - var charset = new StringBuilder(LOWERCASE_CHARACTERS); - - if (isContainCapital) charset.append(UPPERCASE_CHARACTERS); - if (isContainDigital) charset.append(DIGITS); - if (isContainSpecialSign) charset.append(SPECIAL_SIGNS); - - var secretBuilder = new StringBuilder(); - var charsetSize = charset.length(); - for (var i = 0; i < length; ++i) { - secretBuilder.append(charset.charAt(randomiser.nextInt(charsetSize))); - } - - return secretBuilder.toString(); - } - - /** - * Generates a secure secret with the specified length, containing - * uppercase letters and digits. - * - * @param length the length of the secret to be generated - * @param isContainCapital flag indicating if the secret should contain - * uppercase letters - * @param isContainDigital flag indicating if the secret should contain - * digits - * @return the generated secure secret - * @throws WeakSecretException if the requested secret length is less than - * 32 characters - * @see #createSecret(int, boolean, boolean, boolean) - */ - public static String createSecret(int length, - boolean isContainCapital, - boolean isContainDigital) { - return createSecret(length, isContainCapital, isContainDigital, false); - } - - /** - * Generates a secure secret with the specified length, containing - * uppercase letters. - * - * @param length the length of the secret to be generated - * @param isContainCapital flag indicating if the secret should contain - * uppercase letters - * @return the generated secure secret - * @throws WeakSecretException if the requested secret length is less than - * 32 characters - * @see #createSecret(int, boolean, boolean, boolean) - */ - public static String createSecret(int length, - boolean isContainCapital) { - return createSecret(length, isContainCapital, false, false); - } - - /** - * Generates a secure secret with the specified length, containing - * lowercase letters. - * - * @param length the length of the secret to be generated - * @return the generated secure secret - * @throws WeakSecretException if the requested secret length is less than - * 32 characters - * @see #createSecret(int, boolean, boolean, boolean) - */ - public static String createSecret(int length) { - return createSecret(length, false, false, false); - } - - /** - * Private constructor to prevent instantiation of this utility class. - */ - private SecretCreator() { - } - - /** - * The string containing all lowercase characters that can be used to - * generate the secret. - */ - private static final String LOWERCASE_CHARACTERS = "abcdefghijklmnopqrstuvwxyz"; - - /** - * The string containing all uppercase characters that can be used to - * generate the secret. - */ - private static final String UPPERCASE_CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; - - /** - * The string containing all digit characters that can be used to generate - * the secret. - */ - private static final String DIGITS = "0123456789"; - - /** - * The string containing all special sign characters that can be used to - * generate the secret. - */ - private static final String SPECIAL_SIGNS = "!@#$%^&,*()_+-=,[]{}|;:,'\",.<>/?"; -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenPayload.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenPayload.java deleted file mode 100644 index 1234c6c..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenPayload.java +++ /dev/null @@ -1,45 +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; - -/** - * {@code TokenPayload} interface is used to mark a data class as suitable - * for being used as the payload in a JSON Web Token (JWT). Any class - * implementing this interface can be used to represent the payload data that - * will be included in a JWT. - *

- * Implementing this interface indicates that the data class contains - * information that needs to be securely transmitted and verified as part of a - * JWT. The payload typically contains claims or attributes that provide - * additional information about the JWT subject or context. - *

- * Usage: - * To use a class as a JWT payload, simply implement the {@code TokenPayload} - * interface in the data class: - *

- * public class UserData implements TokenPayload {
- *     // Class implementation with payload data...
- * }
- * 
- * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public interface TokenPayload { -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenResolver.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenResolver.java deleted file mode 100644 index c2ea124..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/TokenResolver.java +++ /dev/null @@ -1,184 +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; - -import java.time.Duration; -import java.util.Map; - -/** - * {@code TokenResolver} defines methods for creating, extracting, and - * renewing tokens, particularly JSON Web Tokens (JWTs). It provides a set of - * methods to generate tokens with various payload configurations, extract - * payload from tokens, and renew expired tokens. - *

- * Token Creation: - * The interface provides overloaded methods for creating tokens with different - * payload configurations, including expiration time, audience, subject, and - * custom payload data. Clients can choose the appropriate method based on - * their specific token requirements. - *

- * Token Extraction: - * The interface includes methods to extract payload information from a given - * token. Clients can use these methods to obtain the payload data encoded in - * the token. - *

- * Token Renewal: - * The interface also offers methods for token renewal. Clients can renew an - * expired token by providing a new expiration time, audience, subject, and - * optional custom payload data. - * - * @param the type of the result obtained by the - * third-party library when parsing JWTs - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public interface TokenResolver { - - /** - * Creates a new token with the specified expiration time, 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} - */ - String createToken(Duration expireAfter, String audience, String subject); - - /** - * 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 payload the custom payload data to be included in the token - * @return the generated token as a {@code String} - */ - String createToken(Duration expireAfter, String audience, String subject, Map payload); - - /** - * Creates a new token with the specified expiration time, subject, - * audience, and strongly-typed payload data. - * - * @param the type of the payload data, must implement - * {@link TokenPayload} - * @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} - */ - String createToken(Duration expireAfter, String audience, String subject, T payload); - - /** - * Resolves the given token into a ResolvedTokenType object. - * - * @param token the token to be resolved - * @return a ResolvedTokenType object - */ - ResolvedTokenType resolve(String token); - - /** - * Extracts the payload information from the given token and maps it to the - * specified target type. - * - * @param the target type to which the payload data will be - * mapped - * @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 - */ - T extract(String token, Class targetType); - - /** - * 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 - */ - String renew(String oldToken, Duration expireAfter); - - /** - * Re-generate a new token with the payload in the old one. - * - * @param oldToken the old token - * @return re-generated token with the payload in the old one - * @see #renew(String, Duration) - */ - default String renew(String oldToken) { - return renew(oldToken, Duration.ofMinutes(30)); - } - - /** - * Renews the given expired token with the specified custom payload data. - * - * @param oldToken the expired token to be renewed - * @param expireAfter specify when does the new token invalid - * @param payload the custom payload data to be included in the renewed - * token - * @return the renewed token as a {@code String} - */ - String renew(String oldToken, Duration expireAfter, Map payload); - - /** - * 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} - */ - default String renew(String oldToken, Map payload) { - return renew(oldToken, Duration.ofMinutes(30), payload); - } - - /** - * Renews the given expired token with the 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 expireAfter specify when does the new token invalid - * @param payload the strongly-typed payload data to be included in the - * renewed token - * @return the renewed token as a {@code String} - */ - String renew(String oldToken, Duration expireAfter, T payload); - - /** - * Renews the given expired token with the 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 {@code String} - */ - default String renew(String oldToken, T payload) { - return renew(oldToken, Duration.ofMinutes(30), payload); - } - -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/ExcludeFromPayload.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/ExcludeFromPayload.java deleted file mode 100644 index 0253755..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/ExcludeFromPayload.java +++ /dev/null @@ -1,60 +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.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Annotation {@code ExcludeFromPayload} is used to mark a property of a data - * class that should be excluded from being automatically injected into the - * JSON Web Token (JWT) payload during token generation. When a property is - * annotated by this annotation, it will not be included in the JWT payloads. - *

- * Usage: - * To exclude a property from the JWT payload, annotate the property with - * {@code @ExcludeFromPayload}: - * - *

{@code
- * public class UserData implements TokenPayload {
- *     private String username;
- *
- *     // This property will not be included in the JWT payload
- *     @ExcludeFromPayload
- *     private String sensitiveData;
- *
- *     // Getters and setters...
- * }
- * }
- *

- * Note: - * This annotation should be used on properties that are not intended to - * be included in the JWT payload due to their sensitive nature or for other - * reasons only. It is important to carefully choose which properties are - * excluded from the payload to ensure the JWT remains secure and efficient. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface ExcludeFromPayload { -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/TokenEnum.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/TokenEnum.java deleted file mode 100644 index ffb5e2f..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/annotations/TokenEnum.java +++ /dev/null @@ -1,51 +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.annotations; - -import com.onixbyte.simplejwt.constants.TokenDataType; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * This annotation marks the enum field declared in payload class will be handled as basic data - * types in {@link TokenDataType}. - * - * @author Zihlu Wang - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface TokenEnum { - - /** - * The name of the field of the base data corresponding to the enumeration data. - * - * @return the name of the property - */ - String propertyName(); - - /** - * The attribute {@code dataType} specifies what base data type to treat this enum as. - * - * @return the data type of the token - */ - TokenDataType dataType(); - -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/PredefinedKeys.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/PredefinedKeys.java deleted file mode 100644 index af3b315..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/PredefinedKeys.java +++ /dev/null @@ -1,98 +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.constants; - -import java.util.List; - -/** - * The {@code PredefinedKeys} class contains constants for standard JSON Web Token (JWT) claims. These constants - * represent the names of the standard claims that can be included in a JWT payload. Developers can use these constants - * when working with JWTs to ensure consistent naming of the claims. - *

- * The class provides the following standard JWT claim constants: - *

    - *
  • {@link #ISSUER}: Represents the "iss" (Issuer) claim.
  • - *
  • {@link #SUBJECT}: Represents the "sub" (Subject) claim.
  • - *
  • {@link #AUDIENCE}: Represents the "aud" (Audience) claim.
  • - *
  • {@link #EXPIRATION_TIME}: Represents the "exp" (Expiration Time) claim.
  • - *
  • {@link #NOT_BEFORE}: Represents the "nbf" (Not Before) claim.
  • - *
  • {@link #ISSUED_AT}: Represents the "iat" (Issued At) claim.
  • - *
  • {@link #JWT_ID}: Represents the "jti" (JWT ID) claim.
  • - *
- *

- * The class also contains a list of all the standard claim constants, accessible via the {@link - * #KEYS} field. This list can be useful for iterating through all the standard claims or checking - * for the presence of specific claims. - *

- * Note: This class is final and cannot be instantiated. It only serves as a utility class to hold - * the standard JWT claim constants. - * - * @author zihluwang - * @version 1.1.0 - * @since 1.0.0 - */ -public final class PredefinedKeys { - - /** - * Constant representing the "iss" (Issuer) claim in a JWT payload. - */ - public static final String ISSUER = "iss"; - - /** - * Constant representing the "sub" (Subject) claim in a JWT payload. - */ - public static final String SUBJECT = "sub"; - - /** - * Constant representing the "aud" (Audience) claim in a JWT payload. - */ - public static final String AUDIENCE = "aud"; - - /** - * Constant representing the "exp" (Expiration Time) claim in a JWT payload. - */ - public static final String EXPIRATION_TIME = "exp"; - - /** - * Constant representing the "nbf" (Not Before) claim in a JWT payload. - */ - public static final String NOT_BEFORE = "nbf"; - - /** - * Constant representing the "iat" (Issued At) claim in a JWT payload. - */ - public static final String ISSUED_AT = "iat"; - - /** - * Constant representing the "jti" (JWT ID) claim in a JWT payload. - */ - public static final String JWT_ID = "jti"; - - /** - * List containing all the standard JWT claim constants. - */ - public static final List KEYS = - List.of(ISSUER, SUBJECT, AUDIENCE, EXPIRATION_TIME, NOT_BEFORE, ISSUED_AT, JWT_ID); - - /** - * Private constructor to prevent instantiation of this utility class. - */ - private PredefinedKeys() { - } -} - diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenAlgorithm.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenAlgorithm.java deleted file mode 100644 index 21d34c2..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenAlgorithm.java +++ /dev/null @@ -1,108 +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.constants; - -import java.util.List; - -/** - * The {@code TokenAlgorithm} enum class defines the algorithms that can be - * used for signing and verifying JSON Web Tokens (JWT). JWT allows various - * cryptographic algorithms to be used for secure token generation and - * validation. This enum provides a list of supported algorithms to ensure - * consistent usage and avoid potential security issues. - *

- * Supported Algorithms: - *

    - *
  • {@link TokenAlgorithm#HS256}: HMAC SHA-256
  • - *
  • {@link TokenAlgorithm#HS384}: HMAC SHA-384
  • - *
  • {@link TokenAlgorithm#HS512}: HMAC SHA-512
  • - *
  • {@link TokenAlgorithm#RS256}: RSA PKCS#1 v1.5 with SHA-256
  • - *
  • {@link TokenAlgorithm#RS384}: RSA PKCS#1 v1.5 with SHA-384
  • - *
  • {@link TokenAlgorithm#RS512}: RSA PKCS#1 v1.5 with SHA-512
  • - *
  • {@link TokenAlgorithm#ES256}: ECDSA with SHA-256
  • - *
  • {@link TokenAlgorithm#ES384}: ECDSA with SHA-384
  • - *
  • {@link TokenAlgorithm#ES512}: ECDSA with SHA-512
  • - *
- * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public enum TokenAlgorithm { - - /** - * HMAC using SHA-256 - */ - HS256, - - /** - * HMAC using SHA-384 - */ - HS384, - - /** - * HMAC using SHA-512 - */ - HS512, - - /** - * RSASSA-PKCS-v1_5 using SHA-256 - */ - RS256, - - /** - * RSASSA-PKCS-v1_5 using SHA-384 - */ - RS384, - - /** - * RSASSA-PKCS-v1_5 using SHA-512 - */ - RS512, - - /** - * ECDSA using P-256 and SHA-256 - */ - ES256, - - /** - * ECDSA using P-384 and SHA-384 - */ - ES384, - - /** - * ECDSA using P-521 and SHA-512 - */ - ES512, - ; - - /** - * HMAC-based algorithms. - */ - public static final List HMAC_ALGORITHMS = List.of( - TokenAlgorithm.HS256, TokenAlgorithm.HS384, TokenAlgorithm.HS512 - ); - - /** - * ECDSA-based algorithms. - */ - public static final List ECDSA_ALGORITHMS = List.of( - TokenAlgorithm.ES256, TokenAlgorithm.ES384, TokenAlgorithm.ES512 - ); - -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenDataType.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenDataType.java deleted file mode 100644 index 187b2e9..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/constants/TokenDataType.java +++ /dev/null @@ -1,78 +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.constants; - -/** - * The base data types used to process enum data. - * - * @author Zihlu Wang - */ -public enum TokenDataType { - - /** - * Marks enumeration being processed as Boolean. - */ - BOOLEAN(Boolean.class), - - /** - * Marks enumeration being processed as Double. - */ - DOUBLE(Long.class), - - /** - * Marks enumeration being processed as Float. - */ - FLOAT(Float.class), - - /** - * Marks enumeration being processed as Integer. - */ - INTEGER(Integer.class), - - /** - * Marks enumeration being processed as Long. - */ - LONG(Long.class), - - /** - * Marks enumeration being processed as String. - */ - STRING(String.class), - ; - - /** - * The mapped class to this mark. - */ - private final Class mappedClass; - - /** - * Create a TokenDataType with a mapped class. - */ - TokenDataType(Class mappedClass) { - this.mappedClass = mappedClass; - } - - /** - * Return the target mapped class. - * - * @return mapped class - */ - public Class getMappedClass() { - return mappedClass; - } -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalKeyPairException.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalKeyPairException.java deleted file mode 100644 index 55959ce..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalKeyPairException.java +++ /dev/null @@ -1,53 +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.exceptions; - -/** - * {@link IllegalKeyPairException} indicates an exception that the key pair is invalid. - * - * @author zihluwang - * @version 1.6.0 - */ -public class IllegalKeyPairException extends RuntimeException { - - /** - * Create a default exception instance. - */ - public IllegalKeyPairException() { - } - - /** - * Create an exception instance with specific message. - * - * @param message the message of the exception - */ - public IllegalKeyPairException(String message) { - super(message); - } - - /** - * Create an exception instance with specific message and cause. - * - * @param message the message of the exception - * @param cause the cause of the exception - */ - public IllegalKeyPairException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalSecretException.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalSecretException.java deleted file mode 100644 index 3ade2f2..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/IllegalSecretException.java +++ /dev/null @@ -1,54 +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.exceptions; - -/** - * {@link IllegalKeyPairException} indicates the secret to sign a JWT is illegal. - * - * @author zihluwang - * @version 1.6.0 - * @since 1.6.0 - */ -public class IllegalSecretException extends RuntimeException { - - /** - * Create a default exception instance. - */ - public IllegalSecretException() { - } - - /** - * Create an exception instance with specific message. - * - * @param message the message of the exception - */ - public IllegalSecretException(String message) { - super(message); - } - - /** - * Create an exception instance with specific message and the cause of this exception. - * - * @param message the message of the exception - * @param cause the cause of the exception - */ - public IllegalSecretException(String message, Throwable cause) { - super(message, cause); - } - -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/UnsupportedAlgorithmException.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/UnsupportedAlgorithmException.java deleted file mode 100644 index c626e40..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/UnsupportedAlgorithmException.java +++ /dev/null @@ -1,109 +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.exceptions; - -import com.onixbyte.simplejwt.TokenResolver; - -/** - * This {@code UnsupportedAlgorithmException} represents the given - * algorithm is not supported by {@link - * TokenResolver} yet. - *

- * If you want the supports to an unsupported algorithm, you could - *

    - *
  • Commit an issue at GitHub Issues or;
  • - *
  • Communicate with us on Discord Community.
  • - *
- * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public class UnsupportedAlgorithmException extends RuntimeException { - - /** - * Constructs a new {@code UnsupportedAlgorithmException} with {@code null} - * as its detail message. The cause is not initialized, and may - * subsequently be initialized by a call to {@link #initCause}. - */ - public UnsupportedAlgorithmException() { - } - - /** - * Constructs a new {@code UnsupportedAlgorithmException} with the - * specified detail message. The cause is not initialized, and may - * subsequently be initialized by a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public UnsupportedAlgorithmException(String message) { - super(message); - } - - /** - * Constructs a new {@code UnsupportedAlgorithmException} with the - * specified detail message and cause. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public UnsupportedAlgorithmException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new {@code UnsupportedAlgorithmException} with the - * specified cause and a detail message of - * {@code (cause==null ? null : cause.toString())} (which typically - * contains the class and detail message of {@code cause}). This - * constructor is useful for runtime exceptions that are little more - * than wrappers for other throwable. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.4 - */ - public UnsupportedAlgorithmException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new {@code UnsupportedAlgorithmException} with the - * specified detail message, cause, suppression enabled or disabled, and - * writable stack trace enabled or disabled. - * - * @param message the detail message. - * @param cause the cause (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or - * unknown.) - * @param enableSuppression whether suppression is enabled or disabled - * @param writableStackTrace whether the stack trace should be writable - * @since 1.0.0 - */ - public UnsupportedAlgorithmException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/WeakSecretException.java b/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/WeakSecretException.java deleted file mode 100644 index a7a57e7..0000000 --- a/simple-jwt-facade/src/main/java/com/onixbyte/simplejwt/exceptions/WeakSecretException.java +++ /dev/null @@ -1,106 +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.exceptions; - -/** - * {@code WeakSecretException} represents that your secret is too weak to be - * used in signing JWTs. - *

- * {@code WeakSecretException} will only appears that if you are using the - * implementation module {@code cn.org.codecrafters:simple-jwt-jjwt} due to - * it is implemented by {@code io.jsonwebtoken:jjwt}. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public class WeakSecretException extends RuntimeException { - - /** - * Constructs a new {@code WeakSecretException} with {@code null} as its - * detail message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - */ - public WeakSecretException() { - } - - /** - * Constructs a new {@code WeakSecretException} with the specified detail - * message. The cause is not initialized, and may subsequently be - * initialized by a call to {@link #initCause}. - * - * @param message the detail message. The detail message is saved for - * later retrieval by the {@link #getMessage()} method. - */ - public WeakSecretException(String message) { - super(message); - } - - /** - * Constructs a new {@code WeakSecretException} with the specified detail - * message and cause. - *

- * Note that the detail message associated with {@code cause} is not - * automatically incorporated in this runtime exception's detail message. - * - * @param message the detail message (which is saved for later retrieval - * by the {@link #getMessage()} method). - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.0.0 - */ - public WeakSecretException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Constructs a new {@code WeakSecretException} with the specified cause - * and a detail message of {@code (cause==null ? null : cause.toString())} - * (which typically contains the class and detail message of - * {@code cause}). This constructor is useful for runtime exceptions that - * are little more than wrappers for other throwable. - * - * @param cause the cause (which is saved for later retrieval by the - * {@link #getCause()} method). (A {@code null} value is - * permitted, and indicates that the cause is nonexistent or - * unknown.) - * @since 1.0.0 - */ - public WeakSecretException(Throwable cause) { - super(cause); - } - - /** - * Constructs a new {@code WeakSecretException} with the specified detail - * message, cause, suppression enabled or disabled, and writable - * stack trace enabled or disabled. - * - * @param message the detail message. - * @param cause the cause. (A {@code null} value is permitted, - * and indicates that the cause is nonexistent or - * unknown.) - * @param enableSuppression whether suppression is enabled or disabled - * @param writableStackTrace whether the stack trace should be writable - * @since 1.0.0 - */ - public WeakSecretException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/simple-jwt-facade/src/main/resources/logback.xml b/simple-jwt-facade/src/main/resources/logback.xml deleted file mode 100644 index 6d26440..0000000 --- a/simple-jwt-facade/src/main/resources/logback.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - ${COLOURFUL_OUTPUT} - - - - - - \ No newline at end of file diff --git a/simple-jwt-spring-boot-starter/README.md b/simple-jwt-spring-boot-starter/README.md deleted file mode 100644 index 8b3a8ca..0000000 --- a/simple-jwt-spring-boot-starter/README.md +++ /dev/null @@ -1,101 +0,0 @@ -# Module `simple-jwt-spring-boot-starter` - -## Introduction - -Module `simple-jwt-spring-boot-starter` is a lightweight and easy-to-use Spring Boot starter module that provides seamless integration with JSON Web Token (JWT) authentication in Spring Boot applications. With this starter, developers can easily configure and enable JWT-based authentication for their APIs and web applications without the need for complex manual setup. It simplifies the process of generating and validating JWTs, making it effortless to secure endpoints and implement token-based authentication in Spring Boot projects. The module is designed to be flexible, allowing developers to customize various aspects of JWT authentication to suit their specific requirements. Overall, `simple-jwt-spring-boot-starter` is a convenient solution for adding secure and efficient JWT authentication to Spring Boot applications. - -## Prerequisites - -- This whole `JDevKit` is developed by **JDK 17**, which means you have to use JDK 17 for better experience. -- You also need an implementation of any `simple-jwt-$implementation` module to make sure you can create an instance of `TokenResolver`. - -### Known Implementation - -> If you implemented one on your own, please contact us to add your artifact to this list. - -- [`cn.org.codecrafters:simple-jwt-authzero`](../simple-jwt-authzero/README.md) -- [`cn.org.codecrafters:simple-jwt-jjwt`](../simple-jwt-jjwt/README.md) - -## Installation - -### If you are using `Maven` - -It is quite simple to install this module by `Maven`. The only thing you need to do is find your `pom.xml` file in the project, then find the `` node in the `` node, and add the following codes to `` node: - -```xml - - ${implementation-builder-group-id} - simple-jwt-${any-implementation} - ${simple-jwt-${any-implementation}.version} - - - com.onixbyte - simple-jwt-spring-boot-starter - ${simple-jwt-spring-boot-starter.version} - -``` - -And run `mvn dependency:get` in your project root folder(i.e., if your `pom.xml` is located at `/path/to/your/project/pom.xml`, then your current work folder should be `/path/to/your/project`), then `Maven` will automatically download the `jar` archive from `Maven Central Repository`. This could be **MUCH EASIER** if you are using IDE(i.e., IntelliJ IDEA), the only thing you need to do is click the refresh button of `Maven`. - -If you are restricted using the Internet, and have to make `Maven` offline, you could follow the following steps. - -1. Download the `jar` file from any place you can get and transfer the `jar` files to your work computer. -2. Move the `jar` files to your local `Maven` Repository as the path of `/path/to/maven_local_repo/cn/org/codecrafters/simple-jwt-spring-boot-starter/` and `/path/to/maven_local_repo/${implementation-builder-group-seperated-by-system-seperator}/${implementation_artifact_id}`. - -### 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 '${implementation-builder-group-id}:simple-jwt-${any-implementation}:${simple-jwt-${any-implementation}.version}' -implementation 'com.onixbyte:simple-jwt-spring-boot-starter:${simple-jwt-spring-boot-starter.version}' -``` - -### If you are not using `Maven` or `Gradle` - -1. Download the `jar` file from the Internet. -2. Create a folder in your project and name it as a name you like(i.e., for me, I prefer `vendor`). -3. Put the `jar` file to the folder you just created in Step 2. -4. Add this folder to your project `classpath`. - -## Configuration - -### Configuration for a customized JWT ID Creator - -We need a `GuidCreator` instance to create JWT ID, though we did implemented a simple `GuidCreator`, but you can still customize it. - -First, please implement the `com.onixbyte.guid.GuidCreator` interface based on your own rules for generating JWT IDs. - -Then, add the instance of your own guid creator to spring container, whose name is `jtiCreator`. - -Here is a simple example which uses class `Random` to create guid. - -```java -@Bean -public GuidCreator jtiCreator() { - return new GuidCreator() { - private final Random random = new Random(); - - @Override - public Long nextId() { - return random.nextLong(); - } - }; -} -``` - -### `TokenResolver` Configuration - -| Property Name | Type | Description | -| ------------------------------------ | ---------------- | ------------------------------------------------------ | -| `code-crafters.simple-jwt.algorithm` | `TokenAlgorithm` | The algorithm used for JWT generation and validation. | -| `code-crafters.simple-jwt.issuer` | `String` | The issuer value to be included in the generated JWT. | -| `code-crafters.simple-jwt.secret` | `String` | The secret key used for JWT generation and validation. | - -## Contact - -If you have any suggestions, ideas, don't hesitate contacting us via [GitHub Issues](https://github.com/CodeCraftersCN/jdevkit/issues/new) or [Discord Community](https://discord.gg/NQK9tjcBB8). - -If you face any bugs while using our library and you are able to fix any bugs in our library, we would be happy to accept pull requests from you on [GitHub](https://github.com/CodeCraftersCN/jdevkit/compare). \ No newline at end of file diff --git a/simple-jwt-spring-boot-starter/build.gradle.kts b/simple-jwt-spring-boot-starter/build.gradle.kts deleted file mode 100644 index 8bd585b..0000000 --- a/simple-jwt-spring-boot-starter/build.gradle.kts +++ /dev/null @@ -1,142 +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(":guid")) - api(project(":simple-jwt-facade")) - api(project(":simple-jwt-authzero")) - implementation(libs.springBoot.autoconfigure) - implementation(libs.springBoot.starter.logging) - implementation(libs.springBoot.configurationProcessor) - annotationProcessor(libs.springBoot.configurationProcessor) - - testImplementation(platform(libs.junit.bom)) - testImplementation(libs.junit.jupiter) - testImplementation(libs.springBoot.starter.test) -} - -java { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - withSourcesJar() - withJavadocJar() -} - -tasks.test { - useJUnitPlatform() -} - -publishing { - publications { - create("simpleJwtSpringBootStarter") { - groupId = group.toString() - artifactId = "simple-jwt-spring-boot-starter" - version = artefactVersion - - pom { - name = "OnixByte JWT Toolbox :: Spring Boot Starter" - description = "Simple JWT all-in-one package for Spring Boot." - 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["simpleJwtSpringBootStarter"]) - } - } - - 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-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/AuthzeroTokenResolverAutoConfiguration.java b/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/AuthzeroTokenResolverAutoConfiguration.java deleted file mode 100644 index dd30bde..0000000 --- a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/AuthzeroTokenResolverAutoConfiguration.java +++ /dev/null @@ -1,119 +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.autoconfiguration; - -import com.onixbyte.guid.GuidCreator; -import com.onixbyte.simplejwt.TokenResolver; -import com.onixbyte.simplejwt.authzero.AuthzeroTokenResolver; -import com.onixbyte.simplejwt.autoconfiguration.properties.SimpleJwtProperties; -import com.auth0.jwt.interfaces.DecodedJWT; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.onixbyte.simplejwt.constants.TokenAlgorithm; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; - -/** - * {@code AuthzeroTokenResolverAutoConfiguration} is responsible for automatically configuring the - * Simple JWT library with - * {@code com.auth0:java-jwt} when used in a Spring Boot application. It provides default settings - * and configurations to ensure that the library works smoothly without requiring - * manual configuration. - *

- * This autoconfiguration class sets up the necessary beans and components required for JWT - * generation and validation. It automatically creates and configures the - * {@link AuthzeroTokenResolver} bean based on the available options and properties. - *

- * Developers using the Simple JWT library with Spring Boot do not need to explicitly configure the - * library, as the autoconfiguration takes care of setting up the necessary components and - * configurations automatically. However, developers still have the flexibility to customise the - * behavior of the library by providing their own configurations and properties. - * - * @author zihluwang - * @version 1.6.0 - * @since 1.0.0 - */ -@AutoConfiguration -@EnableConfigurationProperties(value = {SimpleJwtProperties.class}) -@ConditionalOnClass({DecodedJWT.class, AuthzeroTokenResolver.class}) -@ConditionalOnMissingBean({TokenResolver.class}) -@ConditionalOnBean(value = {GuidCreator.class}, name = "jtiCreator") -@AutoConfigureAfter(value = GuidAutoConfiguration.class) -public class AuthzeroTokenResolverAutoConfiguration { - - private final static Logger log = LoggerFactory.getLogger(AuthzeroTokenResolverAutoConfiguration.class); - - /** - * Constructs a new {@code SimpleJwtAutoConfiguration} instance with the - * provided SimpleJwtProperties. - * - * @param simpleJwtProperties a {@link SimpleJwtProperties} instance - * @param jtiCreator a creator to create ids for JSON Web Token - * @param objectMapper jackson JSON Handler - */ - @Autowired - public AuthzeroTokenResolverAutoConfiguration(SimpleJwtProperties simpleJwtProperties, - @Qualifier("jtiCreator") GuidCreator jtiCreator, - ObjectMapper objectMapper) { - this.jtiCreator = jtiCreator; - this.simpleJwtProperties = simpleJwtProperties; - this.objectMapper = objectMapper; - } - - /** - * Creates a new {@link TokenResolver} bean using {@link AuthzeroTokenResolver} if no existing - * {@link TokenResolver} bean is found. The {@link AuthzeroTokenResolver} is configured with the - * provided {@link GuidCreator}, {@code algorithm}, {@code issuer}, and {@code secret} - * properties from {@link SimpleJwtProperties}. - * - * @return the {@link TokenResolver} instance - */ - @Bean - public TokenResolver tokenResolver() { - var builder = AuthzeroTokenResolver.builder(); - - if (TokenAlgorithm.ECDSA_ALGORITHMS.contains(simpleJwtProperties.getAlgorithm())) { - builder.keyPair(simpleJwtProperties.getPublicKey(), simpleJwtProperties.getPrivateKey()) - .algorithm(simpleJwtProperties.getAlgorithm()); - } else if (TokenAlgorithm.HMAC_ALGORITHMS.contains(simpleJwtProperties.getAlgorithm())) { - builder.secret(simpleJwtProperties.getSecret()) - .algorithm(simpleJwtProperties.getAlgorithm()); - } - - builder.issuer(simpleJwtProperties.getIssuer()); - builder.jtiCreator(jtiCreator); - builder.objectMapper(objectMapper); - - return builder.build(); - } - - private final GuidCreator jtiCreator; - - private final SimpleJwtProperties simpleJwtProperties; - - private final ObjectMapper objectMapper; - -} diff --git a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/GuidAutoConfiguration.java b/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/GuidAutoConfiguration.java deleted file mode 100644 index 149aabf..0000000 --- a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/GuidAutoConfiguration.java +++ /dev/null @@ -1,59 +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.autoconfiguration; - -import com.onixbyte.guid.GuidCreator; -import com.onixbyte.simplejwt.autoconfiguration.conditions.GuidCreatorCondition; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.autoconfigure.AutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Conditional; - -import java.util.UUID; - -/** - * Autoconfiguration for injecting a {@link GuidCreator} for generating jwt id. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -@AutoConfiguration -public class GuidAutoConfiguration { - - private final static Logger log = LoggerFactory.getLogger(GuidAutoConfiguration.class); - - /** - * Default constructor. - */ - public GuidAutoConfiguration() { - } - - /** - * Create a default {@code jtiCreator} with UUID. - * - * @return UUID creator - */ - @Bean(name = "jtiCreator") - @Conditional(GuidCreatorCondition.class) - public GuidCreator jtiCreator() { - return UUID::randomUUID; - } - -} diff --git a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/conditions/GuidCreatorCondition.java b/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/conditions/GuidCreatorCondition.java deleted file mode 100644 index ff0410a..0000000 --- a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/conditions/GuidCreatorCondition.java +++ /dev/null @@ -1,66 +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.autoconfiguration.conditions; - -import com.onixbyte.guid.GuidCreator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Condition; -import org.springframework.context.annotation.ConditionContext; -import org.springframework.core.type.AnnotatedTypeMetadata; - -import java.util.Objects; - -/** - * The conditions to create bean {@code jtiCreator}. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -public class GuidCreatorCondition implements Condition { - - private final static Logger log = LoggerFactory.getLogger(GuidCreatorCondition.class); - - /** - * Default constructor. - */ - public GuidCreatorCondition() { - } - - /** - * The condition to create bean {@code jtiCreator}. - *

- * If Spring does not have a bean of type {@link GuidCreator} named {@code jtiCreator} in the - * application context, then create {@code jtiCreator}. - * - * @param context the spring application context - * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata - * class} or {@link org.springframework.core.type.MethodMetadata method} - * being checked - */ - @Override - public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - final var beanFactory = Objects.requireNonNull(context.getBeanFactory()); - var isContainJtiCreator = beanFactory.containsBean("jtiCreator"); - if (isContainJtiCreator) { - return !(beanFactory.getBean("jtiCreator") instanceof GuidCreator); - } - return true; - } -} diff --git a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/properties/SimpleJwtProperties.java b/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/properties/SimpleJwtProperties.java deleted file mode 100644 index 826d108..0000000 --- a/simple-jwt-spring-boot-starter/src/main/java/com/onixbyte/simplejwt/autoconfiguration/properties/SimpleJwtProperties.java +++ /dev/null @@ -1,170 +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.autoconfiguration.properties; - -import com.onixbyte.simplejwt.SecretCreator; -import com.onixbyte.simplejwt.autoconfiguration.AuthzeroTokenResolverAutoConfiguration; -import com.onixbyte.simplejwt.constants.TokenAlgorithm; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * {@code SimpleJwtProperties} is a configuration properties class used to store the properties - * related to Simple JWT library configurations. These properties can be configured in the - * application's properties file (e.g., application.properties) with the prefix - * "onixbyte.simple-jwt". - *

- * {@code SimpleJwtProperties} provides configuration options for the JWT algorithm, issuer, - * and secret. The properties are used by the {@link AuthzeroTokenResolverAutoConfiguration} to - * set up the necessary configurations for JWT generation and validation. - *

- * Developers can customise the JWT algorithm, issuer, and secret by setting the corresponding - * properties in the application's properties file. The {@code SimpleJwtAutoConfiguration} class - * reads these properties and uses them to create the TokenResolver bean with the - * desired configuration. - * - * @author Zihlu Wang - * @version 1.1.0 - * @since 1.0.0 - */ -@ConfigurationProperties(prefix = "onixbyte.simple-jwt") -public class SimpleJwtProperties { - - /** - * Default constructor. - */ - public SimpleJwtProperties() { - } - - /** - * The algorithm used for JWT generation and validation. Default value is - * {@link TokenAlgorithm#HS256} - */ - private TokenAlgorithm algorithm = TokenAlgorithm.HS256; - - /** - * The issuer value to be included in the generated JWT. Default value is an empty String. - */ - private String issuer = ""; - - /** - * The secret key used for JWT generation and validation. Default value is the result of call to - * {@link SecretCreator#createSecret(int, boolean, boolean, boolean)}. - */ - private String secret = SecretCreator.createSecret(32, true, true, true); - - /** - * The private key, PEM formatted. - */ - private String privateKey; - - /** - * The public key, PEM formatted - */ - private String publicKey; - - /** - * Algorithm getter. - * - * @return algorithm - */ - public TokenAlgorithm getAlgorithm() { - return algorithm; - } - - /** - * Algorithm setter. - * - * @param algorithm the algorithm - */ - public void setAlgorithm(TokenAlgorithm algorithm) { - this.algorithm = algorithm; - } - - /** - * Issuer getter. - * - * @return issuer - */ - public String getIssuer() { - return issuer; - } - - /** - * Issuer setter. - * - * @param issuer the issuer - */ - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - /** - * Secret setter. - * - * @return secret - */ - public String getSecret() { - return secret; - } - - /** - * Secret setter. - * - * @param secret the secret - */ - public void setSecret(String secret) { - this.secret = secret; - } - - /** - * Private key getter. - * - * @return private key - */ - public String getPrivateKey() { - return privateKey; - } - - /** - * Private key setter. - * - * @param privateKey private key - */ - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } - - /** - * Public key getter. - * - * @return public key - */ - public String getPublicKey() { - return publicKey; - } - - /** - * Public key setter. - * - * @param publicKey public key - */ - public void setPublicKey(String publicKey) { - this.publicKey = publicKey; - } -} - diff --git a/simple-jwt-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/simple-jwt-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports deleted file mode 100644 index a7b7bbe..0000000 --- a/simple-jwt-spring-boot-starter/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ /dev/null @@ -1,2 +0,0 @@ -com.onixbyte.simplejwt.autoconfiguration.GuidAutoConfiguration -com.onixbyte.simplejwt.autoconfiguration.AuthzeroTokenResolverAutoConfiguration \ No newline at end of file diff --git a/simple-jwt-spring-boot-starter/src/main/resources/logback.xml b/simple-jwt-spring-boot-starter/src/main/resources/logback.xml deleted file mode 100644 index fd31eac..0000000 --- a/simple-jwt-spring-boot-starter/src/main/resources/logback.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - ${COLOURFUL_OUTPUT} - - - - - - \ No newline at end of file diff --git a/version-catalogue/README.md b/version-catalogue/README.md new file mode 100644 index 0000000..c6e4105 --- /dev/null +++ b/version-catalogue/README.md @@ -0,0 +1,49 @@ +# Version Catalogue + +The **Version Catalogue** (Bill of Materials) is a Maven POM file provided by OnixByte to manage +dependency versions for the **OnixByte Toolbox**. 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 `version-catalogue` to your `pom.xml` under ``: + +```xml + + + + com.onixbyte + version-catalogue + 3.0.0 + pom + import + + + +``` + +Then reference any dependency built by OnixByte without a version. + +## Using in Gradle + +In your `build.gradle[.kts]`, apply the BOM using the `platform` dependency: + +```groovy +dependencies { + implementation platform('com.onixbyte:version-catalogue:3.0.0') + implementation 'com.onixbyte:common-toolbox' +} +``` + +If you are using Kotlin DSL: + +```kotlin +dependencies { + implementation(platform("com.onixbyte:version-catalogue:3.0.0")) + implementation("com.onixbyte:common-toolbox") +} +``` + diff --git a/devkit-bom/build.gradle.kts b/version-catalogue/build.gradle.kts similarity index 60% rename from devkit-bom/build.gradle.kts rename to version-catalogue/build.gradle.kts index e5c2ed2..5c440d3 100644 --- a/devkit-bom/build.gradle.kts +++ b/version-catalogue/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 { @@ -37,21 +43,18 @@ repositories { dependencies { constraints { - api("com.onixbyte:devkit-utils:$artefactVersion") - api("com.onixbyte:guid:$artefactVersion") - api("com.onixbyte:key-pair-loader:$artefactVersion") - api("com.onixbyte:num4j:$artefactVersion") - api("com.onixbyte:simple-jwt-facade:$artefactVersion") - api("com.onixbyte:simple-jwt-authzero:$artefactVersion") - api("com.onixbyte:simple-jwt-spring-boot-starter:$artefactVersion") + api("com.onixbyte:common-toolbox:$artefactVersion") + api("com.onixbyte:identity-generator:$artefactVersion") + api("com.onixbyte:crypto-toolbox:$artefactVersion") + api("com.onixbyte:math-toolbox:$artefactVersion") } } publishing { publications { - create("devkitBom") { + create("versionCatalogue") { groupId = group.toString() - artifactId = "devkit-bom" + artifactId = "version-catalogue" version = artefactVersion pom { @@ -92,7 +95,7 @@ publishing { from(components["javaPlatform"]) signing { - sign(publishing.publications["devkitBom"]) + sign(publishing.publications["versionCatalogue"]) } }