feat(kms): support ECC imported key material (#4428)

* feat(kms): support ECC imported key material

* test(kms): cover verify, digest signing and import lifecycle for ECC keys

* docs(kms): explain why ECC keys accept every supported wrapping algorithm

* fix(kms): reject ECC key material whose inner curve parameters differ

* fix(kms): report malformed ECC key fields as IncorrectKeyMaterialException

* fix(kms): reject RSAES_OAEP wrapping of ECC_NIST_P521 material under an RSA_2048 key
This commit is contained in:
MIdhun authored and GitHub committed 2026-09-26 16:23:53 -05:00
1 parent 60d112542d
commit 5cb973c561
8 files changed
+561 -9

No files matched your search

+11 -2
View File
@@ -124,6 +124,11 @@ following combinations:
| Symmetric encryption key (`SYMMETRIC_DEFAULT`) | **Wrapping algorithms:** `RSAES_OAEP_SHA_256`, `RSAES_OAEP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |
| HMAC key (`HMAC_*`) | **Wrapping algorithms:** `RSAES_OAEP_SHA_256`, `RSAES_OAEP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |
| Asymmetric RSA private key (`RSA_*`) | **Wrapping algorithms:** `RSA_AES_KEY_WRAP_SHA_256`, `RSA_AES_KEY_WRAP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |
| Asymmetric elliptic curve private key (`ECC_NIST_P256`, `ECC_NIST_P384`, `ECC_NIST_P521`, `ECC_SECG_P256K1`) | **Wrapping algorithms:** `RSA_AES_KEY_WRAP_SHA_256`, `RSA_AES_KEY_WRAP_SHA_1`, `RSAES_OAEP_SHA_256`, `RSAES_OAEP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |
As on AWS, `ECC_NIST_P521` material cannot use an `RSAES_OAEP_*` algorithm with the `RSA_2048`
wrapping key spec: `GetParametersForImport` rejects that combination with
`UnsupportedOperationException`. Use a larger wrapping key or an `RSA_AES_KEY_WRAP_*` algorithm.
The hybrid `RSA_AES_KEY_WRAP_*` algorithms require a 256-bit AES key. `RSAES_PKCS1_V1_5` is
rejected, matching AWS, which stopped supporting it on October 10, 2023.
@@ -157,8 +162,12 @@ own the material and cannot rotate it.
**Deviations:**
- `Origin=EXTERNAL` supports `SYMMETRIC_DEFAULT`, the `HMAC_*` key specs and the `RSA_*` key specs.
- Other asymmetric key specs are rejected at `CreateKey` with `UnsupportedOperationException`.
- `Origin=EXTERNAL` supports `SYMMETRIC_DEFAULT`, the `HMAC_*` key specs, the `RSA_*` key specs, and
`ECC_NIST_P256`, `ECC_NIST_P384`, `ECC_NIST_P521` and `ECC_SECG_P256K1`. Imported elliptic curve
material is a PKCS#8 private key on the key spec's named curve; as on AWS, the public key is
derived from it, and an embedded public key must match.
- Other asymmetric key specs, including `ECC_NIST_EDWARDS25519`, which AWS can import, are rejected at
`CreateKey` with `UnsupportedOperationException`.
- Holding several imported key materials on one symmetric key, which real KMS uses for on-demand
rotation of imported material, is not emulated. `ImportType=NEW_KEY_MATERIAL` on a key that
already has key material is rejected with `UnsupportedOperationException`, and
@@ -73,7 +73,7 @@ final class KmsKeyImport {
* <p>RSAES_PKCS1_V1_5 stays in the modelled enum but AWS KMS stopped honouring it on
* October 10, 2023.
*/
static void validateWrappingAlgorithm(KmsKeySpec keySpec, String wrappingAlgorithm) {
static void validateWrappingAlgorithm(KmsKeySpec keySpec, String wrappingAlgorithm, String wrappingKeySpec) {
String algorithm = wrappingAlgorithm == null ? "" : wrappingAlgorithm;
validateWrappingAlgorithmValue(algorithm, wrappingAlgorithm);
@@ -92,6 +92,18 @@ final class KmsKeyImport {
+ "Supported values are: RSA_AES_KEY_WRAP_SHA_1 and RSA_AES_KEY_WRAP_SHA_256.", 400);
}
}
case ECC -> {
// AWS accepts both RSAES_OAEP_* and RSA_AES_KEY_WRAP_* for ECC material, which is
// everything validateWrappingAlgorithmValue lets through, except RSAES_OAEP_* under an
// RSA_2048 wrapping key for ECC_NIST_P521, whose material is too long for that payload.
boolean rsaesOaep = RSAES_OAEP_SHA_1.equals(algorithm) || RSAES_OAEP_SHA_256.equals(algorithm);
if (keySpec == KmsKeySpec.ECC_NIST_P521 && rsaesOaep && "RSA_2048".equals(wrappingKeySpec)) {
throw new AwsException("UnsupportedOperationException",
"WrappingAlgorithm " + wrappingAlgorithm + " with WrappingKeySpec RSA_2048 is not "
+ "supported for " + keySpec + " key. Use a larger wrapping key spec or "
+ "RSA_AES_KEY_WRAP_SHA_1 or RSA_AES_KEY_WRAP_SHA_256.", 400);
}
}
default -> throw new AwsException("UnsupportedOperationException",
"Importing key material for key spec " + keySpec + " is not supported.", 400);
}
@@ -870,7 +870,7 @@ public class KmsService implements ResourceProvider {
KmsKey key = resolveKey(keyId, region);
requireExternalOrigin(key);
requireNotPendingDeletion(key);
KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm);
KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm, wrappingKeySpec);
KmsKeyImport.WrappingKeyPair wrappingKeyPair = KmsKeyImport.generateWrappingKeyPair(wrappingKeySpec);
KmsImportParameters parameters = new KmsImportParameters();
@@ -1125,15 +1125,16 @@ public class KmsService implements ResourceProvider {
}
/**
* Allows imports for symmetric, HMAC and RSA key specs. Other key specs are not supported.
* Allows imports for symmetric, HMAC, RSA and ECC key specs. Other key specs are not supported.
*/
private static String requireImportableSpec(KmsKeySpec spec) {
if (spec != KmsKeySpec.SYMMETRIC_DEFAULT
&& spec.getKeyType() != KmsKeySpec.KeyType.HMAC
&& spec.getKeyType() != KmsKeySpec.KeyType.RSA) {
&& spec.getKeyType() != KmsKeySpec.KeyType.RSA
&& spec.getKeyType() != KmsKeySpec.KeyType.ECC) {
throw new AwsException("UnsupportedOperationException",
"Origin EXTERNAL is only supported for SYMMETRIC_DEFAULT, HMAC and RSA key specs, not "
"Origin EXTERNAL is only supported for SYMMETRIC_DEFAULT, HMAC, RSA and ECC key specs, not "
+ spec + ".", 400);
}
return EXTERNAL_ORIGIN;
@@ -1,8 +1,16 @@
package io.github.hectorvent.floci.services.kms.keytype;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import org.bouncycastle.asn1.ASN1BitString;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.sec.ECPrivateKey;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
@@ -10,15 +18,19 @@ 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.asymmetric.util.ECUtil;
import org.bouncycastle.jcajce.provider.util.AsymmetricKeyInfoConverter;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
// The BouncyCastle SPI classes are allocated directly. JCA lookup cannot find them in the native image.
@@ -47,6 +59,93 @@ final class BcEcKeys {
return new ECPublicKeyParameters(publicKey.getQ(), domainParameters(curveName));
}
/**
* Stores imported ECC key material: a PKCS#8 private key (RFC 5208) holding an RFC 5915
* ECPrivateKey on the key spec's named curve. As on AWS, only the private key is taken from
* the material and the public key is derived from it; an embedded public key must match.
*/
static void importPrivateKey(KmsKey key, byte[] material, String curveName) {
try {
ImportedEcKey imported = parseImportedPrivateKey(material, curveName);
Base64.Encoder encoder = Base64.getEncoder();
key.setPrivateKeyEncoded(encoder.encodeToString(imported.privateKeyEncoded()));
key.setPublicKeyEncoded(encoder.encodeToString(imported.publicKeyEncoded()));
} catch (InvalidKeySpecException e) {
throw new AwsException("IncorrectKeyMaterialException",
"Key material for key spec " + key.getKeySpec() + " must be a PKCS#8-encoded "
+ curveName + " private key: " + e.getMessage(), 400);
}
}
private static ImportedEcKey parseImportedPrivateKey(byte[] material, String curveName)
throws InvalidKeySpecException {
// BouncyCastle decodes the ECPrivateKey fields lazily, so a malformed field only fails when it
// is read: read them all here, where a failure maps to IncorrectKeyMaterialException.
PrivateKeyInfo privateKeyInfo;
BigInteger privateScalar;
ASN1Object innerParameters;
ASN1BitString embeddedPublicKey;
try {
privateKeyInfo = PrivateKeyInfo.getInstance(material);
ECPrivateKey ecPrivateKey = ECPrivateKey.getInstance(privateKeyInfo.parsePrivateKey());
privateScalar = ecPrivateKey.getKey();
innerParameters = ecPrivateKey.getParametersObject();
embeddedPublicKey = ecPrivateKey.getPublicKey();
} catch (IOException | RuntimeException e) {
throw new InvalidKeySpecException("the material is not a PKCS#8 EC private key", e);
}
AlgorithmIdentifier algorithm = privateKeyInfo.getPrivateKeyAlgorithm();
if (!X9ObjectIdentifiers.id_ecPublicKey.equals(algorithm.getAlgorithm())) {
throw new InvalidKeySpecException("the material is not an EC private key");
}
ASN1ObjectIdentifier curveOid = ECUtil.getNamedCurveOid(curveName);
if (!curveOid.equals(algorithm.getParameters())) {
throw new InvalidKeySpecException("the material must name the " + curveName + " curve");
}
if (innerParameters != null && !curveOid.equals(innerParameters)) {
throw new InvalidKeySpecException("the EC private key's own parameters must also name the "
+ curveName + " curve");
}
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
if (privateScalar.signum() <= 0 || privateScalar.compareTo(spec.getN()) >= 0) {
throw new InvalidKeySpecException("the private key is out of range for " + curveName);
}
ECPoint publicPoint = spec.getG().multiply(privateScalar).normalize();
requireMatchingEmbeddedPublicKey(embeddedPublicKey, publicPoint, spec);
try {
SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo(
new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, curveOid),
publicPoint.getEncoded(false));
return new ImportedEcKey(privateKeyInfo.getEncoded(ASN1Encoding.DER),
publicKeyInfo.getEncoded(ASN1Encoding.DER));
} catch (IOException e) {
throw new InvalidKeySpecException("the key could not be re-encoded", e);
}
}
private static void requireMatchingEmbeddedPublicKey(ASN1BitString embedded, ECPoint derived,
ECNamedCurveParameterSpec spec)
throws InvalidKeySpecException {
if (embedded == null) {
return;
}
ECPoint embeddedPoint;
try {
embeddedPoint = spec.getCurve().decodePoint(embedded.getOctets());
} catch (RuntimeException e) {
throw new InvalidKeySpecException("the embedded public key is not a point on the curve", e);
}
if (!embeddedPoint.equals(derived)) {
throw new InvalidKeySpecException("the embedded public key does not match the private key");
}
}
private record ImportedEcKey(byte[] privateKeyEncoded, byte[] publicKeyEncoded) {
}
private static ECDomainParameters domainParameters(String curveName) {
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
return new ECDomainParameters(spec.getCurve(), spec.getG(), spec.getN(), spec.getH());
@@ -19,6 +19,11 @@ final class EccNistKeyType implements KmsKeyType {
AsymmetricKeys.store(key, generator.generateKeyPair());
}
@Override
public void importKeyMaterial(KmsKey key, byte[] material) {
BcEcKeys.importPrivateKey(key, material, key.getKeySpec().curveName());
}
@Override
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
throws GeneralSecurityException {
@@ -33,6 +33,11 @@ final class EccSecgP256k1KeyType implements KmsKeyType {
AsymmetricKeys.store(key, BcEcKeys.generateKeyPair(CURVE));
}
@Override
public void importKeyMaterial(KmsKey key, byte[] material) {
BcEcKeys.importPrivateKey(key, material, CURVE);
}
@Override
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
throws GeneralSecurityException, IOException {
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.kms;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import jakarta.inject.Inject;
import org.junit.jupiter.api.BeforeAll;
@@ -18,6 +19,7 @@ import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
@@ -3124,6 +3126,62 @@ class KmsIntegrationTest {
.body("KeyMetadata.Enabled", equalTo(true));
}
@Test
void eccImportRoundTripDerivesThePublicKey() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec("secp256r1"));
KeyPair importedKeyPair = generator.generateKeyPair();
String keyId = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("{\"Origin\":\"EXTERNAL\",\"KeyUsage\":\"SIGN_VERIFY\",\"KeySpec\":\"ECC_NIST_P256\"}")
.when().post("/")
.then()
.statusCode(200)
.body("KeyMetadata.KeyState", equalTo("PendingImport"))
.extract().path("KeyMetadata.KeyId");
JsonPath parameters = given()
.header("X-Amz-Target", "TrentService.GetParametersForImport")
.contentType(KMS_CONTENT_TYPE)
.body(("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSA_AES_KEY_WRAP_SHA_256\","
+ "\"WrappingKeySpec\":\"RSA_2048\"}").formatted(keyId))
.when().post("/")
.then()
.statusCode(200)
.extract().jsonPath();
String wrapped = Base64.getEncoder().encodeToString(wrapWithRsaAesSha256(
parameters.getString("PublicKey"), importedKeyPair.getPrivate().getEncoded()));
given()
.header("X-Amz-Target", "TrentService.ImportKeyMaterial")
.contentType(KMS_CONTENT_TYPE)
.body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","
+ "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")
.formatted(keyId, parameters.getString("ImportToken"), wrapped))
.when().post("/")
.then()
.statusCode(200)
.body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));
String publicKey = given()
.header("X-Amz-Target", "TrentService.GetPublicKey")
.contentType(KMS_CONTENT_TYPE)
.body("{\"KeyId\":\"%s\"}".formatted(keyId))
.when().post("/")
.then()
.statusCode(200)
.body("KeySpec", equalTo("ECC_NIST_P256"))
.body("KeyUsage", equalTo("SIGN_VERIFY"))
.extract().path("PublicKey");
assertEquals(Base64.getEncoder().encodeToString(importedKeyPair.getPublic().getEncoded()), publicKey);
describeKey(keyId)
.body("KeyMetadata.KeyState", equalTo("Enabled"))
.body("KeyMetadata.Enabled", equalTo(true));
}
@Test
void aDeprecatedWrappingAlgorithmIsRejected() {
String keyId = createExternalSymmetricKey();
@@ -14,6 +14,21 @@ import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
import io.github.hectorvent.floci.services.kms.model.KmsKeyUsage;
import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
import jakarta.ws.rs.core.Response;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.sec.ECPrivateKey;
import org.bouncycastle.asn1.sec.SECObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.ECNamedCurveTable;
import org.bouncycastle.asn1.x9.X962Parameters;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -26,6 +41,7 @@ import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.KeyPair;
@@ -34,6 +50,7 @@ import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.security.spec.X509EncodedKeySpec;
@@ -2464,6 +2481,47 @@ class KmsServiceTest {
return generator.generateKeyPair();
}
private KeyPair ecKeyPair(String keySpec) throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC", BouncyCastleProvider.PROVIDER_NAME);
generator.initialize(new ECGenParameterSpec(KmsKeySpec.valueOf(keySpec).curveName()));
return generator.generateKeyPair();
}
private byte[] ecPublicPoint(KeyPair keyPair) {
return SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()).getPublicKeyData().getBytes();
}
/** Re-encodes an EC private key with the given algorithm identifier and embedded public point. */
private byte[] ecPkcs8(KeyPair keyPair, String curveName, AlgorithmIdentifier algorithm,
byte[] embeddedPublicPoint) throws Exception {
return ecPkcs8(keyPair, curveName, algorithm, embeddedPublicPoint, null);
}
/** As above, also setting the RFC 5915 ECPrivateKey's own optional curve parameters. */
private byte[] ecPkcs8(KeyPair keyPair, String curveName, AlgorithmIdentifier algorithm,
byte[] embeddedPublicPoint, ASN1Encodable innerParameters) throws Exception {
BigInteger privateScalar = ECPrivateKey.getInstance(
PrivateKeyInfo.getInstance(keyPair.getPrivate().getEncoded()).parsePrivateKey()).getKey();
int orderBits = ECNamedCurveTable.getByName(curveName).getN().bitLength();
ECPrivateKey ecPrivateKey = new ECPrivateKey(orderBits, privateScalar,
new DERBitString(embeddedPublicPoint), innerParameters);
return new PrivateKeyInfo(algorithm, ecPrivateKey).getEncoded();
}
/** A P-256 PKCS#8 key whose RFC 5915 fields after the version are given as-is, malformed or not. */
private byte[] ecPkcs8WithRawFields(ASN1Encodable... fieldsAfterVersion) throws Exception {
ASN1EncodableVector fields = new ASN1EncodableVector();
fields.add(new ASN1Integer(1));
for (ASN1Encodable field : fieldsAfterVersion) {
fields.add(field);
}
return new PrivateKeyInfo(p256NamedCurve(), new DERSequence(fields)).getEncoded();
}
private AlgorithmIdentifier p256NamedCurve() {
return new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, X9ObjectIdentifiers.prime256v1);
}
private KmsKey importInto(KmsKey key, byte[] rawMaterial, String wrappingAlgorithm) throws Exception {
return importInto(key, rawMaterial, wrappingAlgorithm, "RSA_2048");
}
@@ -2943,10 +3001,315 @@ class KmsServiceTest {
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@ParameterizedTest
@CsvSource({
"ECC_NIST_P256, RSA_AES_KEY_WRAP_SHA_256, RSA_2048",
"ECC_NIST_P384, RSA_AES_KEY_WRAP_SHA_1, RSA_3072",
"ECC_NIST_P521, RSA_AES_KEY_WRAP_SHA_256, RSA_4096",
"ECC_SECG_P256K1, RSA_AES_KEY_WRAP_SHA_256, RSA_2048",
"ECC_NIST_P256, RSAES_OAEP_SHA_256, RSA_2048",
"ECC_NIST_P521, RSAES_OAEP_SHA_1, RSA_4096",
"ECC_NIST_P521, RSAES_OAEP_SHA_256, RSA_3072",
"ECC_NIST_P521, RSA_AES_KEY_WRAP_SHA_256, RSA_2048",
"ECC_SECG_P256K1, RSAES_OAEP_SHA_256, RSA_3072"
})
void supportedEccKeyAndWrappingSpecsImportUsablePrivateKeyMaterial(
String keySpec, String wrappingAlgorithm, String wrappingKeySpec) throws Exception {
KmsKey key = externalKey(keySpec, "SIGN_VERIFY");
KeyPair importedKeyPair = ecKeyPair(keySpec);
KmsKey imported = importInto(key, importedKeyPair.getPrivate().getEncoded(),
wrappingAlgorithm, wrappingKeySpec);
assertEquals("Enabled", imported.getKeyState());
assertTrue(imported.isEnabled());
assertArrayEquals(importedKeyPair.getPublic().getEncoded(),
Base64.getDecoder().decode(imported.getPublicKeyEncoded()));
KmsKeySpec.Algorithm algorithm = KmsKeySpec.valueOf(keySpec).getAlgorithm().getFirst();
byte[] message = "imported ECC key".getBytes(StandardCharsets.UTF_8);
byte[] signature = kmsService.sign(key.getKeyId(), message, algorithm.name(), REGION);
Signature verifier = Signature.getInstance(algorithm.getJavaName(), BouncyCastleProvider.PROVIDER_NAME);
verifier.initVerify(importedKeyPair.getPublic());
verifier.update(message);
assertTrue(verifier.verify(signature));
}
@Test
void nonRsaAsymmetricKeySpecsCannotUseExternalOrigin() {
void eccImportAcceptsACompressedEmbeddedPublicKey() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
byte[] compressedPoint = ECNamedCurveTable.getByName("secp256r1").getCurve()
.decodePoint(ecPublicPoint(keyPair)).getEncoded(true);
KmsKey imported = importInto(key, ecPkcs8(keyPair, "secp256r1", p256NamedCurve(), compressedPoint),
RSA_AES_SHA_256);
assertEquals("Enabled", imported.getKeyState());
assertArrayEquals(keyPair.getPublic().getEncoded(),
Base64.getDecoder().decode(imported.getPublicKeyEncoded()));
}
@Test
void eccImportRejectsKeyMaterialOnAnotherCurve() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
byte[] p384Material = ecKeyPair("ECC_NIST_P384").getPrivate().getEncoded();
AwsException ex = assertThrows(AwsException.class, () ->
externalKey("ECC_NIST_P256", "SIGN_VERIFY"));
importInto(key, p384Material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsExplicitCurveParameters() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
AlgorithmIdentifier explicitCurve = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey,
new X962Parameters(ECNamedCurveTable.getByName("secp256r1")));
byte[] material = ecPkcs8(keyPair, "secp256r1", explicitCurve, ecPublicPoint(keyPair));
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportAcceptsInnerParametersNamingTheSameCurve() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
byte[] material = ecPkcs8(keyPair, "secp256r1", p256NamedCurve(), ecPublicPoint(keyPair),
X9ObjectIdentifiers.prime256v1);
KmsKey imported = importInto(key, material, RSA_AES_SHA_256);
assertEquals("Enabled", imported.getKeyState());
}
@Test
void eccImportRejectsInnerParametersNamingAnotherCurve() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
byte[] material = ecPkcs8(keyPair, "secp256r1", p256NamedCurve(), ecPublicPoint(keyPair),
SECObjectIdentifiers.secp384r1);
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsExplicitInnerCurveParameters() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
byte[] material = ecPkcs8(keyPair, "secp256r1", p256NamedCurve(), ecPublicPoint(keyPair),
new X962Parameters(ECNamedCurveTable.getByName("secp256r1")));
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsAMalformedPrivateKeyField() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
byte[] material = ecPkcs8WithRawFields(new ASN1Integer(7));
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsMalformedInnerParameters() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
byte[] material = ecPkcs8WithRawFields(new DEROctetString(new byte[] {1}),
new DERTaggedObject(false, 0, new DERSequence(new ASN1Integer(3))));
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsAMalformedEmbeddedPublicKeyField() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
byte[] material = ecPkcs8WithRawFields(new DEROctetString(new byte[] {1}),
new DERTaggedObject(true, 1, new ASN1Integer(5)));
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsAnEmbeddedPublicKeyThatDoesNotMatch() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
byte[] otherPublicPoint = ecPublicPoint(ecKeyPair("ECC_NIST_P256"));
byte[] material = ecPkcs8(keyPair, "secp256r1", p256NamedCurve(), otherPublicPoint);
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsAnRsaPrivateKey() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
byte[] rsaMaterial = rsaKeyPair("RSA_2048").getPrivate().getEncoded();
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, rsaMaterial, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void eccImportRejectsInvalidPkcs8Material() {
KmsKey key = externalKey("ECC_SECG_P256K1", "SIGN_VERIFY");
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, material(32, (byte) 7), RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@ParameterizedTest
@ValueSource(strings = {"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"})
void importedEccKeyVerifiesSignaturesAndSignsDigests(String keySpec) throws Exception {
KmsKey key = externalKey(keySpec, "SIGN_VERIFY");
KeyPair importedKeyPair = ecKeyPair(keySpec);
importInto(key, importedKeyPair.getPrivate().getEncoded(), RSA_AES_SHA_256, "RSA_4096");
KmsKeySpec.Algorithm algorithm = KmsKeySpec.valueOf(keySpec).getAlgorithm().getFirst();
byte[] message = "imported ECC key".getBytes(StandardCharsets.UTF_8);
Signature signer = Signature.getInstance(algorithm.getJavaName(), BouncyCastleProvider.PROVIDER_NAME);
signer.initSign(importedKeyPair.getPrivate());
signer.update(message);
byte[] externalSignature = signer.sign();
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, externalSignature,
algorithm.name(), REGION));
byte[] tampered = "tampered message".getBytes(StandardCharsets.UTF_8);
AwsException ex = assertThrows(AwsException.class, () -> kmsService.verify(key.getKeyId(), tampered,
externalSignature, algorithm.name(), REGION));
assertEquals("KMSInvalidSignatureException", ex.getErrorCode());
byte[] digest = MessageDigest.getInstance(algorithm.getJavaName().substring(0, 6)).digest(message);
byte[] digestSignature = kmsService.sign(key.getKeyId(), digest, algorithm.name(),
KmsMessageType.DIGEST, REGION);
Signature verifier = Signature.getInstance(algorithm.getJavaName(), BouncyCastleProvider.PROVIDER_NAME);
verifier.initVerify(importedKeyPair.getPublic());
verifier.update(message);
assertTrue(verifier.verify(digestSignature));
}
@Test
void reimportingTheSameEccKeyAfterDeletionRestoresIt() throws Exception {
KmsKey key = externalKey("ECC_SECG_P256K1", "SIGN_VERIFY");
KeyPair keyPair = ecKeyPair("ECC_SECG_P256K1");
byte[] material = keyPair.getPrivate().getEncoded();
importInto(key, material, RSA_AES_SHA_256);
KmsKey deleted = kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
assertEquals("PendingImport", deleted.getKeyState());
assertNull(deleted.getPrivateKeyEncoded());
KmsKey reimported = importInto(key, material, RSA_AES_SHA_256);
assertEquals("Enabled", reimported.getKeyState());
assertArrayEquals(keyPair.getPublic().getEncoded(),
Base64.getDecoder().decode(reimported.getPublicKeyEncoded()));
}
@Test
void reimportingADifferentEccKeyIsRejected() throws Exception {
KmsKey key = externalKey("ECC_NIST_P384", "SIGN_VERIFY");
importInto(key, ecKeyPair("ECC_NIST_P384").getPrivate().getEncoded(), RSA_AES_SHA_256);
kmsService.deleteImportedKeyMaterial(key.getKeyId(), REGION);
byte[] otherKey = ecKeyPair("ECC_NIST_P384").getPrivate().getEncoded();
AwsException ex = assertThrows(AwsException.class, () ->
importInto(key, otherKey, RSA_AES_SHA_256));
assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());
assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());
}
@Test
void expiringEccMaterialReturnsTheKeyToPendingImport() throws Exception {
KmsKey key = externalKey("ECC_NIST_P256", "SIGN_VERIFY");
KmsService.ImportParameters parameters =
kmsService.getParametersForImport(key.getKeyId(), RSA_AES_SHA_256, "RSA_2048", REGION);
byte[] wrapped = wrapRsaAes(parameters.publicKeyEncoded(), RSA_AES_SHA_256,
ecKeyPair("ECC_NIST_P256").getPrivate().getEncoded(), material(32, (byte) 91));
kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,
"KEY_MATERIAL_EXPIRES", Instant.now().getEpochSecond() + 3600, null, REGION);
KmsKey stored = keyStore.get(REGION + "::" + key.getKeyId()).orElseThrow();
stored.setValidTo(Instant.now().getEpochSecond() - 60);
keyStore.put(REGION + "::" + key.getKeyId(), stored);
KmsKey expired = kmsService.describeKey(key.getKeyId(), REGION);
assertEquals("PendingImport", expired.getKeyState());
assertFalse(expired.isEnabled());
assertNull(expired.getPrivateKeyEncoded());
}
@Test
void aReplicaOfAnImportedEccKeyAcceptsTheSameKey() throws Exception {
String replicaRegion = "us-west-2";
KmsKey primary = kmsService.createKey("external primary", "SIGN_VERIFY", "ECC_NIST_P256",
null, Map.of(), "EXTERNAL", true, REGION);
KeyPair keyPair = ecKeyPair("ECC_NIST_P256");
importInto(primary, keyPair.getPrivate().getEncoded(), RSA_AES_SHA_256);
KmsKey replica = kmsService.replicateKey(primary.getKeyId(), null, null, Map.of(), replicaRegion, REGION);
assertEquals("PendingImport", replica.getKeyState());
KmsService.ImportParameters parameters = kmsService.getParametersForImport(
replica.getKeyId(), RSA_AES_SHA_256, "RSA_2048", replicaRegion);
byte[] wrapped = wrapRsaAes(parameters.publicKeyEncoded(), RSA_AES_SHA_256,
keyPair.getPrivate().getEncoded(), material(32, (byte) 91));
KmsKey imported = kmsService.importKeyMaterial(replica.getKeyId(), parameters.importToken(), wrapped,
"KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, replicaRegion);
assertEquals("Enabled", imported.getKeyState());
assertArrayEquals(keyPair.getPublic().getEncoded(),
Base64.getDecoder().decode(imported.getPublicKeyEncoded()));
}
@ParameterizedTest
@ValueSource(strings = {"RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256"})
void p521MaterialRejectsRsaesOaepUnderAnRsa2048WrappingKey(String wrappingAlgorithm) {
String keyId = externalKey("ECC_NIST_P521", "SIGN_VERIFY").getKeyId();
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.getParametersForImport(keyId, wrappingAlgorithm, "RSA_2048", REGION));
assertEquals("UnsupportedOperationException", ex.getErrorCode());
}
@ParameterizedTest
@ValueSource(strings = {"ECC_NIST_EDWARDS25519", "ML_DSA_44"})
void asymmetricKeySpecsWithoutImportSupportCannotUseExternalOrigin(String keySpec) {
AwsException ex = assertThrows(AwsException.class, () ->
externalKey(keySpec, "SIGN_VERIFY"));
assertEquals("UnsupportedOperationException", ex.getErrorCode());
}