diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java index 87e85d6432..1fa05ea33f 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsTest.java @@ -12,6 +12,7 @@ import software.amazon.awssdk.services.kms.model.EncryptResponse; import software.amazon.awssdk.services.kms.model.GenerateDataKeyResponse; import software.amazon.awssdk.services.kms.model.GenerateDataKeyWithoutPlaintextResponse; import software.amazon.awssdk.services.kms.model.GetPublicKeyResponse; +import software.amazon.awssdk.services.kms.model.KeySpec; import software.amazon.awssdk.services.kms.model.KeyState; import software.amazon.awssdk.services.kms.model.KeyUsageType; import software.amazon.awssdk.services.kms.model.ListAliasesResponse; @@ -279,4 +280,32 @@ class KmsTest { kms.deleteAlias(b -> b.aliasName(aliasName)); // No exception means success } + + @Test + @Order(18) + void signAndVerifySecp256k1() { + CreateKeyResponse createResponse = kms.createKey(b -> b + .description("secp256k1-sign-key") + .keyUsage(KeyUsageType.SIGN_VERIFY) + .keySpec(KeySpec.ECC_SECG_P256_K1)); + + String eccKeyId = createResponse.keyMetadata().keyId(); + + SdkBytes msg = SdkBytes.fromString("message to sign", StandardCharsets.UTF_8); + + SignResponse signResponse = kms.sign(b -> b + .keyId(eccKeyId) + .message(msg) + .signingAlgorithm(SigningAlgorithmSpec.ECDSA_SHA_256)); + + assertThat(signResponse.signature()).isNotNull(); + + VerifyResponse verifyResponse = kms.verify(b -> b + .keyId(eccKeyId) + .message(msg) + .signature(signResponse.signature()) + .signingAlgorithm(SigningAlgorithmSpec.ECDSA_SHA_256)); + + assertThat(verifyResponse.signatureValid()).isTrue(); + } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java b/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java index 095cf5fcfa..8cc6c5247a 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/BouncyCastleInitializer.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common; import io.quarkus.runtime.Startup; import jakarta.enterprise.context.ApplicationScoped; +import org.bouncycastle.jcajce.provider.asymmetric.EC; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.jboss.logging.Logger; @@ -27,8 +28,18 @@ public class BouncyCastleInitializer { private static final Logger LOG = Logger.getLogger(BouncyCastleInitializer.class); static { + BouncyCastleProvider provider = new BouncyCastleProvider(); + // BC's ClassUtil.loadClass (used during provider setup) uses ClassLoader.loadClass, + // which in GraalVM native image only finds classes that are directly allocated in + // reachable code — not classes listed only in reflect-config.json or via class literals. + // If EC.Mappings failed to load internally, configure EC algorithms explicitly. + // Guard prevents IllegalStateException from double-registration in regular JVM mode. + EC.Mappings ecMappings = new EC.Mappings(); + if (provider.getService("KeyPairGenerator", "EC") == null) { + ecMappings.configure(provider); + } if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { - Security.addProvider(new BouncyCastleProvider()); + Security.addProvider(provider); LOG.info("Registered BouncyCastle security provider (static initializer)"); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java index 6cb1aa179f..bfa9a5c4e1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java @@ -9,8 +9,28 @@ import io.github.hectorvent.floci.services.kms.model.KmsKey; import com.fasterxml.jackson.core.type.TypeReference; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import org.bouncycastle.asn1.ASN1Integer; +import org.bouncycastle.asn1.ASN1Primitive; +import org.bouncycastle.asn1.ASN1Sequence; +import org.bouncycastle.asn1.DERSequenceGenerator; +import org.bouncycastle.asn1.pkcs.PrivateKeyInfo; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.crypto.params.ECDomainParameters; +import org.bouncycastle.crypto.params.ECPrivateKeyParameters; +import org.bouncycastle.crypto.params.ECPublicKeyParameters; +import org.bouncycastle.crypto.params.ParametersWithRandom; +import org.bouncycastle.crypto.signers.ECDSASigner; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey; +import org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPublicKey; +import org.bouncycastle.jcajce.provider.asymmetric.ec.KeyFactorySpi; +import org.bouncycastle.jcajce.provider.asymmetric.ec.KeyPairGeneratorSpi; +import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter; +import org.bouncycastle.jce.ECNamedCurveTable; +import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec; import org.jboss.logging.Logger; +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.*; @@ -92,7 +112,6 @@ public class KmsService { int size = Integer.parseInt(spec.substring(4)); generator.initialize(size); } else if (spec.startsWith("ECC_")) { - generator = KeyPairGenerator.getInstance("EC"); String curveName = switch (spec) { case "ECC_NIST_P256" -> "secp256r1"; case "ECC_NIST_P384" -> "secp384r1"; @@ -100,6 +119,13 @@ public class KmsService { case "ECC_SECG_P256K1" -> "secp256k1"; default -> throw new AwsException("InvalidCustomerMasterKeySpecException", "Unsupported curve: " + spec, 400); }; + // For secp256k1 (ECC_SECG_P256K1), instantiate BC's SPI directly. + // JCA's ClassLoader.loadClass cannot find BC SPI classes in GraalVM native image + // unless they are allocated directly in code (GraalVM escape analysis eliminates + // unused allocations, keeping them out of the native image type registry). + generator = isSecgP256k1(spec) + ? new KeyPairGeneratorSpi.EC() + : KeyPairGenerator.getInstance("EC"); generator.initialize(new ECGenParameterSpec(curveName)); } else { throw new AwsException("InvalidCustomerMasterKeySpecException", "Unsupported key spec: " + spec, 400); @@ -267,7 +293,10 @@ public class KmsService { // If message is already a digest, we need a "NONEwith..." algorithm jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA"); } - + + if (isSecgP256k1(kmsKey.getCustomerMasterKeySpec())) { + return signSecgP256k1(privateKey, message, jcaAlgo); + } Signature sig = Signature.getInstance(jcaAlgo); sig.initSign(privateKey); sig.update(message); @@ -295,6 +324,9 @@ public class KmsService { jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA"); } + if (isSecgP256k1(kmsKey.getCustomerMasterKeySpec())) { + return verifySecgP256k1(publicKey, message, signature, jcaAlgo); + } Signature sig = Signature.getInstance(jcaAlgo); sig.initVerify(publicKey); sig.update(message); @@ -307,14 +339,23 @@ public class KmsService { private PrivateKey loadPrivateKey(String encoded, String spec) throws Exception { byte[] decoded = Base64.getDecoder().decode(encoded); - KeyFactory factory = KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC"); - return factory.generatePrivate(new PKCS8EncodedKeySpec(decoded)); + if (isSecgP256k1(spec)) { + // For secp256k1, use BC's KeyFactorySpi.EC directly as AsymmetricKeyInfoConverter. + // This bypasses JCA and ClassLoader.loadClass; the allocation is live (generatePrivate + // is called), so GraalVM's escape analysis keeps the class in the native image. + AsymmetricKeyInfoConverter converter = new KeyFactorySpi.EC(); + return converter.generatePrivate(PrivateKeyInfo.getInstance(decoded)); + } + return buildKeyFactory(spec).generatePrivate(new PKCS8EncodedKeySpec(decoded)); } private PublicKey loadPublicKey(String encoded, String spec) throws Exception { byte[] decoded = Base64.getDecoder().decode(encoded); - KeyFactory factory = KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC"); - return factory.generatePublic(new X509EncodedKeySpec(decoded)); + if (isSecgP256k1(spec)) { + AsymmetricKeyInfoConverter converter = new KeyFactorySpi.EC(); + return converter.generatePublic(SubjectPublicKeyInfo.getInstance(decoded)); + } + return buildKeyFactory(spec).generatePublic(new X509EncodedKeySpec(decoded)); } private String mapAlgorithm(String awsAlgo) { @@ -364,6 +405,69 @@ public class KmsService { // ──────────────────────────── Helpers ──────────────────────────── + private static boolean isSecgP256k1(String spec) { + return "ECC_SECG_P256K1".equals(spec); + } + + /** + * Signs {@code message} with secp256k1 using BC's lightweight {@link ECDSASigner}. + * + *

BC's {@code SignatureSpi} subclasses extend {@code java.security.SignatureSpi} (not + * {@code java.security.Signature}), so they cannot be used as a drop-in {@code Signature}. + * Using the lightweight API avoids JCA's {@code ClassLoader.loadClass} entirely — every + * class referenced here is directly allocated in reachable code and is always in GraalVM's + * native image type registry.

+ */ + private static byte[] signSecgP256k1(PrivateKey privateKey, byte[] message, String jcaAlgo) throws Exception { + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + ECDomainParameters domain = new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN(), spec.getH()); + ECPrivateKeyParameters privParams = new ECPrivateKeyParameters(((BCECPrivateKey) privateKey).getD(), domain); + + byte[] hash = "NONEwithECDSA".equals(jcaAlgo) ? message : hashForEcdsa(message, jcaAlgo); + + ECDSASigner signer = new ECDSASigner(); + signer.init(true, new ParametersWithRandom(privParams, new SecureRandom())); + BigInteger[] rs = signer.generateSignature(hash); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + DERSequenceGenerator seq = new DERSequenceGenerator(bOut); + seq.addObject(new ASN1Integer(rs[0])); + seq.addObject(new ASN1Integer(rs[1])); + seq.close(); + return bOut.toByteArray(); + } + + /** Verifies a DER-encoded ECDSA signature over secp256k1. */ + private static boolean verifySecgP256k1(PublicKey publicKey, byte[] message, byte[] signature, String jcaAlgo) throws Exception { + ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1"); + ECDomainParameters domain = new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN(), spec.getH()); + ECPublicKeyParameters pubParams = new ECPublicKeyParameters(((BCECPublicKey) publicKey).getQ(), domain); + + byte[] hash = "NONEwithECDSA".equals(jcaAlgo) ? message : hashForEcdsa(message, jcaAlgo); + + ASN1Sequence asn1 = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(signature)); + BigInteger r = ASN1Integer.getInstance(asn1.getObjectAt(0)).getValue(); + BigInteger s = ASN1Integer.getInstance(asn1.getObjectAt(1)).getValue(); + + ECDSASigner verifier = new ECDSASigner(); + verifier.init(false, pubParams); + return verifier.verifySignature(hash, r, s); + } + + private static byte[] hashForEcdsa(byte[] message, String jcaAlgo) throws Exception { + String mdAlgo = switch (jcaAlgo) { + case "SHA256withECDSA" -> "SHA-256"; + case "SHA384withECDSA" -> "SHA-384"; + case "SHA512withECDSA" -> "SHA-512"; + default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported EC algorithm: " + jcaAlgo, 400); + }; + return MessageDigest.getInstance(mdAlgo).digest(message); + } + + private static KeyFactory buildKeyFactory(String spec) throws Exception { + return KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC"); + } + private KmsKey resolveKey(String keyIdOrArn, String region) { String id = keyIdOrArn; // Alias arn diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 95f8c13fd4..095addf0a7 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -12,6 +12,7 @@ quarkus: --initialize-at-run-time=org.bouncycastle.jcajce.provider.drbg.DRBG$NonceAndIV, --initialize-at-run-time=org.bouncycastle.crypto.prng.SP800SecureRandom, --initialize-at-run-time=org.bouncycastle.jce.provider.BouncyCastleProvider, + --initialize-at-run-time=io.github.hectorvent.floci.core.common.BouncyCastleInitializer, --initialize-at-run-time=io.github.hectorvent.floci.services.acm.AcmService, --initialize-at-run-time=io.github.hectorvent.floci.services.acm.CertificateGenerator, --initialize-at-run-time=io.github.hectorvent.floci.services.cognito.CognitoSrpHelper diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java index ec055380e6..694358571a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java @@ -5,16 +5,21 @@ import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.kms.model.KmsAlias; import io.github.hectorvent.floci.services.kms.model.KmsKey; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; +import java.security.Security; import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.List; import java.util.Map; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import static org.junit.jupiter.api.Assertions.*; @@ -24,6 +29,13 @@ class KmsServiceTest { private KmsService kmsService; + @BeforeAll + static void registerBouncyCastle() { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + } + @BeforeEach void setUp() { kmsService = new KmsService( @@ -184,9 +196,10 @@ class KmsServiceTest { kmsService.decrypt("not-valid-ciphertext".getBytes(StandardCharsets.UTF_8), REGION)); } - @Test - void signAndVerify() { - KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION); + @ParameterizedTest + @ValueSource(strings = {"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"}) + void signAndVerify(String keySpec) { + KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", keySpec, null, Map.of(), REGION); byte[] message = "sign me".getBytes(StandardCharsets.UTF_8); byte[] sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION); @@ -354,4 +367,4 @@ class KmsServiceTest { assertThrows(AwsException.class, () -> kmsService.enableKeyRotation(key.getKeyId(), REGION)); } -} \ No newline at end of file +}