refactor: migrate from repo onixbyte/onixbyte-toolbox to module repos

This commit is contained in:
2026-06-02 14:01:53 +08:00
commit 812ac5e2aa
30 changed files with 2221 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
max_line_length = 100
tab_width = 4
[*.less]
indent_size = 2
[*.proto]
indent_size = 2
tab_width = 2
[*.sass]
indent_size = 2
[*.scss]
indent_size = 2
[*.vue]
indent_size = 2
tab_width = 2
[{*.bash,*.sh,*.zsh}]
indent_size = 2
tab_width = 2
[{*.default,*.yaml,*.yml}]
indent_size = 2
[{*.har,*.jsb2,*.jsb3,*.json,*.jsonc,*.postman_collection,*.postman_collection.json,*.postman_environment,*.postman_environment.json,.babelrc,.eslintrc,.prettierrc,.stylelintrc,.ws-context,jest.config}]
indent_size = 2
[{*.pb,*.textproto,*.txtpb}]
indent_size = 2
tab_width = 2
[{*.ps1,*.psd1,*.psm1}]
max_line_length = 115
+96
View File
@@ -0,0 +1,96 @@
# Publishes onixbyte-tuple to Maven Central when a version tag is pushed to main.
#
# Supported tag format: <major>.<minor>.<patch>[-suffix] (e.g. 3.3.1, 3.3.1-alpha)
name: Publish Package to Maven Central
on:
push:
tags:
- '[0-9]*.[0-9]*.[0-9]*'
jobs:
publish:
name: Build and Publish
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout
uses: actions/checkout@v4.2.2
with:
fetch-depth: 0
- name: Verify Tag is on Main Branch
run: |
if ! git merge-base --is-ancestor HEAD origin/main; then
echo "::error::Tag ${{ github.ref_name }} does not point to a commit on the main branch"
echo "Tags must be pushed after the commit is merged to main."
exit 1
fi
echo "✓ Tag ${{ github.ref_name }} is on main"
- name: Extract Version
id: version
run: |
VERSION="${{ github.ref_name }}"
echo "version=${VERSION}" >> $GITHUB_OUTPUT
echo "Version: ${VERSION}"
- name: Setup GPG TTY
run: export GPG_TTY=$(tty)
- name: Import PGP Private Key
uses: crazy-max/ghaction-import-gpg@v6.3.0
with:
gpg_private_key: ${{ secrets.GPG_PRIVATE_KEY }}
passphrase: ${{ secrets.GPG_PASSPHRASE }}
trust_level: 5
- name: Creating PGP Ring Key
run: |
mkdir -p ~/.gnupg
echo ${{ secrets.GPG_PASSPHRASE }} | gpg --batch --yes --pinentry-mode loopback --passphrase-fd 0 --export-secret-keys -o ~/.gnupg/gpg_key.ring
- name: Restore gradle.properties
env:
GRADLE_PROPERTIES: ${{ secrets.GRADLE_PROPERTIES }}
shell: bash
run: |
mkdir -p ~/.gradle/
echo "GRADLE_USER_HOME=${HOME}/.gradle" >> $GITHUB_ENV
echo "${GRADLE_PROPERTIES}" > ~/.gradle/gradle.properties
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: "17"
distribution: "corretto"
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4.4.1
- name: Grant Execution Authority to Gradlew
run: chmod +x ./gradlew
- name: Build with Gradle
env:
VERSION: ${{ steps.version.outputs.version }}
run: ./gradlew build "-PartefactVersion=${VERSION}"
- name: List Output Items
run: ls -l ./build/libs
- name: Publish to Maven Central
env:
VERSION: ${{ steps.version.outputs.version }}
run: ./gradlew publish "-PartefactVersion=${VERSION}"
- name: Create Deployment on Central Publisher Portal
run: |
curl --fail -X 'POST' \
'https://ossrh-staging-api.central.sonatype.com/manual/upload/defaultRepository/com.onixbyte?publishing_type=user_managed' \
-H 'accept: */*' \
-H 'Authorization: Bearer ${{ secrets.MAVEN_PORTAL_TOKEN }}' \
-d ''
+42
View File
@@ -0,0 +1,42 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
### Gradle ###
.gradle
+62
View File
@@ -0,0 +1,62 @@
# Code of Conduct
## 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.
## Our Standards
Examples of behaviour that contributes to creating a positive environment include:
- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
Examples of unacceptable behaviour by participants include:
- The use of sexualised language or imagery, and unwelcome sexual attention or advances
- 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
- 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 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.
## Enforcement
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.
## 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/
+61
View File
@@ -0,0 +1,61 @@
# 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.
## Getting Started
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.
```shell
./gradlew build
```
## 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.
## 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.
## Commit Messages
We require that commit messages follow this structure:
```text
type[(scope)]: subject
[body]
[BREAKING CHANGE: breaking changes]
```
This format helps in auto-generating changelogs and understanding the purpose behind changes.
## Submitting Contributions
1. Fork the repository.
2. Create a branch: `git checkout -b feature/my-new-feature` or `git checkout -b hotfix/my-fix`.
3. Make your changes and commit them.
4. Push to the branch: `git push origin feature/my-new-feature`.
5. Create a Pull Request with a succinct subject and a detailed body.
## Testing
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 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.
+21
View File
@@ -0,0 +1,21 @@
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.
+113
View File
@@ -0,0 +1,113 @@
# Crypto Toolbox
Crypto Toolbox provides methods to simplify your codes on key pairs.
## ECDSA-based algorithm
### Generate key pair
#### Generate private key
Generate a private key by `genpkey` command provided by OpenSSL:
```shell
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec_private_key.pem
```
The output of this command is a file called `ec_private_key.pem` and its content looks like the
following:
```text
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
+PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
-----END PRIVATE KEY-----
```
#### Generate public key by private key
Export public key from private key with `ec` command provided by OpenSSL:
```shell
openssl ec -in ec_private_key.pem -pubout -out ec_public_key.pem
```
The output of this command is a file called `ec_public_key.pem` and its content looks like the
following:
```text
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZAOxkWNouIIPKsdF1YgF1D/XD8Pa
ZyYNcH60ONRWjMqlQXozWMb2i7WphKxf8kopp42nzCflWQod+JQY+hM/EQ==
-----END PUBLIC KEY-----
```
## RSA-based algorithm
### Generate key pair
#### Generate private key
Generate a private key by `genpkey` command provided by OpenSSL:
```shell
openssl genpkey -algorithm RSA -out rsa_private_key.pem -pkeyopt rsa_keygen_bits:2048
```
The output of this command is a file called `rsa_private_key.pem` and its content looks like the
following:
```text
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD4VIFYJFMAs15j
J3V3IicHd7sI2TIFqTZME40zlOlVAlPKLZmTQvZFLNgaUAAsvPi5i1DR2ywwK6Al
BfnwVnzvmDXC5mKHOz4oxOQVA6Nlp2yVaQMzidmfYNSkMtcv/4HRPsatc7K/M5l6
pCP20DVRjkikBdIy8e9w+x6BrIFp5Q8PZc/X2BGNAUMMYACdeYH5R/A0CxqkND13
esc4gkynMOrvZrZGHCz51usfSCqyDWWwsN+GG6LYWia4GkNlS0erQnP8gS93dfjl
e96BIfy3z7Iv+kUrf5ikNW2P8jMxLAv6LO+dcUAu9k477wIAF7Iq5KMuH/otsDOu
+h+2qXmBAgMBAAECggEAdRqcmC0g+y6arxV3fkObthjPGYAa57KBCWUa7B0n30+m
pavVRS2Jpttb2SSqwG4ouI6rARti/iBEd9EWqTCP4AieKZetFOpqCJ24lPRPRGus
d9S6jr5N4qut+vSCp37NABijZj4uJ540nTH0R7qtuhTnynl4Q0/1wwiYvTvVF1Lg
dn+I/8aRbshwDhdAOWOUe6GL7/eaCYgN8/UmlKIpp8tg0w2iWxbaFiR7gZiM41LA
M6SXXfcCas+ZVXsGbzQ3SNiVurCGuuRNcCScXS3/WoEDIb3cNtp49iOmQS+nmEoo
wh4uiEd+0+BrzxngS4o5+mKnHJnwgY0+veGVYLMR5QKBgQD9WKQmevMDU5c+NPq9
8jaR457Fuxq1gwzeFNJdWfOc/K2LEWh+nFNFCb++EboEj6FdxWaWNMxbrmJps5gs
EoBUYy/Tl7UycDqDfiYLmDdTsf2pVjjh9jaIADiLcJ8S6wwJMZKub7Tp8UVkenAl
535MqShLUC11Y7VxLb3Tsll4XwKBgQD67mm6iCmshr/eszPfNE3ylZ+PiNa7nat7
N7lQzBIiRJflT1kmVidC5gE+jASqH728ChkZZKxbHsjxpmWdAhLOITdXoTB4sDsd
wtV1lxkXxK9FnrpFvO3y1wZ/QsD3Z2KXxHYZqawkUETO9F3nqAXW0b2GDar5Qiyo
J3Tx/43aHwKBgDC0NMJtCoDONhowZy/S+6iqQKC0qprQec3L5PErVMkOTnKYwyTr
+pogGKt6ju9HiXcUdvdTaSIK8UJu00dNuzv94XjlBmGO78DNpJTAC4rcge5m9AKE
qdEVcclkukARzbuKuy8rrHT4/CUn4J141m/4aRWpcUPLCluato6XD9ozAoGBANvf
JhOFFgcPd3YazfvpZ9eE1XA+tfFlYYmxNRcgCU+vjO0oDvSxjutmgHae18N91pG6
w21lskSRf/+GDwl5dKLbphOJsOA/gz07qDDGOf2CoRW+1Hcg6drcINxH0K+4DkLv
qZApBSY4k2JH6zR+HMeztn6M4WBRZLHfCPC3PUN/AoGAA3AoHbLTZvqMIKSDkP4Y
U/tTsSFDY4aYo7LG/jk8af3oPU3KyGh4ZFBd6aMmXbS8f8FjvmrM+/e+y9OOGAlq
iOl0hYrs5cJSMLW6i4KnJYuYbMkgmk3bN2t9apu64xKR94gbPrI6AGnPZp+iIzp0
hXKe4HcuhQ3G0a2hjayiQ84=
-----END PRIVATE KEY-----
```
#### Generate public key by private key
Export public key from private key by OpenSSL:
```shell
openssl pkey -in rsa_private_key.pem -pubout -out rsa_public_key.pem
```
The output of this command is a file called `rsa_public_key.pem` and its content looks like the
following:
```text
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+FSBWCRTALNeYyd1dyIn
B3e7CNkyBak2TBONM5TpVQJTyi2Zk0L2RSzYGlAALLz4uYtQ0dssMCugJQX58FZ8
75g1wuZihzs+KMTkFQOjZadslWkDM4nZn2DUpDLXL/+B0T7GrXOyvzOZeqQj9tA1
UY5IpAXSMvHvcPsegayBaeUPD2XP19gRjQFDDGAAnXmB+UfwNAsapDQ9d3rHOIJM
pzDq72a2Rhws+dbrH0gqsg1lsLDfhhui2FomuBpDZUtHq0Jz/IEvd3X45XvegSH8
t8+yL/pFK3+YpDVtj/IzMSwL+izvnXFALvZOO+8CABeyKuSjLh/6LbAzrvoftql5
gQIDAQAB
-----END PUBLIC KEY-----
```
+135
View File
@@ -0,0 +1,135 @@
/*
* Copyright (c) 2024-2026 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.
*/
import java.net.URI
plugins {
java
id("java-library")
id("maven-publish")
id("signing")
}
val artefactVersion: String by project
version = artefactVersion
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
repositories {
mavenCentral()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.withType<Jar> {
exclude("logback.xml")
}
dependencies {
compileOnly(libs.slf4j)
implementation(libs.logback)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
publishing {
publications {
create<MavenPublication>("cryptoToolbox") {
groupId = group.toString()
artifactId = "crypto-toolbox"
version = artefactVersion
pom {
name = "OnixByte Crypto Toolbox"
description =
"This module can easily load key pairs from a PEM content."
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 = "real@zihluwang.me"
timezone = "Asia/Hong_Kong"
}
developer {
id = "siujamo"
name = "Siu Jam'o"
email = "jamo.siu@gmail.com"
timezone = "Asia/Shanghai"
}
}
}
from(components["java"])
signing {
setRequired(project.hasProperty("signing.keyId"))
sign(publishing.publications["cryptoToolbox"])
}
}
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()
}
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
#
# 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.
#
artefactVersion=3.4.0
projectUrl=https://github.com/onixbyte/onixbyte-tuple
projectGithubUrl=git@github.com:onixbyte/onixbyte-tuple.git
licenseName=MIT
licenseUrl=
+10
View File
@@ -0,0 +1,10 @@
[versions]
slf4j = "2.0.17"
logback = "1.5.26"
junit = "5.11.4"
[libraries]
slf4j = { group = "org.slf4j", name = "slf4j-api", version.ref = "slf4j" }
logback = { group = "ch.qos.logback", name = "logback-classic", version.ref = "logback" }
junit-bom = { group = "org.junit", name = "junit-bom", version.ref = "junit" }
junit-jupiter = { group = "org.junit.jupiter", name = "junit-jupiter", version.ref = "junit" }
Binary file not shown.
+7
View File
@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored
+252
View File
@@ -0,0 +1,252 @@
#!/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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
+94
View File
@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@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
@rem https://www.apache.org/licenses/LICENSE-2.0
@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
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+23
View File
@@ -0,0 +1,23 @@
/*
* 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.
*/
rootProject.name = "onixbyte-crypto-toolbox"
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2024-2026 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);
}
@@ -0,0 +1,83 @@
/*
* Copyright (c) 2024-2026 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.
* <p>
* 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.
* <p>
* 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.");
}
}
@@ -0,0 +1,95 @@
/*
* Copyright (c) 2024-2026 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.
* <p>
* 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.
* <p>
* 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);
}
}
}
@@ -0,0 +1,159 @@
/*
* Copyright (c) 2024-2026 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.PublicKeyLoader;
import com.onixbyte.crypto.exception.KeyLoadingException;
import com.onixbyte.crypto.util.CryptoUtil;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.*;
import java.util.Base64;
import java.util.HashSet;
import java.util.Set;
/**
* A class responsible for loading public ECDSA keys from PEM formatted text.
* <p>
* 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.
* <p>
* 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 ECPublicKeyLoader implements PublicKeyLoader {
/**
* Supported curves.
*/
public static final Set<String> SUPPORTED_CURVES = new HashSet<>(Set.of(
"secp256r1", "secp384r1", "secp521r1", "secp224r1"
));
private final KeyFactory keyFactory;
private final Base64.Decoder decoder;
/**
* Initialise a key loader for EC-based algorithms.
*/
public ECPublicKeyLoader() {
try {
this.keyFactory = KeyFactory.getInstance("EC");
this.decoder = Base64.getDecoder();
} catch (NoSuchAlgorithmException e) {
throw new KeyLoadingException(e);
}
}
/**
* Load public key from pem-formatted key text.
*
* @param pemKeyText pem-formatted key text
* @return loaded private key
* @throws KeyLoadingException if the generated key is not a {@link ECPrivateKey} instance,
* or EC Key Factory is not loaded, or key spec is invalid
*/
@Override
public ECPublicKey loadPublicKey(String pemKeyText) {
try {
pemKeyText = CryptoUtil.getRawContent(pemKeyText);
var keyBytes = decoder.decode(pemKeyText);
var spec = new X509EncodedKeySpec(keyBytes);
var key = keyFactory.generatePublic(spec);
if (key instanceof ECPublicKey publicKey) {
return publicKey;
} else {
throw new KeyLoadingException("Unable to load public key from pem-formatted key text.");
}
} catch (InvalidKeySpecException e) {
throw new KeyLoadingException("Key spec is invalid.", e);
}
}
/**
* Loads an EC public key from the given hexadecimal x and y coordinates alongside the curve name.
* <p>
* This method converts the hexadecimal string representations of the EC point coordinates into {@link BigInteger}
* instances, then constructs an {@link ECPoint} and retrieves the corresponding {@link ECParameterSpec} for the
* named curve. Subsequently, it utilises the {@link KeyFactory} to generate an {@link ECPublicKey}.
* <p>
* Only curves listed in {@link #SUPPORTED_CURVES} are supported. Should the specified curve name be unsupported,
* or if key construction fails due to invalid parameters or unsupported algorithms, a {@link KeyLoadingException}
* will be thrown.
*
* @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 {@link ECPublicKey} generated from the specified coordinates and curve
* @throws KeyLoadingException if the curve is unsupported or key generation fails
*/
@Override
public ECPublicKey loadPublicKey(String xHex, String yHex, String curveName) {
if (!SUPPORTED_CURVES.contains(curveName)) {
throw new KeyLoadingException("Given curve is not supported yet.");
}
try {
// Convert hex string coordinates to BigInteger
var x = new BigInteger(xHex, 16);
var y = new BigInteger(yHex, 16);
// Create ECPoint with (x, y)
var ecPoint = new ECPoint(x, y);
// Get EC parameter spec for the named curve
var parameters = AlgorithmParameters.getInstance("EC");
parameters.init(new ECGenParameterSpec(curveName));
var ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
// Create ECPublicKeySpec with point and curve params
var pubSpec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
// Generate public key using KeyFactory
var publicKey = keyFactory.generatePublic(pubSpec);
if (publicKey instanceof ECPublicKey ecPublicKey) {
return ecPublicKey;
} else {
throw new KeyLoadingException("Cannot load EC public key with given x, y and curve name.");
}
} catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) {
throw new KeyLoadingException("Cannot load EC public key with given x, y and curve name.", e);
}
}
}
@@ -0,0 +1,107 @@
/*
* Copyright (c) 2024-2026 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.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.*;
import java.util.Base64;
/**
* A class responsible for loading private RSA keys from PEM formatted text.
* <p>
* 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.
* <p>
* 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}.
* <p>
* 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.
* <p>
* 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);
}
}
}
@@ -0,0 +1,142 @@
/*
* Copyright (c) 2024-2026 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.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.RSAPublicKey;
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 public RSA keys from PEM formatted text.
* <p>
* 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.
* <p>
* 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 RSAPublicKeyLoader implements PublicKeyLoader {
private final Base64.Decoder decoder;
private final Base64.Decoder urlDecoder;
private final KeyFactory keyFactory;
/**
* Constructs an instance of {@code RsaKeyLoader}.
* <p>
* 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 RSAPublicKeyLoader() {
try {
this.decoder = Base64.getDecoder();
this.urlDecoder = Base64.getUrlDecoder();
this.keyFactory = KeyFactory.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
throw new KeyLoadingException(e);
}
}
/**
* Loads an RSA public key from a given PEM formatted key text.
* <p>
* This method extracts the raw key content from the provided PEM text, decodes the
* Base64-encoded content, and generates an instance of {@link RSAPublicKey}. If the key cannot
* be loaded due to invalid specifications or types, a {@link KeyLoadingException} is thrown.
*
* @param pemKeyText the PEM formatted public key text
* @return an instance of {@link RSAPublicKey}
* @throws KeyLoadingException if the key loading process encounters an error
*/
@Override
public RSAPublicKey loadPublicKey(String pemKeyText) {
// Extract the raw key content
var rawKeyContent = CryptoUtil.getRawContent(pemKeyText);
// Decode the Base64-encoded content
var keyBytes = decoder.decode(rawKeyContent);
// Create an X509EncodedKeySpec from the decoded bytes
var keySpec = new X509EncodedKeySpec(keyBytes);
// Get an RSA KeyFactory and generate the public key
try {
var _key = keyFactory.generatePublic(keySpec);
if (_key instanceof RSAPublicKey key) {
return key;
} else {
throw new KeyLoadingException("Unable to load public key from pem-formatted key text.");
}
} catch (InvalidKeySpecException e) {
throw new KeyLoadingException("Key spec is invalid.", e);
}
}
/**
* Get the public key with given modulus and public exponent.
*
* @param modulus the modulus
* @param exponent the public exponent
* @return generated public key object from the provided key specification
* @see KeyFactory#getInstance(String)
* @see KeyFactory#generatePublic(KeySpec)
*/
@Override
public RSAPublicKey loadPublicKey(String modulus, String exponent) {
try {
var _modulus = new BigInteger(1, urlDecoder.decode(modulus));
var _exponent = new BigInteger(1, urlDecoder.decode(exponent));
var keySpec = new RSAPublicKeySpec(_modulus, _exponent);
var kf = KeyFactory.getInstance("RSA");
if (kf.generatePublic(keySpec) instanceof RSAPublicKey rsaPublicKey) {
return rsaPublicKey;
} else {
throw new KeyLoadingException("Cannot generate RSA public key with given modulus and exponent.");
}
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new KeyLoadingException("Cannot generate RSA public key with given modulus and exponent.", e);
}
}
}
@@ -0,0 +1,100 @@
/*
* Copyright (c) 2024-2026 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.exception;
/**
* The {@code KeyLoadingException} class represents an exception that is thrown when there is an
* error loading cryptographic keys. This exception can be used to indicate various issues such as
* invalid key specifications, unsupported key algorithms, or other key loading errors.
* <p>
* This class extends {@link RuntimeException}, allowing it to be thrown without being declared in
* a method's {@code throws} clause.
* </p>
*
* <p><b>Example usage:</b></p>
* <pre>{@code
* try {
* PrivateKeyLoader keyLoader = new ECPrivateKeyLoader();
* ECPrivateKey privateKey = keyLoader.loadPrivateKey(pemPrivateKey);
* } catch (KeyLoadingException e) {
* // Handle the exception
* e.printStackTrace();
* }
* }</pre>
*
* @author zihluwang
* @version 3.0.0
*/
public class KeyLoadingException extends RuntimeException {
/**
* Creates a new instance of {@code KeyLoadingException} without a specific message or cause.
*/
public KeyLoadingException() {
}
/**
* Creates a new instance of {@code KeyLoadingException} with the specified detail message.
*
* @param message the detail message
*/
public KeyLoadingException(String message) {
super(message);
}
/**
* Creates a new instance of {@code KeyLoadingException} with the specified detail message
* and cause.
*
* @param message the detail message
* @param cause the cause of this exception
*/
public KeyLoadingException(String message, Throwable cause) {
super(message, cause);
}
/**
* Creates a new instance of {@code KeyLoadingException} with the specified cause.
*
* @param cause the cause of this exception
*/
public KeyLoadingException(Throwable cause) {
super(cause);
}
/**
* Constructs a new exception 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 of this exception
* @param enableSuppression whether suppression is enabled or disabled
* @param writableStackTrace whether the stack trace should be writable
*/
public KeyLoadingException(String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,98 @@
/*
* Copyright (c) 2024-2026 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;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* 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.
*
* <p>
* 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-----", "")
.replace("\n", "");
}
/**
* Computes a Hash-based Message Authentication Code (HMAC) using the SHA-256 algorithm.
* <p>
* The input payload and secret key are both processed using the {@code UTF-8} charset
* to guarantee consistent results across different operating system environments.
* The final byte array output is converted into a lower-case hexadecimal string.
*
* @param payload the raw string data or message content to be authenticated
* @param secret the secret key used to sign the payload
* @return a lower-case hexadecimal string representing the computed HMAC-SHA256 signature
* @throws NoSuchAlgorithmException if the HmacSHA256 algorithm is not available in the environment
* @throws InvalidKeyException if the provided secret key is inappropriate for
* initialising the MAC
*/
public static String hmacSha256(
String payload,
String secret
) throws NoSuchAlgorithmException, InvalidKeyException {
var secretKeySpec = new SecretKeySpec(
secret.getBytes(StandardCharsets.UTF_8),
"HmacSHA256"
);
var mac = Mac.getInstance("HmacSHA256");
mac.init(secretKeySpec);
var rawHmac = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8));
return EncodingUtil.bytesToHex(rawHmac);
}
}
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2024-2026 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;
import java.util.HexFormat;
/**
* Utility class for handling various data encoding and formatting operations.
* <p>
* This class provides helper methods to convert raw binary data into standardised
* string representations (such as hexadecimal format) commonly required for
* cryptographic verification, logging, and data transmission.
* <p>
* This utility class is stateless and thread-safe.
*
* @author siujamo
*/
public class EncodingUtil {
/**
* Converts an array of bytes into its corresponding hexadecimal string representation.
* <p>
* Each byte is converted to a two-digit hex string. If the resulting hex value
* is a single digit (i.e., less than 16), a leading '0' is automatically prepended
* to ensure a consistent and uniform format throughout the output string.
*
* @param bytes the byte array to be converted, typically the raw output of a cryptographic hash
* @return a lower-case hexadecimal string representing the input bytes
*/
public static String bytesToHex(byte[] bytes) {
return HexFormat.of().formatHex(bytes);
}
}
@@ -0,0 +1,270 @@
/*
* Copyright (c) 2024-2026 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;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;
/**
* The {@code HashUtil} class provides convenient methods for calculating various hash functions on
* strings, including MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. It allows developers
* to easily obtain the hash value of a given string using different algorithms.
* <p>
* Example usage:
* <pre>
* // Perform MD2 hash operation
* String md2Hash = HashUtil.md2("someString");
*
* // Perform MD5 hash operation
* String md5Hash = HashUtil.md5("someString");
*
* // Perform SHA-1 hash operation
* String sha1Hash = HashUtil.sha1("someString");
*
* // Perform SHA-224 hash operation
* String sha224Hash = HashUtil.sha224("someString");
*
* // Perform SHA-256 hash operation
* String sha256Hash = HashUtil.sha256("someString");
*
* // Perform SHA-384 hash operation
* String sha384Hash = HashUtil.sha384("someString");
*
* // Perform SHA-512 hash operation
* String sha512Hash = HashUtil.sha512("someString");
* </pre>
* The above examples demonstrate how to use the {@code HashUtil} class to calculate hash values
* for a given string using different algorithms.
* <p>
* The hash functions provided by the {@link HashUtil} are one-way hash functions, meaning the
* original data cannot be retrieved from the hash value. These hash functions are commonly used
* for data integrity checks and password storage, but they should not be used for
* encryption purposes.
*
* @author zihluwang
* @version 3.0.0
* @see MessageDigest
*/
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.
*
* @param value the string to calculate with the MD2 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the MD2 hash value as a hexadecimal string
*/
public static String md2(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("MD2", value, charset);
}
/**
* Calculates the MD2 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the MD2 algorithm
* @return the MD2 hash value as a hexadecimal string
*/
public static String md2(String value) {
return hash("MD2", value, StandardCharsets.UTF_8);
}
/**
* Calculates the MD5 hash value of the specified string using the given charset.
*
* @param value the string to calculate with the MD5 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the MD5 hash value as a hexadecimal string
*/
public static String md5(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("MD5", value, charset);
}
/**
* Calculates the MD5 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the MD5 algorithm
* @return the MD5 hash value as a hexadecimal string
*/
public static String md5(String value) {
return hash("MD5", value, StandardCharsets.UTF_8);
}
/**
* Calculates the SHA-1 hash value of the specified string using the given charset.
*
* @param value the string to calculate with the SHA-1 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the SHA-1 hash value as a hexadecimal string
*/
public static String sha1(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("SHA-1", value, charset);
}
/**
* Calculates the SHA-1 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the SHA-1 algorithm
* @return the SHA-1 hash value as a hexadecimal string
*/
public static String sha1(String value) {
return hash("SHA-1", value, StandardCharsets.UTF_8);
}
/**
* Calculates the SHA-224 hash value of the specified string using the given charset.
*
* @param value the string to calculate with the SHA-225 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the SHA-224 hash value as a hexadecimal string
*/
public static String sha224(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("SHA-224", value, charset);
}
/**
* Calculates the SHA-224 hash value of the specified string using the
* UTF-8 charset.
*
* @param value the string to calculate with the SHA-224 algorithm
* @return the SHA-224 hash value as a hexadecimal string
*/
public static String sha224(String value) {
return hash("SHA-224", value, StandardCharsets.UTF_8);
}
/**
* Calculates the SHA-256 hash value of the specified string using the
* given charset.
*
* @param value the string to calculate with the SHA-256 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the SHA-256 hash value as a hexadecimal string
*/
public static String sha256(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("SHA-256", value, charset);
}
/**
* Calculates the SHA-256 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the SHA-256 algorithm
* @return the SHA-256 hash value as a hexadecimal string
*/
public static String sha256(String value) {
return hash("SHA-256", value, StandardCharsets.UTF_8);
}
/**
* Calculates the SHA-384 hash value of the specified string using the given charset.
*
* @param value the string to calculate with the SHA-384 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the SHA-384 hash value as a hexadecimal string
*/
public static String sha384(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("SHA-384", value, charset);
}
/**
* Calculates the SHA-384 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the SHA-384 algorithm
* @return the SHA-384 hash value as a hexadecimal string
*/
public static String sha384(String value) {
return hash("SHA-384", value, StandardCharsets.UTF_8);
}
/**
* Calculates the SHA-512 hash value of the specified string using the given charset.
*
* @param value the string to calculate with the SHA-512 algorithm
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the SHA-512 hash value as a hexadecimal string
*/
public static String sha512(String value, Charset charset) {
charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
return hash("SHA-512", value, charset);
}
/**
* Calculates the SHA-512 hash value of the specified string using the UTF-8 charset.
*
* @param value the string to calculate with the SHA-512 algorithm
* @return the SHA-512 hash value as a hexadecimal string
*/
public static String sha512(String value) {
return hash("SHA-512", value, StandardCharsets.UTF_8);
}
/**
* Calculates the hash value of the specified string using the specified
* algorithm and charset.
*
* @param method the hash algorithm to use
* @param value the string to calculate the hash value for
* @param charset the charset to use for encoding the string (default is UTF-8 if null)
* @return the hash value as a hexadecimal string, or an empty string if the algorithm is
* not available
* @throws RuntimeException if an unknown algorithm name is provided (should not occur under
* controlled usage)
*/
private static String hash(String method, String value, Charset charset) {
try {
var messageDigest = MessageDigest.getInstance(method);
messageDigest.update(value.getBytes(charset));
var bytes = messageDigest.digest();
var builder = new StringBuilder();
for (var b : bytes) {
var str = Integer.toHexString(b & 0xff);
if (str.length() == 1) {
builder.append(0);
}
builder.append(str);
}
return builder.toString();
} catch (NoSuchAlgorithmException ignored) {
// This should not occur under controlled usage
// Only trusted algorithms are allowed
return "";
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2024-2026 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.
-->
<configuration>
<property name="COLOURFUL_OUTPUT"
value="%black(%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK}) %highlight(%-5level) %black(---) %black([%10.10t]) %cyan(%-20.20logger{20}) %black(:) %msg%n"/>
<property name="STANDARD_OUTPUT"
value="%date{'dd MMM, yyyy HH:mm:ss', Asia/Hong_Kong, en-UK} %-5level %black(---) [%10.10t] %-20.20logger{20} : %msg%n"/>
<statusListener class="ch.qos.logback.core.status.NopStatusListener"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${COLOURFUL_OUTPUT}</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
+5
View File
@@ -0,0 +1,5 @@
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgs79JlARgXEf6EDV7
+PHQCTHEMtqIoHOy1GZ1+ynQJ6yhRANCAARkA7GRY2i4gg8qx0XViAXUP9cPw9pn
Jg1wfrQ41FaMyqVBejNYxvaLtamErF/ySimnjafMJ+VZCh34lBj6Ez8R
-----END PRIVATE KEY-----
+4
View File
@@ -0,0 +1,4 @@
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEZAOxkWNouIIPKsdF1YgF1D/XD8Pa
ZyYNcH60ONRWjMqlQXozWMb2i7WphKxf8kopp42nzCflWQod+JQY+hM/EQ==
-----END PUBLIC KEY-----
+28
View File
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQD4VIFYJFMAs15j
J3V3IicHd7sI2TIFqTZME40zlOlVAlPKLZmTQvZFLNgaUAAsvPi5i1DR2ywwK6Al
BfnwVnzvmDXC5mKHOz4oxOQVA6Nlp2yVaQMzidmfYNSkMtcv/4HRPsatc7K/M5l6
pCP20DVRjkikBdIy8e9w+x6BrIFp5Q8PZc/X2BGNAUMMYACdeYH5R/A0CxqkND13
esc4gkynMOrvZrZGHCz51usfSCqyDWWwsN+GG6LYWia4GkNlS0erQnP8gS93dfjl
e96BIfy3z7Iv+kUrf5ikNW2P8jMxLAv6LO+dcUAu9k477wIAF7Iq5KMuH/otsDOu
+h+2qXmBAgMBAAECggEAdRqcmC0g+y6arxV3fkObthjPGYAa57KBCWUa7B0n30+m
pavVRS2Jpttb2SSqwG4ouI6rARti/iBEd9EWqTCP4AieKZetFOpqCJ24lPRPRGus
d9S6jr5N4qut+vSCp37NABijZj4uJ540nTH0R7qtuhTnynl4Q0/1wwiYvTvVF1Lg
dn+I/8aRbshwDhdAOWOUe6GL7/eaCYgN8/UmlKIpp8tg0w2iWxbaFiR7gZiM41LA
M6SXXfcCas+ZVXsGbzQ3SNiVurCGuuRNcCScXS3/WoEDIb3cNtp49iOmQS+nmEoo
wh4uiEd+0+BrzxngS4o5+mKnHJnwgY0+veGVYLMR5QKBgQD9WKQmevMDU5c+NPq9
8jaR457Fuxq1gwzeFNJdWfOc/K2LEWh+nFNFCb++EboEj6FdxWaWNMxbrmJps5gs
EoBUYy/Tl7UycDqDfiYLmDdTsf2pVjjh9jaIADiLcJ8S6wwJMZKub7Tp8UVkenAl
535MqShLUC11Y7VxLb3Tsll4XwKBgQD67mm6iCmshr/eszPfNE3ylZ+PiNa7nat7
N7lQzBIiRJflT1kmVidC5gE+jASqH728ChkZZKxbHsjxpmWdAhLOITdXoTB4sDsd
wtV1lxkXxK9FnrpFvO3y1wZ/QsD3Z2KXxHYZqawkUETO9F3nqAXW0b2GDar5Qiyo
J3Tx/43aHwKBgDC0NMJtCoDONhowZy/S+6iqQKC0qprQec3L5PErVMkOTnKYwyTr
+pogGKt6ju9HiXcUdvdTaSIK8UJu00dNuzv94XjlBmGO78DNpJTAC4rcge5m9AKE
qdEVcclkukARzbuKuy8rrHT4/CUn4J141m/4aRWpcUPLCluato6XD9ozAoGBANvf
JhOFFgcPd3YazfvpZ9eE1XA+tfFlYYmxNRcgCU+vjO0oDvSxjutmgHae18N91pG6
w21lskSRf/+GDwl5dKLbphOJsOA/gz07qDDGOf2CoRW+1Hcg6drcINxH0K+4DkLv
qZApBSY4k2JH6zR+HMeztn6M4WBRZLHfCPC3PUN/AoGAA3AoHbLTZvqMIKSDkP4Y
U/tTsSFDY4aYo7LG/jk8af3oPU3KyGh4ZFBd6aMmXbS8f8FjvmrM+/e+y9OOGAlq
iOl0hYrs5cJSMLW6i4KnJYuYbMkgmk3bN2t9apu64xKR94gbPrI6AGnPZp+iIzp0
hXKe4HcuhQ3G0a2hjayiQ84=
-----END PRIVATE KEY-----
+9
View File
@@ -0,0 +1,9 @@
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+FSBWCRTALNeYyd1dyIn
B3e7CNkyBak2TBONM5TpVQJTyi2Zk0L2RSzYGlAALLz4uYtQ0dssMCugJQX58FZ8
75g1wuZihzs+KMTkFQOjZadslWkDM4nZn2DUpDLXL/+B0T7GrXOyvzOZeqQj9tA1
UY5IpAXSMvHvcPsegayBaeUPD2XP19gRjQFDDGAAnXmB+UfwNAsapDQ9d3rHOIJM
pzDq72a2Rhws+dbrH0gqsg1lsLDfhhui2FomuBpDZUtHq0Jz/IEvd3X45XvegSH8
t8+yL/pFK3+YpDVtj/IzMSwL+izvnXFALvZOO+8CABeyKuSjLh/6LbAzrvoftql5
gQIDAQAB
-----END PUBLIC KEY-----