refactor(kms): use enums for type-safety. add algorithms to keymetadata (#1430)

* refactor(kms) use enums for type-safety. add algorithms to keymetadata

Signed-off-by: Mark Hayen <mark.hayen@edsn.nl>

* refactor(kms): use enums for type-safety. add algorithms to keymetadata

Signed-off-by: Mark Hayen <mark.hayen@edsn.nl>

* refactor(kms): update missing algorithms handling and add tests to cover all combinations of keySpec,KeyUsage

Signed-off-by: Mark Hayen <mark.hayen@edsn.nl>

---------

Signed-off-by: Mark Hayen <mark.hayen@edsn.nl>
Co-authored-by: Mark Hayen <mark.hayen@edsn.nl>
This commit is contained in:
MarkandMark Hayen authored and GitHub committed 2026-06-21 01:02:01 -05:00
1 parent 93782c0142
commit c2cd31216b
10 files changed
+759 -230

No files matched your search

@@ -3,6 +3,7 @@ package com.floci.test;
import org.junit.jupiter.api.*;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.CreateKeyResponse;
import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec;
import software.amazon.awssdk.services.kms.model.GetKeyPolicyResponse;
import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;
@@ -15,6 +16,7 @@ import static org.assertj.core.api.Assertions.*;
* #269 — CreateKey applies Tags at creation time
* #258 — GetKeyPolicy returns the stored policy
* #259 — PutKeyPolicy updates the key policy
* #DescribeKey — Returns proper EncryptionAlgorithms, SigningAlgorithms, and MacAlgorithms
*/
@DisplayName("KMS features (#258 #259 #269)")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@@ -51,8 +53,8 @@ class KmsFeaturesTest {
software.amazon.awssdk.services.kms.model.Tag::tagKey,
software.amazon.awssdk.services.kms.model.Tag::tagValue));
assertThat(tagMap).containsEntry("env", "prod");
assertThat(tagMap).containsEntry("team", "platform");
assertThat(tagMap).containsEntry("env", "prod")
.containsEntry("team", "platform");
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
}
@@ -146,4 +148,57 @@ class KmsFeaturesTest {
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
}
// ── DescribeKey Responses ────────────────────────────────────────────────
@Test
@Order(40)
void describeSymmetricKeyReturnsNoEncryptionAlgorithms() {
CreateKeyResponse resp = kms.createKey(b -> b
.description("symmetric-key")
.keyUsage("ENCRYPT_DECRYPT")
.keySpec("SYMMETRIC_DEFAULT"));
String keyId = resp.keyMetadata().keyId();
assertThat(resp.keyMetadata().encryptionAlgorithms()).isNotEmpty();
assertThat(resp.keyMetadata().encryptionAlgorithms()).contains(EncryptionAlgorithmSpec.SYMMETRIC_DEFAULT);
assertThat(resp.keyMetadata().signingAlgorithms()).isEmpty();
assertThat(resp.keyMetadata().macAlgorithms()).isEmpty();
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
}
@Test
@Order(41)
void describeAsymmetricRsaSignKeyReturnsSigningAlgorithms() {
CreateKeyResponse resp = kms.createKey(b -> b
.description("rsa-sign-key")
.keyUsage("SIGN_VERIFY")
.keySpec("RSA_2048"));
String keyId = resp.keyMetadata().keyId();
assertThat(resp.keyMetadata().signingAlgorithms())
.contains(software.amazon.awssdk.services.kms.model.SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_256,
software.amazon.awssdk.services.kms.model.SigningAlgorithmSpec.RSASSA_PSS_SHA_256);
assertThat(resp.keyMetadata().encryptionAlgorithms()).isEmpty();
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
}
@Test
@Order(42)
void describeHmacKeyReturnsMacAlgorithms() {
CreateKeyResponse resp = kms.createKey(b -> b
.description("hmac-key")
.keyUsage("GENERATE_VERIFY_MAC")
.keySpec("HMAC_256"));
String keyId = resp.keyMetadata().keyId();
assertThat(resp.keyMetadata().macAlgorithms())
.containsExactly(software.amazon.awssdk.services.kms.model.MacAlgorithmSpec.HMAC_SHA_256);
assertThat(resp.keyMetadata().signingAlgorithms()).isEmpty();
assertThat(resp.keyMetadata().encryptionAlgorithms()).isEmpty();
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
}
}
@@ -3,25 +3,7 @@ package com.floci.test;
import org.junit.jupiter.api.*;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.kms.model.CreateKeyResponse;
import software.amazon.awssdk.services.kms.model.CustomerMasterKeySpec;
import software.amazon.awssdk.services.kms.model.DataKeySpec;
import software.amazon.awssdk.services.kms.model.DecryptResponse;
import software.amazon.awssdk.services.kms.model.DescribeKeyResponse;
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;
import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;
import software.amazon.awssdk.services.kms.model.MessageType;
import software.amazon.awssdk.services.kms.model.ReEncryptResponse;
import software.amazon.awssdk.services.kms.model.SignResponse;
import software.amazon.awssdk.services.kms.model.SigningAlgorithmSpec;
import software.amazon.awssdk.services.kms.model.VerifyResponse;
import software.amazon.awssdk.services.kms.model.*;
import java.nio.charset.StandardCharsets;
@@ -203,6 +185,10 @@ class KmsTest {
.customerMasterKeySpec(CustomerMasterKeySpec.RSA_2048));
String asymmetricKeyId = createResponse.keyMetadata().keyId();
assertThat(createResponse.keyMetadata().keySpec()).isEqualTo(KeySpec.RSA_2048);
assertThat(createResponse.keyMetadata().signingAlgorithms()).contains(SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_256);
assertThat(createResponse.keyMetadata().customerMasterKeySpec().name()).isEqualTo(KeySpec.RSA_2048.name());
assertThat(createResponse.keyMetadata().keySpec().name()).isEqualTo(KeySpec.RSA_2048.name());
SdkBytes msg = SdkBytes.fromString("message to sign", StandardCharsets.UTF_8);
SignResponse signResponse = kms.sign(b -> b
@@ -262,6 +248,10 @@ class KmsTest {
assertThat(pubResponse.publicKey()).isNotNull();
assertThat(pubResponse.keyUsage()).isEqualTo(KeyUsageType.SIGN_VERIFY);
assertThat(pubResponse.customerMasterKeySpec()).isEqualTo(CustomerMasterKeySpec.ECC_NIST_P256);
assertThat(pubResponse.keySpec()).isEqualTo(KeySpec.ECC_NIST_P256);
assertThat(pubResponse.signingAlgorithms()).isNotEmpty();
assertThat(pubResponse.signingAlgorithms()).contains(SigningAlgorithmSpec.ECDSA_SHA_256);
}
@Test
@@ -277,7 +267,8 @@ class KmsTest {
@Test
@Order(17)
void deleteAlias() {
kms.deleteAlias(b -> b.aliasName(aliasName));
DeleteAliasResponse deleteAliasResponse = kms.deleteAlias(b -> b.aliasName(aliasName));
assertThat(deleteAliasResponse).isNotNull();
// No exception means success
}
@@ -317,4 +308,104 @@ class KmsTest {
assertThat(response.plaintext()).isNotNull();
assertThat(response.plaintext().asByteArray()).hasSize(32);
}
@Test
@Order(19)
void describeSignVerifyRsaKey() {
CreateKeyResponse response = kms.createKey(b -> b.description("test-sign-key")
.keySpec(KeySpec.RSA_2048)
.keyUsage("SIGN_VERIFY"));
String signKeyId = response.keyMetadata().keyId();
assertThat(response.keyMetadata().encryptionAlgorithms()).isEmpty();
assertThat(response.keyMetadata().signingAlgorithms()).isNotEmpty();
assertThat(response.keyMetadata().keySpec()).isNotNull();
assertThat(response.keyMetadata().signingAlgorithms()).contains(SigningAlgorithmSpec.RSASSA_PKCS1_V1_5_SHA_256);
assertThat(signKeyId).isNotNull();
DescribeKeyResponse describeKeyResponse = kms.describeKey(b -> b.keyId(signKeyId));
assertThat(describeKeyResponse.keyMetadata().signingAlgorithms()).isNotEmpty();
assertThat(describeKeyResponse.keyMetadata().keySpec()).isNotNull();
assertThat(describeKeyResponse.keyMetadata().keyId()).isEqualTo(signKeyId);
}
@Test
@Order(20)
void describeSignVerifyEcKey() {
CreateKeyResponse response = kms.createKey(b -> b.description("test-sign-key")
.keySpec(KeySpec.ECC_SECG_P256_K1)
.keyUsage("SIGN_VERIFY"));
String signKeyId = response.keyMetadata().keyId();
assertThat(response.keyMetadata().signingAlgorithms()).isNotEmpty();
assertThat(response.keyMetadata().keySpec()).isNotNull();
assertThat(response.keyMetadata().signingAlgorithms()).contains(SigningAlgorithmSpec.ECDSA_SHA_256);
assertThat(signKeyId).isNotNull();
DescribeKeyResponse describeKeyResponse = kms.describeKey(b -> b.keyId(signKeyId));
assertThat(describeKeyResponse.keyMetadata().signingAlgorithms()).isNotEmpty();
assertThat(describeKeyResponse.keyMetadata().signingAlgorithms()).contains(SigningAlgorithmSpec.ECDSA_SHA_256);
assertThat(describeKeyResponse.keyMetadata().keySpec()).isNotNull();
assertThat(describeKeyResponse.keyMetadata().keyId()).isEqualTo(signKeyId);
}
@Test
@Order(21)
void describeSignVerifyOtherKey() {
CreateKeyResponse response = kms.createKey(b -> b.description("test-sign-key")
.keySpec(KeySpec.RSA_2048)
.keyUsage("ENCRYPT_DECRYPT"));
String signKeyId = response.keyMetadata().keyId();
assertThat(response.keyMetadata().signingAlgorithms()).isEmpty();
assertThat(response.keyMetadata().keySpec()).isNotNull();
assertThat(response.keyMetadata().encryptionAlgorithms()).contains(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_1);
assertThat(signKeyId).isNotNull();
DescribeKeyResponse describeKeyResponse = kms.describeKey(b -> b.keyId(signKeyId));
assertThat(describeKeyResponse.keyMetadata().encryptionAlgorithms()).isNotEmpty();
assertThat(describeKeyResponse.keyMetadata().encryptionAlgorithms()).contains(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256);
assertThat(describeKeyResponse.keyMetadata().keySpec()).isNotNull();
assertThat(describeKeyResponse.keyMetadata().keyId()).isEqualTo(signKeyId);
}
@Test
@Order(22)
void describeHmacKey() {
CreateKeyResponse response = kms.createKey(b -> b.description("test-sign-key")
.keySpec(KeySpec.HMAC_224)
.keyUsage("GENERATE_VERIFY_MAC"));
String signKeyId = response.keyMetadata().keyId();
assertThat(response.keyMetadata().signingAlgorithms()).isEmpty();
assertThat(response.keyMetadata().encryptionAlgorithms()).isEmpty();
assertThat(response.keyMetadata().keySpec()).isNotNull();
assertThat(response.keyMetadata().macAlgorithms()).contains(MacAlgorithmSpec.HMAC_SHA_224);
assertThat(signKeyId).isNotNull();
DescribeKeyResponse describeKeyResponse = kms.describeKey(b -> b.keyId(signKeyId));
assertThat(describeKeyResponse.keyMetadata().macAlgorithms()).isNotEmpty();
assertThat(describeKeyResponse.keyMetadata().macAlgorithms()).contains(MacAlgorithmSpec.HMAC_SHA_224);
assertThat(describeKeyResponse.keyMetadata().keySpec()).isNotNull();
assertThat(describeKeyResponse.keyMetadata().keyId()).isEqualTo(signKeyId);
}
@Test
@Order(23)
void generateAndVerifyMac() {
CreateKeyResponse createResponse = kms.createKey(b -> b
.description("hmac-test-key")
.keySpec(KeySpec.HMAC_256)
.keyUsage(KeyUsageType.GENERATE_VERIFY_MAC));
String hmacKeyId = createResponse.keyMetadata().keyId();
SdkBytes msg = SdkBytes.fromString("message for mac", StandardCharsets.UTF_8);
GenerateMacResponse generateMacResponse = kms.generateMac(b -> b
.keyId(hmacKeyId)
.message(msg)
.macAlgorithm(MacAlgorithmSpec.HMAC_SHA_256));
assertThat(generateMacResponse.mac()).isNotNull();
VerifyMacResponse verifyMacResponse = kms.verifyMac(b -> b
.keyId(hmacKeyId)
.message(msg)
.mac(generateMacResponse.mac())
.macAlgorithm(MacAlgorithmSpec.HMAC_SHA_256));
assertThat(verifyMacResponse.macValid()).isTrue();
}
}
@@ -11,14 +11,14 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
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.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.Response;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
@ApplicationScoped
public class KmsJsonHandler {
@@ -81,16 +81,16 @@ public class KmsJsonHandler {
private Response handleCreateKey(JsonNode request, String region) {
String description = request.path("Description").asText(null);
String keyUsage = request.path("KeyUsage").asText("ENCRYPT_DECRYPT");
String customerMasterKeySpec = !request.path("KeySpec").isMissingNode()
String keySpec = !request.path("KeySpec").isMissingNode()
? request.path("KeySpec").asText("SYMMETRIC_DEFAULT")
: request.path("CustomerMasterKeySpec").asText("SYMMETRIC_DEFAULT");
String policy = request.path("Policy").isMissingNode() ? null : request.path("Policy").asText(null);
Map<String, String> tags = new HashMap<>();
request.path("Tags").forEach(t -> tags.put(t.path("TagKey").asText(), t.path("TagValue").asText()));
KmsKey key = service.createKey(description, keyUsage, customerMasterKeySpec, policy, tags, region);
KmsKey key = service.createKey(description, keyUsage, keySpec, policy, tags, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("KeyMetadata", keyToNode(key));
response.set("KeyMetadata", addKeyMetadata(key));
return Response.ok(response).build();
}
@@ -101,30 +101,11 @@ public class KmsJsonHandler {
ObjectNode response = objectMapper.createObjectNode();
response.put("KeyId", key.getArn());
response.put("PublicKey", key.getPublicKeyEncoded());
response.put("CustomerMasterKeySpec", key.getCustomerMasterKeySpec());
response.put("KeyUsage", key.getKeyUsage());
response.put("CustomerMasterKeySpec", key.getKeySpec().name());
response.put("KeySpec", key.getKeySpec().name());
response.put("KeyUsage", key.getKeyUsage().name());
if ("SIGN_VERIFY".equals(key.getKeyUsage())) {
ArrayNode algs = response.putArray("SigningAlgorithms");
if (key.getCustomerMasterKeySpec().startsWith("RSA")) {
algs.add("RSASSA_PSS_SHA_256");
algs.add("RSASSA_PSS_SHA_384");
algs.add("RSASSA_PSS_SHA_512");
algs.add("RSASSA_PKCS1_V1_5_SHA_256");
algs.add("RSASSA_PKCS1_V1_5_SHA_384");
algs.add("RSASSA_PKCS1_V1_5_SHA_512");
} else {
algs.add("ECDSA_SHA_256");
algs.add("ECDSA_SHA_384");
algs.add("ECDSA_SHA_512");
}
} else {
ArrayNode algs = response.putArray("EncryptionAlgorithms");
if (key.getCustomerMasterKeySpec().startsWith("RSA")) {
algs.add("RSAES_OAEP_SHA_1");
algs.add("RSAES_OAEP_SHA_256");
}
}
addAlgorithms(key, response);
return Response.ok(response).build();
}
@@ -133,7 +114,7 @@ public class KmsJsonHandler {
String keyId = request.path("KeyId").asText();
KmsKey key = service.describeKey(keyId, region);
ObjectNode response = objectMapper.createObjectNode();
response.set("KeyMetadata", keyToNode(key));
response.set("KeyMetadata", addKeyMetadata(key));
return Response.ok(response).build();
}
@@ -334,7 +315,7 @@ public class KmsJsonHandler {
String keyId = request.path("KeyId").asText();
byte[] message = Base64.getDecoder().decode(request.path("Message").asText());
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
String messageType = request.path("MessageType").asText("RAW");
KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));
byte[] signature = service.sign(keyId, message, algorithm, messageType, region);
@@ -350,7 +331,7 @@ public class KmsJsonHandler {
byte[] message = Base64.getDecoder().decode(request.path("Message").asText());
byte[] signature = Base64.getDecoder().decode(request.path("Signature").asText());
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
String messageType = request.path("MessageType").asText("RAW");
KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));
boolean valid = service.verify(keyId, message, signature, algorithm, messageType, region);
@@ -547,28 +528,25 @@ public class KmsJsonHandler {
return Response.ok(response).build();
}
private ObjectNode keyToNode(KmsKey k) {
ObjectNode node = objectMapper.createObjectNode();
node.put("AWSAccountId", regionResolver.getAccountId());
node.put("KeyId", k.getKeyId());
node.put("Arn", k.getArn());
node.put("CreationDate", k.getCreationDate());
node.put("Enabled", k.isEnabled());
node.put("Description", k.getDescription());
node.put("KeyUsage", k.getKeyUsage());
node.put("KeyState", k.getKeyState());
node.put("Origin", "AWS_KMS");
node.put("KeyManager", "CUSTOMER");
node.put("CustomerMasterKeySpec", k.getCustomerMasterKeySpec());
node.put("KeySpec", k.getCustomerMasterKeySpec());
String macAlgo = KmsService.macAlgorithmFor(k.getCustomerMasterKeySpec());
if (macAlgo != null) {
node.putArray("MacAlgorithms").add(macAlgo);
}
private ObjectNode addKeyMetadata(KmsKey k) {
ObjectNode keyMetadata = objectMapper.createObjectNode();
keyMetadata.put("AWSAccountId", regionResolver.getAccountId());
keyMetadata.put("KeyId", k.getKeyId());
keyMetadata.put("Arn", k.getArn());
keyMetadata.put("CreationDate", k.getCreationDate());
keyMetadata.put("Enabled", k.isEnabled());
keyMetadata.put("Description", k.getDescription());
keyMetadata.put("KeyUsage", k.getKeyUsage().name());
keyMetadata.put("KeyState", k.getKeyState());
keyMetadata.put("Origin", "AWS_KMS");
keyMetadata.put("KeyManager", "CUSTOMER");
keyMetadata.put("CustomerMasterKeySpec", k.getKeySpec().name());
keyMetadata.put("KeySpec", k.getKeySpec().name());
addAlgorithms(k, keyMetadata);
if (k.getDeletionDate() > 0) {
node.put("DeletionDate", k.getDeletionDate());
keyMetadata.put("DeletionDate", k.getDeletionDate());
}
return node;
return keyMetadata;
}
private ObjectNode errorResponse(String code, String message) {
@@ -577,4 +555,30 @@ public class KmsJsonHandler {
error.put("message", message);
return error;
}
private void addAlgorithms(KmsKey key, ObjectNode response) {
if (KmsKeyUsage.SIGN_VERIFY == key.getKeyUsage()) {
ArrayNode signingAlgorithms = response.putArray("SigningAlgorithms");
key.getKeySpec().getAlgorithm()
.stream()
.filter(algorithm -> algorithm.getKeyUsage() == KmsKeyUsage.SIGN_VERIFY)
.map(KmsKeySpec.Algorithm::getAlgName)
.filter(Objects::nonNull)
.forEach(signingAlgorithms::add);
} else if (KmsKeyUsage.ENCRYPT_DECRYPT == key.getKeyUsage()) {
if (key.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA
|| key.getKeySpec().getKeyType() == KmsKeySpec.KeyType.SYMMETRIC) {
ArrayNode encryptionAlgorithms = response.putArray("EncryptionAlgorithms");
key.getKeySpec().getAlgorithm()
.stream()
.filter(algorithm -> algorithm.getKeyUsage() == KmsKeyUsage.ENCRYPT_DECRYPT)
.map(KmsKeySpec.Algorithm::getAlgName)
.filter(Objects::nonNull)
.forEach(encryptionAlgorithms::add);
}
} else if (KmsKeyUsage.GENERATE_VERIFY_MAC == key.getKeyUsage()
&& key.getKeySpec().getKeyType() == KmsKeySpec.KeyType.HMAC) {
response.putArray("MacAlgorithms").add(key.getKeySpec().getAlgorithm().getFirst().getAlgName());
}
}
}
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.kms;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.ReservedTags;
@@ -8,7 +9,9 @@ import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.kms.model.KmsAlias;
import io.github.hectorvent.floci.services.kms.model.KmsGrant;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
import com.fasterxml.jackson.core.type.TypeReference;
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.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.bouncycastle.asn1.ASN1Integer;
@@ -44,11 +47,16 @@ import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.*;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.DIGEST;
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
@ApplicationScoped
public class KmsService {
@@ -63,11 +71,11 @@ public class KmsService {
@Inject
public KmsService(StorageFactory storageFactory, RegionResolver regionResolver) {
this(storageFactory.create("kms", "kms-keys.json",
new TypeReference<Map<String, KmsKey>>() {}),
new TypeReference<>() {}),
storageFactory.create("kms", "kms-aliases.json",
new TypeReference<Map<String, KmsAlias>>() {}),
new TypeReference<>() {}),
storageFactory.create("kms", "kms-grants.json",
new TypeReference<Map<String, KmsGrant>>() {}),
new TypeReference<>() {}),
regionResolver);
}
@@ -116,15 +124,19 @@ public class KmsService {
return createKey(description, "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", policy, tags, region);
}
public KmsKey createKey(String description, String keyUsage, String customerMasterKeySpec, String policy, Map<String, String> tags, String region) {
public KmsKey createKey(String description, String keyUsage, String keySpec, String policy, Map<String, String> tags, String region) {
String keyId = resolveKeyId(tags);
if (keyStore.get(region + "::" + keyId).isPresent()) {
throw new AwsException("AlreadyExistsException", "Key already exists", 400);
}
String arn = regionResolver.buildArn("kms", region, "key/" + keyId);
String effectiveUsage = keyUsage != null ? keyUsage : "ENCRYPT_DECRYPT";
String effectiveSpec = customerMasterKeySpec != null ? customerMasterKeySpec : "SYMMETRIC_DEFAULT";
KmsKeyUsage effectiveUsage = Optional.ofNullable(keyUsage)
.map(KmsKeyUsage::fromString)
.orElse(KmsKeyUsage.ENCRYPT_DECRYPT);
KmsKeySpec effectiveSpec = Optional.of(keySpec)
.map(KmsKeySpec::fromString)
.orElse(KmsKeySpec.SYMMETRIC_DEFAULT);
validateKeyUsageForSpec(effectiveUsage, effectiveSpec);
KmsKey key = new KmsKey();
@@ -132,14 +144,14 @@ public class KmsService {
key.setArn(arn);
key.setDescription(description);
key.setKeyUsage(effectiveUsage);
key.setCustomerMasterKeySpec(effectiveSpec);
key.setKeySpec(effectiveSpec);
key.setPolicy(policy != null ? policy : buildDefaultKeyPolicy());
key.getTags().putAll(ReservedTags.stripReservedTags(tags));
generateKeyMaterial(key);
keyStore.put(region + "::" + keyId, key);
LOG.infov("Created KMS key: {0} ({1}/{2}) in {3}", keyId, key.getKeyUsage(), key.getCustomerMasterKeySpec(), region);
LOG.infov("Created KMS key: {0} ({1}/{2}) in {3}", keyId, key.getKeyUsage(), key.getKeySpec(), region);
return key;
}
@@ -160,104 +172,86 @@ public class KmsService {
}
private void generateKeyMaterial(KmsKey key) {
String spec = key.getCustomerMasterKeySpec();
if ("SYMMETRIC_DEFAULT".equals(spec)) {
return; // Use existing mock behavior for symmetric keys
}
if (isHmac(spec)) {
// HMAC keys are symmetric byte strings; generate outside the try block
// so ValidationException (400) isn't rewrapped as InternalFailure (500).
byte[] material = new byte[hmacKeyByteLength(spec)];
new SecureRandom().nextBytes(material);
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));
return;
}
KmsKeySpec spec = key.getKeySpec();
try {
KeyPairGenerator generator;
if (spec.startsWith("RSA_")) {
generator = KeyPairGenerator.getInstance("RSA");
int size = Integer.parseInt(spec.substring(4));
generator.initialize(size);
} else if (spec.startsWith("ECC_")) {
String curveName = switch (spec) {
case "ECC_NIST_P256" -> "secp256r1";
case "ECC_NIST_P384" -> "secp384r1";
case "ECC_NIST_P521" -> "secp521r1";
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);
}
switch (spec.getKeyType()) {
case HMAC -> {
// HMAC keys are symmetric byte strings; generate outside the try block
// so ValidationException (400) isn't rewrapped as InternalFailure (500).
byte[] material = new byte[hmacKeyByteLength(spec)];
new SecureRandom().nextBytes(material);
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));
}
case SYMMETRIC -> {/* // Use existing mock behavior for symmetric keys */}
case RSA -> {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
int size = Integer.parseInt(spec.name().substring(4));
generator.initialize(size);
KeyPair pair = generator.generateKeyPair();
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
}
case ECC -> {
String curveName = spec.curveName();
KeyPair pair = generator.generateKeyPair();
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
} catch (Exception e) {
// 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).
KeyPairGenerator generator = isSecgP256k1(spec)
? new KeyPairGeneratorSpi.EC()
: KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec(curveName));
KeyPair pair = generator.generateKeyPair();
key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(pair.getPrivate().getEncoded()));
key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(pair.getPublic().getEncoded()));
}
default ->
throw new AwsException("InvalidCustomerMasterKeySpecException", "Unsupported key spec: " + spec, 400);
}
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
throw new AwsException("InternalFailure", "Failed to generate key material: " + e.getMessage(), 500);
}
}
public KmsKey getPublicKey(String keyId, String region) {
KmsKey key = resolveKey(keyId, region);
String spec = key.getCustomerMasterKeySpec();
if ("SYMMETRIC_DEFAULT".equals(spec) || isHmac(spec)) {
KmsKeySpec spec = key.getKeySpec();
if (KmsKeySpec.SYMMETRIC_DEFAULT == spec || isHmac(spec)) {
throw new AwsException("UnsupportedOperationException", "GetPublicKey is not supported for symmetric keys.", 400);
}
return key;
}
private static boolean isHmac(String spec) {
return spec != null && spec.startsWith("HMAC_");
private static boolean isHmac(KmsKeySpec spec) {
return spec != null && spec.getKeyType() == KmsKeySpec.KeyType.HMAC;
}
private static void validateKeyUsageForSpec(String keyUsage, String spec) {
if (isHmac(spec) && !"GENERATE_VERIFY_MAC".equals(keyUsage)) {
private static void validateKeyUsageForSpec(KmsKeyUsage keyUsage, KmsKeySpec spec) {
if (isHmac(spec) && KmsKeyUsage.GENERATE_VERIFY_MAC != keyUsage) {
throw new AwsException("ValidationException",
"KeyUsage " + keyUsage + " is not compatible with KeySpec " + spec
+ ". HMAC key specs require KeyUsage GENERATE_VERIFY_MAC.",
400);
}
if ("GENERATE_VERIFY_MAC".equals(keyUsage) && !isHmac(spec)) {
if (KmsKeyUsage.GENERATE_VERIFY_MAC == keyUsage && !isHmac(spec)) {
throw new AwsException("ValidationException",
"KeyUsage GENERATE_VERIFY_MAC requires an HMAC KeySpec (HMAC_224, HMAC_256, HMAC_384, or HMAC_512).",
400);
}
}
private static int hmacKeyByteLength(String spec) {
private static int hmacKeyByteLength(KmsKeySpec spec) {
return switch (spec) {
case "HMAC_224" -> 28;
case "HMAC_256" -> 32;
case "HMAC_384" -> 48;
case "HMAC_512" -> 64;
case HMAC_224 -> 28;
case HMAC_256 -> 32;
case HMAC_384 -> 48;
case HMAC_512 -> 64;
default -> throw new AwsException("InvalidCustomerMasterKeySpecException",
"Unsupported HMAC key spec: " + spec, 400);
};
}
static String macAlgorithmFor(String spec) {
if (!isHmac(spec)) {
return null;
}
return switch (spec) {
case "HMAC_224" -> "HMAC_SHA_224";
case "HMAC_256" -> "HMAC_SHA_256";
case "HMAC_384" -> "HMAC_SHA_384";
case "HMAC_512" -> "HMAC_SHA_512";
default -> null;
};
}
public KmsKey describeKey(String keyId, String region) {
return resolveKey(keyId, region);
}
@@ -506,8 +500,8 @@ public class KmsService {
public boolean getKeyRotationStatus(String keyId, String region) {
KmsKey key = resolveKey(keyId, region);
if (!"ENCRYPT_DECRYPT".equals(key.getKeyUsage())
|| !"SYMMETRIC_DEFAULT".equals(key.getCustomerMasterKeySpec())) {
if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()
|| KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {
return false;
}
return key.isKeyRotationEnabled();
@@ -567,8 +561,8 @@ public class KmsService {
}
private void validateRotationSupported(KmsKey key) {
if (!"ENCRYPT_DECRYPT".equals(key.getKeyUsage())
|| !"SYMMETRIC_DEFAULT".equals(key.getCustomerMasterKeySpec())) {
if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()
|| KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {
throw new AwsException(
"UnsupportedOperationException",
"You cannot perform this operation on a non-symmetric key or a key with non-ENCRYPT_DECRYPT key usage.",
@@ -731,31 +725,29 @@ public class KmsService {
}
public byte[] sign(String keyId, byte[] message, String algorithm, String region) {
return sign(keyId, message, algorithm, "RAW", region);
return sign(keyId, message, algorithm, RAW, region);
}
public byte[] sign(String keyId, byte[] message, String algorithm, String messageType, String region) {
public byte[] sign(String keyId, byte[] message, String algorithm, KmsMessageType messageType, String region) {
KmsKey kmsKey = resolveKey(keyId, region);
if ("SYMMETRIC_DEFAULT".equals(kmsKey.getCustomerMasterKeySpec())) {
if (KmsKeySpec.SYMMETRIC_DEFAULT == kmsKey.getKeySpec()) {
throw new AwsException("UnsupportedOperationException", "Unsupported key spec for signing.", 400);
}
try {
PrivateKey privateKey = loadPrivateKey(kmsKey.getPrivateKeyEncoded(), kmsKey.getCustomerMasterKeySpec());
String jcaAlgo = mapAlgorithm(algorithm);
if ("DIGEST".equals(messageType)) {
PrivateKey privateKey = loadPrivateKey(kmsKey.getPrivateKeyEncoded(), kmsKey.getKeySpec());
String jcaAlgo = switch (messageType) {
// If message is already a digest, we need a "NONEwith..." algorithm
jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA");
if (algorithm.startsWith("RSASSA_PKCS1_V1_5")) {
// RFC 8017 9.2: PKCS#1 v1.5 signs DigestInfo{hashOID, digest}, not the
// bare digest, so the signature validates with external verifiers and
// real KMS (NONEwithRSA only pads the bytes it is given).
message = wrapInDigestInfo(message, algorithm);
}
case DIGEST -> "NONEwith" + (kmsKey.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA ? "RSA" : "ECDSA");
case RAW -> KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName();
};
if (messageType == DIGEST && isPKCS1v1_5(kmsKey.getKeySpec().getAlgorithm().getFirst())) {
// RFC 8017 9.2: PKCS#1 v1.5 signs DigestInfo{hashOID, digest}, not the
// bare digest, so the signature validates with external verifiers and
// real KMS (NONEwithRSA only pads the bytes it is given).
message = wrapInDigestInfo(message, algorithm);
}
if (isSecgP256k1(kmsKey.getCustomerMasterKeySpec())) {
if (isSecgP256k1(kmsKey.getKeySpec())) {
return signSecgP256k1(privateKey, message, jcaAlgo);
}
Signature sig = Signature.getInstance(jcaAlgo);
@@ -768,28 +760,27 @@ public class KmsService {
}
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {
return verify(keyId, message, signature, algorithm, "RAW", region);
return verify(keyId, message, signature, algorithm, RAW, region);
}
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String messageType, String region) {
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, KmsMessageType messageType, String region) {
KmsKey kmsKey = resolveKey(keyId, region);
if ("SYMMETRIC_DEFAULT".equals(kmsKey.getCustomerMasterKeySpec())) {
if (KmsKeySpec.SYMMETRIC_DEFAULT == kmsKey.getKeySpec()) {
return false;
}
try {
PublicKey publicKey = loadPublicKey(kmsKey.getPublicKeyEncoded(), kmsKey.getCustomerMasterKeySpec());
String jcaAlgo = mapAlgorithm(algorithm);
if ("DIGEST".equals(messageType)) {
jcaAlgo = "NONEwith" + (kmsKey.getCustomerMasterKeySpec().startsWith("RSA") ? "RSA" : "ECDSA");
if (algorithm.startsWith("RSASSA_PKCS1_V1_5")) {
PublicKey publicKey = loadPublicKey(kmsKey.getPublicKeyEncoded(), kmsKey.getKeySpec());
String jcaAlgo = KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName();
if (DIGEST.equals(messageType)) {
jcaAlgo = "NONEwith" + (kmsKey.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA ? "RSA" : "ECDSA");
if (isPKCS1v1_5(kmsKey.getKeySpec().getAlgorithm().getFirst())) {
// Mirror sign(): verify against DigestInfo{hashOID, digest} (RFC 8017 9.2).
message = wrapInDigestInfo(message, algorithm);
}
}
if (isSecgP256k1(kmsKey.getCustomerMasterKeySpec())) {
if (isSecgP256k1(kmsKey.getKeySpec())) {
return verifySecgP256k1(publicKey, message, signature, jcaAlgo);
}
Signature sig = Signature.getInstance(jcaAlgo);
@@ -851,13 +842,13 @@ public class KmsService {
private KmsKey validateMacOperationKey(String keyId, String algorithm, String region) {
KmsKey kmsKey = resolveKey(keyId, region);
String spec = kmsKey.getCustomerMasterKeySpec();
if (!isHmac(spec) || !"GENERATE_VERIFY_MAC".equals(kmsKey.getKeyUsage())) {
KmsKeySpec spec = kmsKey.getKeySpec();
if (!isHmac(spec) || !KmsKeyUsage.GENERATE_VERIFY_MAC.equals(kmsKey.getKeyUsage())) {
throw new AwsException("InvalidKeyUsageException",
"MAC operations require an HMAC key with KeyUsage GENERATE_VERIFY_MAC.", 400);
}
String expectedAlgorithm = macAlgorithmFor(spec);
String expectedAlgorithm = kmsKey.getKeySpec().getAlgorithm().getFirst().getAlgName();
if (!Objects.equals(expectedAlgorithm, algorithm)) {
throw new AwsException("InvalidKeyUsageException",
"MacAlgorithm " + algorithm + " is not valid for KeySpec " + spec + ".", 400);
@@ -891,7 +882,7 @@ public class KmsService {
}
}
private PrivateKey loadPrivateKey(String encoded, String spec) throws Exception {
private PrivateKey loadPrivateKey(String encoded, KmsKeySpec spec) throws Exception {
byte[] decoded = Base64.getDecoder().decode(encoded);
if (isSecgP256k1(spec)) {
// For secp256k1, use BC's KeyFactorySpi.EC directly as AsymmetricKeyInfoConverter.
@@ -903,7 +894,7 @@ public class KmsService {
return buildKeyFactory(spec).generatePrivate(new PKCS8EncodedKeySpec(decoded));
}
private PublicKey loadPublicKey(String encoded, String spec) throws Exception {
private PublicKey loadPublicKey(String encoded, KmsKeySpec spec) throws Exception {
byte[] decoded = Base64.getDecoder().decode(encoded);
if (isSecgP256k1(spec)) {
AsymmetricKeyInfoConverter converter = new KeyFactorySpi.EC();
@@ -935,21 +926,6 @@ public class KmsService {
}
}
private String mapAlgorithm(String awsAlgo) {
return switch (awsAlgo) {
case "ECDSA_SHA_256" -> "SHA256withECDSA";
case "ECDSA_SHA_384" -> "SHA384withECDSA";
case "ECDSA_SHA_512" -> "SHA512withECDSA";
case "RSASSA_PSS_SHA_256" -> "SHA256withRSA/PSS";
case "RSASSA_PSS_SHA_384" -> "SHA384withRSA/PSS";
case "RSASSA_PSS_SHA_512" -> "SHA512withRSA/PSS";
case "RSASSA_PKCS1_V1_5_SHA_256" -> "SHA256withRSA";
case "RSASSA_PKCS1_V1_5_SHA_384" -> "SHA384withRSA";
case "RSASSA_PKCS1_V1_5_SHA_512" -> "SHA512withRSA";
default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + awsAlgo, 400);
};
}
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {
return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);
}
@@ -988,8 +964,14 @@ public class KmsService {
// ──────────────────────────── Helpers ────────────────────────────
private static boolean isSecgP256k1(String spec) {
return "ECC_SECG_P256K1".equals(spec);
private static boolean isSecgP256k1(KmsKeySpec spec) {
return KmsKeySpec.ECC_SECG_P256K1 == spec;
}
private static boolean isPKCS1v1_5(KmsKeySpec.Algorithm spec) {
return spec == KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_256
|| spec == KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_384
|| spec == KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_512;
}
/**
@@ -1020,7 +1002,9 @@ public class KmsService {
return bOut.toByteArray();
}
/** Verifies a DER-encoded ECDSA signature over secp256k1. */
/**
* 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());
@@ -1047,8 +1031,8 @@ public class KmsService {
return MessageDigest.getInstance(mdAlgo).digest(message);
}
private static KeyFactory buildKeyFactory(String spec) throws Exception {
return KeyFactory.getInstance(spec.startsWith("RSA") ? "RSA" : "EC");
private static KeyFactory buildKeyFactory(KmsKeySpec spec) throws Exception {
return KeyFactory.getInstance(spec.getKeyType() == KmsKeySpec.KeyType.RSA ? "RSA" : "EC");
}
private KmsKey resolveKey(String keyIdOrArn, String region) {
@@ -15,8 +15,8 @@ public class KmsKey {
private String description;
private boolean enabled = true;
private String keyState = "Enabled"; // Enabled, Disabled, PendingDeletion
private String keyUsage = "ENCRYPT_DECRYPT";
private String customerMasterKeySpec = "SYMMETRIC_DEFAULT";
private KmsKeyUsage keyUsage = KmsKeyUsage.ENCRYPT_DECRYPT;
private KmsKeySpec keySpec = KmsKeySpec.SYMMETRIC_DEFAULT;
private long creationDate;
private long deletionDate;
private String policy;
@@ -45,11 +45,11 @@ public class KmsKey {
public String getKeyState() { return keyState; }
public void setKeyState(String keyState) { this.keyState = keyState; }
public String getKeyUsage() { return keyUsage; }
public void setKeyUsage(String keyUsage) { this.keyUsage = keyUsage; }
public KmsKeyUsage getKeyUsage() { return keyUsage; }
public void setKeyUsage(KmsKeyUsage keyUsage) { this.keyUsage = keyUsage; }
public String getCustomerMasterKeySpec() { return customerMasterKeySpec; }
public void setCustomerMasterKeySpec(String spec) { this.customerMasterKeySpec = spec; }
public KmsKeySpec getKeySpec() { return keySpec; }
public void setKeySpec(KmsKeySpec spec) { this.keySpec = spec; }
public long getCreationDate() { return creationDate; }
public void setCreationDate(long creationDate) { this.creationDate = creationDate; }
@@ -0,0 +1,151 @@
package io.github.hectorvent.floci.services.kms.model;
import io.github.hectorvent.floci.core.common.AwsException;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
@RegisterForReflection
public enum KmsKeySpec {
SYMMETRIC_DEFAULT(KeyType.SYMMETRIC, List.of(Algorithm.SYMMETRIC_DEFAULT)),
RSA_2048(KeyType.RSA, getRsaAlgos()),
RSA_3072(KeyType.RSA, getRsaAlgos()),
RSA_4096(KeyType.RSA, getRsaAlgos()),
ECC_NIST_P256(KeyType.ECC, Algorithm.ECDSA_SHA_256,"secp256r1"),
ECC_NIST_P384(KeyType.ECC, Algorithm.ECDSA_SHA_384,"secp384r1"),
ECC_NIST_P521(KeyType.ECC, Algorithm.ECDSA_SHA_512, "secp521r1"),
ECC_NIST_EDWARDS25519(KeyType.ECC, List.of(Algorithm.ED25519_SHA_512, Algorithm.ED25519_PH_SHA_512),"secp521r1"),
ECC_SECG_P256K1(KeyType.ECC, Algorithm.ECDSA_SHA_256,"secp256k1"),
HMAC_224(KeyType.HMAC, Algorithm.HMAC_SHA_224),
HMAC_256(KeyType.HMAC, Algorithm.HMAC_SHA_256),
HMAC_384(KeyType.HMAC, Algorithm.HMAC_SHA_384),
HMAC_512(KeyType.HMAC, Algorithm.HMAC_SHA_512),
SM2(KeyType.SM2, Algorithm.SM2_DSA),
ML_DSA_44(KeyType.ML_DSA, Algorithm.ML_DSA_SHAKE_256),
ML_DSA_65(KeyType.ML_DSA, Algorithm.ML_DSA_SHAKE_256),
ML_DSA_87(KeyType.ML_DSA, Algorithm.ML_DSA_SHAKE_256);
KmsKeySpec(KeyType keyType, Algorithm algorithm) {
this.keyType = keyType;
this.algorithm = List.of(algorithm);
this.curveName = null;
}
KmsKeySpec(KeyType keyType, Algorithm algorithm, String curveName) {
this.keyType = keyType;
this.algorithm = List.of(algorithm);
this.curveName = curveName;
}
KmsKeySpec(KeyType keyType, List<Algorithm> algorithm) {
this.keyType = keyType;
this.algorithm = algorithm;
this.curveName = null;
}
KmsKeySpec(KeyType keyType, List<Algorithm> algorithm, String curveName) {
this.keyType = keyType;
this.algorithm = algorithm;
this.curveName = curveName;
}
private final KeyType keyType;
private final List<Algorithm> algorithm;
private final String curveName;
public static KmsKeySpec fromString(String keySpec) {
try {
return KmsKeySpec.valueOf(keySpec);
} catch (IllegalArgumentException _) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + keySpec + "' at 'KeySpec' failed to satisfy constraint", 400);
}
}
public KeyType getKeyType() {
return keyType;
}
public List<Algorithm> getAlgorithm() {
return algorithm;
}
public String curveName() {
return curveName;
}
public enum KeyType {
RSA, ECC, SYMMETRIC, HMAC, ML_DSA, SM2
}
private static List<Algorithm> getRsaAlgos() {
return List.of(Algorithm.RSASSA_PKCS1_V1_5_SHA_256, Algorithm.RSASSA_PKCS1_V1_5_SHA_384, Algorithm.RSASSA_PKCS1_V1_5_SHA_512,
Algorithm.RSASSA_PSS_SHA_256, Algorithm.RSASSA_PSS_SHA_384, Algorithm.RSASSA_PSS_SHA_512,
Algorithm.RSAES_OAEP_SHA_1, Algorithm.RSAES_OAEP_SHA_256);
}
public static Algorithm getSignVerifyAlgorithm(String signingAlgorithm) {
try {
return Algorithm.valueOf(signingAlgorithm);
} catch (IllegalArgumentException _) {
throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + signingAlgorithm, 400);
}
}
public enum Algorithm {
SYMMETRIC_DEFAULT("SYMMETRIC_DEFAULT", "", KmsKeyUsage.ENCRYPT_DECRYPT),
RSASSA_PSS_SHA_256("RSASSA_PSS_SHA_256","SHA256withRSA/PSS", KmsKeyUsage.SIGN_VERIFY),
RSASSA_PSS_SHA_384("RSASSA_PSS_SHA_384","SHA384withRSA/PSS", KmsKeyUsage.SIGN_VERIFY),
RSASSA_PSS_SHA_512("RSASSA_PSS_SHA_512", "SHA512withRSA/PSS", KmsKeyUsage.SIGN_VERIFY),
RSASSA_PKCS1_V1_5_SHA_256("RSASSA_PKCS1_V1_5_SHA_256","SHA256withRSA", KmsKeyUsage.SIGN_VERIFY),
RSASSA_PKCS1_V1_5_SHA_384("RSASSA_PKCS1_V1_5_SHA_384", "SHA384withRSA", KmsKeyUsage.SIGN_VERIFY),
RSASSA_PKCS1_V1_5_SHA_512("RSASSA_PKCS1_V1_5_SHA_512", "SHA512withRSA", KmsKeyUsage.SIGN_VERIFY),
RSAES_OAEP_SHA_1("RSAES_OAEP_SHA_1", "", KmsKeyUsage.ENCRYPT_DECRYPT),
RSAES_OAEP_SHA_256("RSAES_OAEP_SHA_256", "", KmsKeyUsage.ENCRYPT_DECRYPT),
ECDSA_SHA_256("ECDSA_SHA_256", "SHA256withECDSA", KmsKeyUsage.SIGN_VERIFY),
ECDSA_SHA_384("ECDSA_SHA_384","SHA384withECDSA", KmsKeyUsage.SIGN_VERIFY),
ECDSA_SHA_512("ECDSA_SHA_512", "SHA512withECDSA", KmsKeyUsage.SIGN_VERIFY),
ED25519_SHA_512("ED25519_SHA_512","Ed25519", KmsKeyUsage.SIGN_VERIFY),
ED25519_PH_SHA_512("ED25519_PH_SHA_512", "Ed25519", KmsKeyUsage.SIGN_VERIFY),
SM2_DSA("SM2DSA","", KmsKeyUsage.SIGN_VERIFY),
ML_DSA_SHAKE_256("ML_DSA_SHAKE_256","", KmsKeyUsage.SIGN_VERIFY),
HMAC_SHA_224("HMAC_SHA_224",""),
HMAC_SHA_256("HMAC_SHA_256",""),
HMAC_SHA_384("HMAC_SHA_384",""),
HMAC_SHA_512("HMAC_SHA_512","");
private final String algName;
private final String javaName;
private KmsKeyUsage keyUsage;
Algorithm(String algName, String javaName) {
this.algName = algName;
this.javaName = javaName;
}
Algorithm(String algName, String javaName, KmsKeyUsage keyUsage) {
this.algName = algName;
this.javaName = javaName;
this.keyUsage = keyUsage;
}
public String getAlgName() {
return algName;
}
public String getJavaName() {
return javaName;
}
public KmsKeyUsage getKeyUsage() {
return keyUsage;
}
public static List<Algorithm> getAll() {
return new ArrayList<>(EnumSet.allOf(Algorithm.class));
}
}
}
@@ -0,0 +1,21 @@
package io.github.hectorvent.floci.services.kms.model;
import io.github.hectorvent.floci.core.common.AwsException;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum KmsKeyUsage {
SIGN_VERIFY,
ENCRYPT_DECRYPT,
GENERATE_VERIFY_MAC,
KEY_AGREEMENT;
public static KmsKeyUsage fromString(String usage) {
try {
return KmsKeyUsage.valueOf(usage);
} catch (IllegalArgumentException _) {
throw new AwsException("ValidationException",
"1 validation error detected: Value '" + usage + "' at 'KeyUsage' failed to satisfy constraint", 400);
}
}
}
@@ -0,0 +1,17 @@
package io.github.hectorvent.floci.services.kms.model;
import io.github.hectorvent.floci.core.common.AwsException;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public enum KmsMessageType {
RAW, DIGEST;
public static KmsMessageType fromString(String messageType) {
try {
return KmsMessageType.valueOf(messageType);
} catch (IllegalArgumentException _) {
throw new AwsException("ValidationException", "1 validation error detected: Value '" + messageType + "' at 'MessageType' failed to satisfy constraint", 400);
}
}
}
@@ -4,15 +4,19 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@QuarkusTest
class KmsIntegrationTest {
@@ -26,7 +30,7 @@ class KmsIntegrationTest {
@Test
void updateKeyDescriptionRoundTripThroughJsonHandler() {
String keyId = given()
var key = given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("""
@@ -39,7 +43,12 @@ class KmsIntegrationTest {
.then()
.statusCode(200)
.body("KeyMetadata.KeyId", notNullValue())
.extract().jsonPath().getString("KeyMetadata.KeyId");
.extract().jsonPath();
String keyId = key.getString("KeyMetadata.KeyId");
assertNotNull(keyId);
List<String> encryptionAlgorithms = key.getList("KeyMetadata.EncryptionAlgorithms");
assertEquals(List.of("SYMMETRIC_DEFAULT"), encryptionAlgorithms);
given()
.header("X-Amz-Target", "TrentService.UpdateKeyDescription")
@@ -67,7 +76,8 @@ class KmsIntegrationTest {
.post("/")
.then()
.statusCode(200)
.body("KeyMetadata.Description", equalTo("new description"));
.body("KeyMetadata.Description", equalTo("new description"))
.body("KeyMetadata.EncryptionAlgorithms", equalTo(List.of("SYMMETRIC_DEFAULT")));
}
@Test
@@ -955,4 +965,145 @@ class KmsIntegrationTest {
.statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@ParameterizedTest
@CsvSource({
"SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, EncryptionAlgorithms, SYMMETRIC_DEFAULT",
"RSA_2048, ENCRYPT_DECRYPT, EncryptionAlgorithms, 'RSAES_OAEP_SHA_1,RSAES_OAEP_SHA_256'",
"RSA_2048, SIGN_VERIFY, SigningAlgorithms, 'RSASSA_PKCS1_V1_5_SHA_256,RSASSA_PKCS1_V1_5_SHA_384,RSASSA_PKCS1_V1_5_SHA_512,RSASSA_PSS_SHA_256,RSASSA_PSS_SHA_384,RSASSA_PSS_SHA_512'",
"RSA_3072, ENCRYPT_DECRYPT, EncryptionAlgorithms, 'RSAES_OAEP_SHA_1,RSAES_OAEP_SHA_256'",
"RSA_3072, SIGN_VERIFY, SigningAlgorithms, 'RSASSA_PKCS1_V1_5_SHA_256,RSASSA_PKCS1_V1_5_SHA_384,RSASSA_PKCS1_V1_5_SHA_512,RSASSA_PSS_SHA_256,RSASSA_PSS_SHA_384,RSASSA_PSS_SHA_512'",
"RSA_4096, ENCRYPT_DECRYPT, EncryptionAlgorithms, 'RSAES_OAEP_SHA_1,RSAES_OAEP_SHA_256'",
"RSA_4096, SIGN_VERIFY, SigningAlgorithms, 'RSASSA_PKCS1_V1_5_SHA_256,RSASSA_PKCS1_V1_5_SHA_384,RSASSA_PKCS1_V1_5_SHA_512,RSASSA_PSS_SHA_256,RSASSA_PSS_SHA_384,RSASSA_PSS_SHA_512'",
"ECC_NIST_P256, SIGN_VERIFY, SigningAlgorithms, ECDSA_SHA_256",
"ECC_NIST_P384, SIGN_VERIFY, SigningAlgorithms, ECDSA_SHA_384",
"ECC_NIST_P521, SIGN_VERIFY, SigningAlgorithms, ECDSA_SHA_512",
"ECC_SECG_P256K1, SIGN_VERIFY, SigningAlgorithms, ECDSA_SHA_256",
"HMAC_224, GENERATE_VERIFY_MAC, MacAlgorithms, HMAC_SHA_224",
"HMAC_256, GENERATE_VERIFY_MAC, MacAlgorithms, HMAC_SHA_256",
"HMAC_384, GENERATE_VERIFY_MAC, MacAlgorithms, HMAC_SHA_384",
"HMAC_512, GENERATE_VERIFY_MAC, MacAlgorithms, HMAC_SHA_512"
})
void createKeyWithAllImplementedCombinations(String keySpec, String keyUsage, String algorithmField, String expectedAlgorithms) {
List<String> expectedList = List.of(expectedAlgorithms.split(","));
given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("""
{
"Description": "test key",
"KeyUsage": "%s",
"CustomerMasterKeySpec": "%s"
}
""".formatted(keyUsage, keySpec))
.when()
.post("/")
.then()
.statusCode(200)
.body("KeyMetadata.%s".formatted(algorithmField), equalTo(expectedList));
}
@ParameterizedTest
@CsvSource({
"SYMMETRIC_DEFAULT, ENCRYPT_DECRYPT, 200",
"SYMMETRIC_DEFAULT, SIGN_VERIFY, 200",
"SYMMETRIC_DEFAULT, GENERATE_VERIFY_MAC, 400",
"SYMMETRIC_DEFAULT, KEY_AGREEMENT, 200",
"RSA_2048, ENCRYPT_DECRYPT, 200",
"RSA_2048, SIGN_VERIFY, 200",
"RSA_2048, GENERATE_VERIFY_MAC, 400",
"RSA_2048, KEY_AGREEMENT, 200",
"RSA_3072, ENCRYPT_DECRYPT, 200",
"RSA_3072, SIGN_VERIFY, 200",
"RSA_3072, GENERATE_VERIFY_MAC, 400",
"RSA_3072, KEY_AGREEMENT, 200",
"RSA_4096, ENCRYPT_DECRYPT, 200",
"RSA_4096, SIGN_VERIFY, 200",
"RSA_4096, GENERATE_VERIFY_MAC, 400",
"RSA_4096, KEY_AGREEMENT, 200",
"ECC_NIST_P256, ENCRYPT_DECRYPT, 200",
"ECC_NIST_P256, SIGN_VERIFY, 200",
"ECC_NIST_P256, GENERATE_VERIFY_MAC, 400",
"ECC_NIST_P256, KEY_AGREEMENT, 200",
"ECC_NIST_P384, ENCRYPT_DECRYPT, 200",
"ECC_NIST_P384, SIGN_VERIFY, 200",
"ECC_NIST_P384, GENERATE_VERIFY_MAC, 400",
"ECC_NIST_P384, KEY_AGREEMENT, 200",
"ECC_NIST_P521, ENCRYPT_DECRYPT, 200",
"ECC_NIST_P521, SIGN_VERIFY, 200",
"ECC_NIST_P521, GENERATE_VERIFY_MAC, 400",
"ECC_NIST_P521, KEY_AGREEMENT, 200",
"ECC_NIST_EDWARDS25519, ENCRYPT_DECRYPT, 200",
"ECC_NIST_EDWARDS25519, SIGN_VERIFY, 200",
"ECC_NIST_EDWARDS25519, GENERATE_VERIFY_MAC, 400",
"ECC_NIST_EDWARDS25519, KEY_AGREEMENT, 200",
"ECC_SECG_P256K1, ENCRYPT_DECRYPT, 200",
"ECC_SECG_P256K1, SIGN_VERIFY, 200",
"ECC_SECG_P256K1, GENERATE_VERIFY_MAC, 400",
"ECC_SECG_P256K1, KEY_AGREEMENT, 200",
"HMAC_224, ENCRYPT_DECRYPT, 400",
"HMAC_224, SIGN_VERIFY, 400",
"HMAC_224, GENERATE_VERIFY_MAC, 200",
"HMAC_224, KEY_AGREEMENT, 400",
"HMAC_256, ENCRYPT_DECRYPT, 400",
"HMAC_256, SIGN_VERIFY, 400",
"HMAC_256, GENERATE_VERIFY_MAC, 200",
"HMAC_256, KEY_AGREEMENT, 400",
"HMAC_384, ENCRYPT_DECRYPT, 400",
"HMAC_384, SIGN_VERIFY, 400",
"HMAC_384, GENERATE_VERIFY_MAC, 200",
"HMAC_384, KEY_AGREEMENT, 400",
"HMAC_512, ENCRYPT_DECRYPT, 400",
"HMAC_512, SIGN_VERIFY, 400",
"HMAC_512, GENERATE_VERIFY_MAC, 200",
"HMAC_512, KEY_AGREEMENT, 400",
"SM2, ENCRYPT_DECRYPT, 400", // Not implemented
"SM2, SIGN_VERIFY, 400",
"SM2, GENERATE_VERIFY_MAC, 400",
"SM2, KEY_AGREEMENT, 400",
"ML_DSA_44, ENCRYPT_DECRYPT, 400", // Not implemented
"ML_DSA_44, SIGN_VERIFY, 400",
"ML_DSA_44, GENERATE_VERIFY_MAC, 400",
"ML_DSA_44, KEY_AGREEMENT, 400",
"ML_DSA_65, ENCRYPT_DECRYPT, 400",
"ML_DSA_65, SIGN_VERIFY, 400",
"ML_DSA_65, GENERATE_VERIFY_MAC, 400",
"ML_DSA_65, KEY_AGREEMENT, 400",
"ML_DSA_87, ENCRYPT_DECRYPT, 400",
"ML_DSA_87, SIGN_VERIFY, 400",
"ML_DSA_87, GENERATE_VERIFY_MAC, 400",
"ML_DSA_87, KEY_AGREEMENT, 400"
})
void createKeyWithCombinations(String keySpec, String keyUsage, int expectedStatusCode) {
given()
.header("X-Amz-Target", "TrentService.CreateKey")
.contentType(KMS_CONTENT_TYPE)
.body("""
{
"Description": "test key",
"KeyUsage": "%s",
"KeySpec": "%s"
}
""".formatted(keyUsage, keySpec))
.when()
.post("/")
.then()
.statusCode(expectedStatusCode);
}
}
@@ -7,6 +7,9 @@ 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.KmsGrant;
import io.github.hectorvent.floci.services.kms.model.KmsKey;
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 org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
@@ -789,11 +792,11 @@ class KmsServiceTest {
byte[] digest = MessageDigest.getInstance("SHA-512").digest(message);
byte[] sig = kmsService.sign(key.getKeyId(), digest,
"RSASSA_PKCS1_V1_5_SHA_512", "DIGEST", REGION);
"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION);
// floci's own Verify round-trips.
assertTrue(kmsService.verify(key.getKeyId(), digest, sig,
"RSASSA_PKCS1_V1_5_SHA_512", "DIGEST", REGION));
"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION));
// External verifier (standard JCA, standing in for openssl/python) reconstructs
// DigestInfo from the message hash and must validate the DIGEST signature (#1345).
@@ -819,9 +822,9 @@ class KmsServiceTest {
// PKCS#1 v1.5 is deterministic, so signing the digest (DIGEST) and signing the
// message (RAW) with the same algorithm must produce identical signatures.
byte[] digestSig = kmsService.sign(key.getKeyId(), digest,
"RSASSA_PKCS1_V1_5_SHA_256", "DIGEST", REGION);
"RSASSA_PKCS1_V1_5_SHA_256", KmsMessageType.DIGEST, REGION);
byte[] rawSig = kmsService.sign(key.getKeyId(), message,
"RSASSA_PKCS1_V1_5_SHA_256", "RAW", REGION);
"RSASSA_PKCS1_V1_5_SHA_256", KmsMessageType.RAW, REGION);
assertArrayEquals(rawSig, digestSig);
}
@@ -1030,8 +1033,8 @@ class KmsServiceTest {
@Test
void enableKeyRotationOnAsymmetricKeyThrows() {
KmsKey key = kmsService.createKey(null, REGION);
key.setCustomerMasterKeySpec("RSA_2048");
key.setKeyUsage("SIGN_VERIFY");
key.setKeySpec(KmsKeySpec.RSA_2048);
key.setKeyUsage(KmsKeyUsage.SIGN_VERIFY);
assertThrows(AwsException.class, () ->
kmsService.enableKeyRotation(key.getKeyId(), REGION));
}
@@ -1039,16 +1042,16 @@ class KmsServiceTest {
@Test
void getKeyRotationStatusOnAsymmetricKeyReturnsFalse() {
KmsKey key = kmsService.createKey(null, REGION);
key.setCustomerMasterKeySpec("ECC_NIST_P256");
key.setKeyUsage("SIGN_VERIFY");
key.setKeySpec(KmsKeySpec.ECC_NIST_P256);
key.setKeyUsage(KmsKeyUsage.SIGN_VERIFY);
assertFalse(kmsService.getKeyRotationStatus(key.getKeyId(), REGION));
}
@Test
void getKeyRotationStatusOnHmacKeyReturnsFalse() {
KmsKey key = kmsService.createKey(null, REGION);
key.setCustomerMasterKeySpec("HMAC_256");
key.setKeyUsage("GENERATE_VERIFY_MAC");
key.setKeySpec(KmsKeySpec.HMAC_256);
key.setKeyUsage(KmsKeyUsage.GENERATE_VERIFY_MAC);
assertFalse(kmsService.getKeyRotationStatus(key.getKeyId(), REGION));
}
@@ -1105,8 +1108,8 @@ class KmsServiceTest {
void createHmacKey_allSpecs(String spec) {
KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", spec, null, Map.of(), REGION);
assertEquals(spec, key.getCustomerMasterKeySpec());
assertEquals("GENERATE_VERIFY_MAC", key.getKeyUsage());
assertEquals(KmsKeySpec.valueOf(spec), key.getKeySpec());
assertEquals("GENERATE_VERIFY_MAC", key.getKeyUsage().name());
assertNotNull(key.getPrivateKeyEncoded());
int expectedBytes = switch (spec) {
@@ -1119,7 +1122,7 @@ class KmsServiceTest {
assertEquals(expectedBytes, Base64.getDecoder().decode(key.getPrivateKeyEncoded()).length);
KmsKey found = kmsService.describeKey(key.getKeyId(), REGION);
assertEquals(spec, found.getCustomerMasterKeySpec());
assertEquals(KmsKeySpec.valueOf(spec), found.getKeySpec());
}
@ParameterizedTest
@@ -1128,7 +1131,7 @@ class KmsServiceTest {
KmsKey key = kmsService.createKey("hmac key", "GENERATE_VERIFY_MAC", spec, null, Map.of(), REGION);
byte[] message = "floci-mac-probe".getBytes(StandardCharsets.UTF_8);
byte[] mac = kmsService.generateMac(key.getKeyId(), message, KmsService.macAlgorithmFor(spec), REGION);
byte[] mac = kmsService.generateMac(key.getKeyId(), message, KmsKeySpec.valueOf(spec).getAlgorithm().getFirst().getAlgName(), REGION);
assertEquals(expectedMacByteLength(spec), mac.length);
}
@@ -1245,4 +1248,56 @@ class KmsServiceTest {
default -> -1;
};
}
@ParameterizedTest
@ValueSource(strings = {"RSA_2048", "RSA_3072", "RSA_4096"})
void signAndVerifyWithAllRsaSpecs(String keySpec) {
KmsKey key = kmsService.createKey("rsa key", "SIGN_VERIFY", keySpec, null, Map.of(), REGION);
byte[] message = "sign me with rsa".getBytes(StandardCharsets.UTF_8);
String algo = "RSASSA_PKCS1_V1_5_SHA_256";
byte[] sig = kmsService.sign(key.getKeyId(), message, algo, REGION);
assertNotNull(sig);
assertTrue(kmsService.verify(key.getKeyId(), message, sig, algo, REGION));
}
@ParameterizedTest
@ValueSource(strings = {
"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1",
"RSA_2048", "RSA_3072", "RSA_4096"
})
void signAndVerifyWithDigestAllSpecs(String keySpec) throws Exception {
KmsKey key = kmsService.createKey("digest key", "SIGN_VERIFY", keySpec, null, Map.of(), REGION);
byte[] message = "floci kms digest test".getBytes(StandardCharsets.UTF_8);
KmsKeySpec.Algorithm algorithm = KmsKeySpec.valueOf(keySpec).getAlgorithm().getFirst();
String digestAlgo = algorithm.getJavaName().substring(0, 6);
byte[] digest = MessageDigest.getInstance(digestAlgo).digest(message);
byte[] sig = kmsService.sign(key.getKeyId(), digest, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION);
assertNotNull(sig);
assertTrue(kmsService.verify(key.getKeyId(), digest, sig, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION));
}
@Test
void signFailsForSymmetricKey() {
KmsKey key = kmsService.createKey("symmetric", "ENCRYPT_DECRYPT", "SYMMETRIC_DEFAULT", null, Map.of(), REGION);
byte[] message = "hello".getBytes(StandardCharsets.UTF_8);
String keyId = key.getKeyId();
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.sign(keyId, message, "RSASSA_PKCS1_V1_5_SHA_256", REGION));
assertEquals("UnsupportedOperationException", ex.getErrorCode());
}
@Test
void generateMacFailsForAsymmetricKey() {
KmsKey key = kmsService.createKey("asymmetric", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
byte[] message = "hello".getBytes(StandardCharsets.UTF_8);
String keyId = key.getKeyId();
AwsException ex = assertThrows(AwsException.class, () ->
kmsService.generateMac(keyId, message, "HMAC_SHA_256", REGION));
assertEquals("InvalidKeyUsageException", ex.getErrorCode());
}
}