feat: added key pair loader

This commit is contained in:
zihluwang
2024-07-25 21:56:15 +08:00
parent cc5ed4beec
commit f29be80773
8 changed files with 424 additions and 41 deletions
+99
View File
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2024-2024 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
val buildGroupId: String by project
val buildVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
group = buildGroupId
version = buildVersion
dependencies {
implementation(project(":devkit-core"))
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("keyPairLoader") {
groupId = buildGroupId
artifactId = "key-pair-loader"
version = buildVersion
pom {
name = "Key Pair Loader"
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/JDevKit.git"
developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["keyPairLoader"])
}
}
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()
}
}
}
}
}
@@ -0,0 +1,74 @@
/*
* Copyright (C) 2024-2024 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.keypairloader;
import com.onixbyte.keypairloader.exception.KeyLoadingException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Optional;
/**
* KeyLoader can load key pairs from PEM formated content.
*
* @author zihluwang
* @version 1.6.0
* @since 1.6.0
*/
@Slf4j
public class KeyLoader {
/**
* Private constructor prevents from being initialised.
*/
private KeyLoader() {
}
public ECPrivateKey loadEcdsaPrivateKey(String pemKeyText) {
return Optional.ofNullable(pemKeyText)
.map(Base64.getDecoder()::decode)
.map(PKCS8EncodedKeySpec::new)
.map((keySpec) -> {
try {
var kf = KeyFactory.getInstance("EC");
return kf.generatePrivate(keySpec);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new KeyLoadingException("Unable to load key from text.", e);
}
}).map((publicKey) -> {
if (publicKey instanceof ECPrivateKey privateKey) {
return privateKey;
}
return null;
})
.orElse(null);
}
// public ECPublicKey loadEcdsaPublicKey(String pemKeyText) {
//
// }
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2024-2024 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.keypairloader.exception;
public class KeyLoadingException extends RuntimeException {
public KeyLoadingException() {
}
public KeyLoadingException(String message) {
super(message);
}
public KeyLoadingException(String message, Throwable cause) {
super(message, cause);
}
public KeyLoadingException(Throwable cause) {
super(cause);
}
public KeyLoadingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (C) 2024-2024 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.
-->
<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>
@@ -0,0 +1,29 @@
/*
* Copyright (C) 2024-2024 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.keypairloader;
import org.junit.jupiter.api.Test;
public class KeyPairLoaderTest {
@Test
public void test() {
}
}
+99
View File
@@ -0,0 +1,99 @@
/*
* Copyright (C) 2024-2024 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
val buildGroupId: String by project
val buildVersion: String by project
val projectUrl: String by project
val projectGithubUrl: String by project
val licenseName: String by project
val licenseUrl: String by project
group = buildGroupId
version = buildVersion
dependencies {
implementation(project(":devkit-core"))
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
withSourcesJar()
withJavadocJar()
}
tasks.test {
useJUnitPlatform()
}
publishing {
publications {
create<MavenPublication>("mapUtilUnsafe") {
groupId = buildGroupId
artifactId = "map-util-unsafe"
version = buildVersion
pom {
name = "Unsafe Map Util"
description =
"This module is a converter that can convert an object to a map with unsafe methods."
url = projectUrl
licenses {
license {
name = licenseName
url = licenseUrl
}
}
scm {
connection = "scm:git:git://github.com:OnixByte/JDevKit.git"
developerConnection = "scm:git:git://github.com:OnixByte/JDevKit.git"
url = projectGithubUrl
}
developers {
developer {
id = "zihluwang"
name = "Zihlu Wang"
email = "really@zihlu.wang"
timezone = "Asia/Hong_Kong"
}
}
}
from(components["java"])
signing {
sign(publishing.publications["mapUtilUnsafe"])
}
}
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()
}
}
}
}
}
+1
View File
@@ -29,3 +29,4 @@ include(
"property-guard-spring-boot-starter" "property-guard-spring-boot-starter"
) )
include("map-util-unsafe") include("map-util-unsafe")
include("key-pair-loader")
@@ -24,51 +24,48 @@ import com.onixbyte.simplejwt.constants.TokenAlgorithm;
import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException; import com.onixbyte.simplejwt.exceptions.UnsupportedAlgorithmException;
import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.algorithms.Algorithm;
import java.util.HashMap; import java.security.KeyFactory;
import java.util.Map; import java.security.NoSuchAlgorithmException;
import java.util.Objects; import java.security.interfaces.ECPrivateKey;
import java.util.Optional; import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;
import java.util.function.Function; import java.util.function.Function;
/** /**
* The {@code AuthzeroTokenResolverConfig} class provides the configuration for * The {@code AuthzeroTokenResolverConfig} class provides the configuration for
* the {@link AuthzeroTokenResolver}. * the {@link AuthzeroTokenResolver}.
* <p> * <p>
* This configuration is used to establish the mapping between the standard * This configuration is used to establish the mapping between the standard {@link TokenAlgorithm}
* {@link TokenAlgorithm} defined in the * defined in the {@code cn.org.codecrafters:simple-jwt-facade} and the specific algorithms used
* {@code cn.org.codecrafters:simple-jwt-facade} and the specific algorithms * by the {@code com.auth0:java-jwt} library, which is the underlying library used by
* used by the {@code com.auth0:java-jwt} library, which is the underlying * {@link AuthzeroTokenResolver} to handle JSON Web Tokens (JWTs).
* library used by {@link AuthzeroTokenResolver} to handle JSON Web Tokens
* (JWTs).
* <p> * <p>
* <b>Algorithm Mapping:</b> * <b>Algorithm Mapping:</b>
* The {@code AuthzeroTokenResolverConfig} allows specifying the relationships * The {@code AuthzeroTokenResolverConfig} allows specifying the relationships between the standard
* between the standard {@link TokenAlgorithm} instances supported by * {@link TokenAlgorithm} instances supported by {@link AuthzeroTokenResolver} and the corresponding
* {@link AuthzeroTokenResolver} and the corresponding algorithms used by the * algorithms used by the {@code com.auth0:java-jwt} library. The mapping is achieved using a Map,
* {@code com.auth0:java-jwt} library. The mapping is achieved using a Map, * where the keys are the standard {@link TokenAlgorithm} instances, and the values represent the
* where the keys are the standard {@link TokenAlgorithm} instances, and the * algorithm functions used by {@code com.auth0:java-jwt} library for each corresponding key.
* values represent the algorithm functions used by {@code com.auth0:java-jwt}
* library for each corresponding key.
* <p> * <p>
* <b>Note:</b> * <b>Note:</b>
* The provided algorithm mapping should be consistent with the actual * The provided algorithm mapping should be consistent with the actual algorithms supported and used
* algorithms supported and used by the {@code com.auth0:java-jwt} library. It * by the {@code com.auth0:java-jwt} library. It is crucial to ensure that the mapping is accurate
* is crucial to ensure that the mapping is accurate to enable proper token * to enable proper token validation and processing within the {@link AuthzeroTokenResolver}.
* validation and processing within the {@link AuthzeroTokenResolver}.
* *
* @author Zihlu Wang * @author Zihlu Wang
* @version 1.1.1 * @version 1.1.1
* @since 1.0.0 * @since 1.0.0
*/ */
public final class AuthzeroTokenResolverConfig implements TokenResolverConfig<Function<String, Algorithm>> { public final class AuthzeroTokenResolverConfig
implements TokenResolverConfig<Function<String, Algorithm>> {
/** /**
* Gets the instance of {@code AuthzeroTokenResolverConfig}. * Gets the instance of {@code AuthzeroTokenResolverConfig}.
* <p> * <p>
* This method returns the singleton instance of * This method returns the singleton instance of {@code AuthzeroTokenResolverConfig}. If the
* {@code AuthzeroTokenResolverConfig}. If the instance is not yet created, * instance is not yet created, it will create a new instance and return it. Otherwise, it
* it will create a new instance and return it. Otherwise, it returns the * returns the existing instance.
* existing instance.
* *
* @return the instance of {@code AuthzeroTokenResolverConfig} * @return the instance of {@code AuthzeroTokenResolverConfig}
*/ */
@@ -81,23 +78,18 @@ public final class AuthzeroTokenResolverConfig implements TokenResolverConfig<Fu
} }
/** /**
* Gets the algorithm function corresponding to the specified * Gets the algorithm function corresponding to the specified {@link TokenAlgorithm}.
* {@link TokenAlgorithm}.
* <p> * <p>
* This method returns the algorithm function associated with the given * This method returns the algorithm function associated with the given {@link TokenAlgorithm}.
* {@link TokenAlgorithm}. The provided {@link TokenAlgorithm} represents * The provided {@link TokenAlgorithm} represents the specific algorithm for which the
* the specific algorithm for which the corresponding algorithm function * corresponding algorithm function is required. The returned Algorithm Function represents the
* is required. The returned Algorithm Function represents the function * function implementation that can be used by the {@link TokenResolver} to handle the
* implementation that can be used by the {@link TokenResolver} to handle * specific algorithm.
* the specific algorithm.
* *
* @param algorithm the {@link TokenAlgorithm} for which the algorithm * @param algorithm the {@link TokenAlgorithm} for which the algorithm function is required
* function isrequired * @return the algorithm function associated with the given {@link TokenAlgorithm}
* @return the algorithm function associated with the given {@link * @throws UnsupportedAlgorithmException if the given {@code algorithm} is not supported by
* TokenAlgorithm} * this implementation
* @throws UnsupportedAlgorithmException if the given {@code algorithm} is
* not supported by this
* implementation
*/ */
@Override @Override
public Function<String, Algorithm> getAlgorithm(TokenAlgorithm algorithm) { public Function<String, Algorithm> getAlgorithm(TokenAlgorithm algorithm) {
@@ -139,5 +131,22 @@ public final class AuthzeroTokenResolverConfig implements TokenResolverConfig<Fu
put(TokenAlgorithm.HS256, Algorithm::HMAC256); put(TokenAlgorithm.HS256, Algorithm::HMAC256);
put(TokenAlgorithm.HS384, Algorithm::HMAC384); put(TokenAlgorithm.HS384, Algorithm::HMAC384);
put(TokenAlgorithm.HS512, Algorithm::HMAC512); put(TokenAlgorithm.HS512, Algorithm::HMAC512);
put(TokenAlgorithm.ES256, (String privateKey) -> {
try {
var keyBytes = Base64.getDecoder().decode(privateKey);
var spec = new PKCS8EncodedKeySpec(keyBytes);
var kf = KeyFactory.getInstance("EC");
var key = kf.generatePrivate(spec);
if (key instanceof ECPrivateKey pk) {
return Algorithm.ECDSA256(pk);
} else {
throw new RuntimeException("Type error!");
}
} catch (NoSuchAlgorithmException ignored) {
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
}
return null;
});
}}; }};
} }