mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(kms): match the AWS error codes, messages and check order (#3968)
* fix(kms): reject Sign and Verify on keys that are not SIGN_VERIFY * fix(kms): validate SigningAlgorithm and key spec * refactor(kms): keep only comments the code cannot show * fix(kms): check the DIGEST length for every signing algorithm * fix(kms): refuse disabled and pending deletion keys * fix(kms): answer a failed Verify with KMSInvalidSignatureException * fix(kms): fix MAC key usage and invalid MAC errors * fix(kms): validate MacAlgorithm * fix(kms): use the key spec error for an unsupported MAC algorithm * fix(kms): only treat a malformed signature as invalid in Verify * fix(kms): answer a key pending import with its ARN and state * fix(kms): name the key ARN when it is pending deletion * fix(kms): refuse a key pending deletion in key management operations * fix(kms): check the key state in GetPublicKey * test(kms): drop the real AWS notes from test comments * fix(kms): send no message when GetPublicKey gets a symmetric key * fix(kms): check the key state before changing key rotation * fix(kms): send no message when the key spec does not rotate * fix(kms): accept DisableKeyRotation on a key spec that does not rotate * fix(kms): name the key ARN and origin when the origin is not valid * fix(kms): ask for new key material when rotating an EXTERNAL key on demand * fix(kms): validate RotationPeriodInDays * fix(kms): use the AWS wording for IncorrectKeyException * fix(kms): send no message with InvalidCiphertextException * fix(kms): list EncryptionAlgorithm values in the AWS order * fix(kms): validate the data key KeySpec and NumberOfBytes * fix(kms): require either KeySpec or NumberOfBytes for a data key * fix(kms): make an AES_128 data key 16 bytes long * fix(kms): use the AWS error for a data key under an asymmetric key * fix(kms): name GenerateDataKeyWithoutPlaintext in its key usage error * fix(kms): report the GenerateRandom bound that NumberOfBytes breaks * fix(kms): say NumberOfBytes is required in GenerateRandom * fix(kms): list the MessageType values in its validation error * fix(kms): answer NotFoundException with status 400 * fix(kms): use the AWS wording when a key does not exist * fix(kms): use the AWS wording when an alias does not exist * fix(kms): reject a key or alias ARN from another region * fix(kms): validate a missing, empty or non-ASCII KeyId * fix(kms): validate blob members before looking up the key * fix(kms): reject an alias in operations that need a key * test(compat): stop scheduling a KMS key for deletion twice
This commit is contained in:
1 parent
ee74fd0a49
commit
68425d942a
17 files changed
+1549
-383
No files matched your search
+16
-24
@@ -407,17 +407,13 @@ class KmsFeaturesTest {
|
||||
void encryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {
|
||||
String keyId = kms.createKey(b -> b.description("pending-encrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
assertThatThrownBy(
|
||||
() -> kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -425,22 +421,18 @@ class KmsFeaturesTest {
|
||||
void decryptWithPendingDeletionKeyRaisesKmsInvalidStateException() {
|
||||
String keyId = kms.createKey(b -> b.description("pending-decrypt")).keyMetadata().keyId();
|
||||
|
||||
try {
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
SdkBytes ciphertext = kms.encrypt(b -> b
|
||||
.keyId(keyId)
|
||||
.plaintext(SdkBytes.fromString("secret data", StandardCharsets.UTF_8)))
|
||||
.ciphertextBlob();
|
||||
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyId))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
} finally {
|
||||
kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));
|
||||
}
|
||||
assertThatThrownBy(
|
||||
() -> kms.decrypt(b -> b
|
||||
.ciphertextBlob(ciphertext)
|
||||
.keyId(keyId))
|
||||
).isInstanceOf(KmsInvalidStateException.class);
|
||||
}
|
||||
|
||||
// ── Issue #3024: Encrypt/Decrypt apply real RSAES-OAEP for RSA keys ──────
|
||||
|
||||
@@ -36,7 +36,33 @@ public class KmsJsonHandler {
|
||||
this.regionResolver = regionResolver;
|
||||
}
|
||||
|
||||
private static final Set<String> KEY_ID_OPERATIONS = Set.of(
|
||||
"GetPublicKey", "DescribeKey", "CreateGrant", "ListGrants", "RevokeGrant", "Encrypt", "GenerateDataKey",
|
||||
"GenerateDataKeyWithoutPlaintext", "Sign", "Verify", "GenerateMac", "VerifyMac", "ScheduleKeyDeletion",
|
||||
"CancelKeyDeletion", "TagResource", "UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy",
|
||||
"ListKeyPolicies", "UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation",
|
||||
"DisableKeyRotation", "EnableKey", "DisableKey", "RotateKeyOnDemand", "GetParametersForImport",
|
||||
"ImportKeyMaterial", "DeleteImportedKeyMaterial");
|
||||
|
||||
private static final Set<String> KEY_ONLY_OPERATIONS = Set.of(
|
||||
"CreateGrant", "ListGrants", "RevokeGrant", "ScheduleKeyDeletion", "CancelKeyDeletion", "TagResource",
|
||||
"UntagResource", "ListResourceTags", "GetKeyPolicy", "PutKeyPolicy", "ListKeyPolicies",
|
||||
"UpdateKeyDescription", "GetKeyRotationStatus", "EnableKeyRotation", "DisableKeyRotation", "EnableKey",
|
||||
"DisableKey", "RotateKeyOnDemand", "GetParametersForImport", "ImportKeyMaterial",
|
||||
"DeleteImportedKeyMaterial");
|
||||
|
||||
public Response handle(String action, JsonNode request, String region) {
|
||||
if (KEY_ID_OPERATIONS.contains(action)) {
|
||||
validateKeyIdMember(request, "KeyId");
|
||||
String keyId = request.path("KeyId").asText();
|
||||
if (KEY_ONLY_OPERATIONS.contains(action) && (keyId.startsWith("alias/") || keyId.contains(":alias/"))) {
|
||||
throw new AwsException("InvalidArnException", "Key Aliases are not supported for this operation.", 400);
|
||||
}
|
||||
} else if ("ReEncrypt".equals(action)) {
|
||||
validateKeyIdMember(request, "DestinationKeyId");
|
||||
} else if ("CreateAlias".equals(action) || "UpdateAlias".equals(action)) {
|
||||
validateKeyIdMember(request, "TargetKeyId");
|
||||
}
|
||||
return switch (action) {
|
||||
case "CreateKey" -> handleCreateKey(request, region);
|
||||
case "GenerateRandom" -> handleGenerateRandom(request, region);
|
||||
@@ -251,7 +277,7 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleEncrypt(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] plaintext = decodeBlob(request, "Plaintext");
|
||||
byte[] plaintext = requireSizedBlob(request, "Plaintext", true, KmsService.MAX_PLAINTEXT_BYTES);
|
||||
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
|
||||
String algorithm = request.path("EncryptionAlgorithm").asText(null);
|
||||
|
||||
@@ -265,7 +291,7 @@ public class KmsJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleDecrypt(JsonNode request, String region) {
|
||||
byte[] ciphertext = decodeBlob(request, "CiphertextBlob");
|
||||
byte[] ciphertext = requireSizedBlob(request, "CiphertextBlob", false, KmsService.MAX_CIPHERTEXT_BYTES);
|
||||
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
|
||||
String requestKeyId = request.path("KeyId").asText(null);
|
||||
String algorithm = request.path("EncryptionAlgorithm").asText(null);
|
||||
@@ -283,8 +309,8 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleGenerateDataKey(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
String spec = request.path("KeySpec").asText(null);
|
||||
int numberOfBytes = request.path("NumberOfBytes").asInt(0);
|
||||
String spec = readDataKeySpec(request);
|
||||
Integer numberOfBytes = readNumberOfBytes(request);
|
||||
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
|
||||
|
||||
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);
|
||||
@@ -298,11 +324,11 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleGenerateDataKeyWithoutPlaintext(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
String spec = request.path("KeySpec").asText(null);
|
||||
int numberOfBytes = request.path("NumberOfBytes").asInt(0);
|
||||
String spec = readDataKeySpec(request);
|
||||
Integer numberOfBytes = readNumberOfBytes(request);
|
||||
Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));
|
||||
|
||||
Map<String, Object> result = service.generateDataKey(keyId, spec, numberOfBytes, context, region);
|
||||
Map<String, Object> result = service.generateDataKeyWithoutPlaintext(keyId, spec, numberOfBytes, context, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("CiphertextBlob", Base64.getEncoder().encodeToString((byte[]) result.get("CiphertextBlob")));
|
||||
@@ -311,7 +337,7 @@ public class KmsJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleReEncrypt(JsonNode request, String region) {
|
||||
byte[] ciphertext = decodeBlob(request, "CiphertextBlob");
|
||||
byte[] ciphertext = requireSizedBlob(request, "CiphertextBlob", false, KmsService.MAX_CIPHERTEXT_BYTES);
|
||||
String destKeyId = request.path("DestinationKeyId").asText();
|
||||
Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));
|
||||
Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));
|
||||
@@ -344,8 +370,8 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleSign(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] message = decodeBlob(request, "Message");
|
||||
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
|
||||
byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);
|
||||
String algorithm = request.path("SigningAlgorithm").asText(null);
|
||||
KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));
|
||||
|
||||
byte[] signature = service.sign(keyId, message, algorithm, messageType, region);
|
||||
@@ -359,24 +385,24 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleVerify(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] message = decodeBlob(request, "Message");
|
||||
byte[] signature = decodeBlob(request, "Signature");
|
||||
String algorithm = request.path("SigningAlgorithm").asText("RSASSA_PSS_SHA_256");
|
||||
byte[] signature = requireSizedBlob(request, "Signature", false, KmsService.MAX_CIPHERTEXT_BYTES);
|
||||
byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);
|
||||
String algorithm = request.path("SigningAlgorithm").asText(null);
|
||||
KmsMessageType messageType = KmsMessageType.fromString(request.path("MessageType").asText("RAW"));
|
||||
|
||||
boolean valid = service.verify(keyId, message, signature, algorithm, messageType, region);
|
||||
service.verify(keyId, message, signature, algorithm, messageType, region);
|
||||
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("KeyId", service.describeKey(keyId, region).getArn());
|
||||
response.put("SignatureValid", valid);
|
||||
response.put("SignatureValid", true);
|
||||
response.put("SigningAlgorithm", algorithm);
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private Response handleGenerateMac(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] message = decodeBlob(request, "Message");
|
||||
String algorithm = request.path("MacAlgorithm").asText();
|
||||
byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);
|
||||
String algorithm = request.path("MacAlgorithm").asText(null);
|
||||
|
||||
KmsService.GenerateMacResult result = service.generateMacAndResolveKey(keyId, message, algorithm, region);
|
||||
|
||||
@@ -389,9 +415,9 @@ public class KmsJsonHandler {
|
||||
|
||||
private Response handleVerifyMac(JsonNode request, String region) {
|
||||
String keyId = request.path("KeyId").asText();
|
||||
byte[] message = decodeBlob(request, "Message");
|
||||
byte[] mac = decodeBlob(request, "Mac");
|
||||
String algorithm = request.path("MacAlgorithm").asText();
|
||||
byte[] mac = requireSizedBlob(request, "Mac", false, KmsService.MAX_CIPHERTEXT_BYTES);
|
||||
byte[] message = requireSizedBlob(request, "Message", true, KmsService.MAX_PLAINTEXT_BYTES);
|
||||
String algorithm = request.path("MacAlgorithm").asText(null);
|
||||
|
||||
KmsService.VerifyMacResult result = service.verifyMacAndResolveKey(keyId, message, mac, algorithm, region);
|
||||
|
||||
@@ -530,6 +556,10 @@ public class KmsJsonHandler {
|
||||
}
|
||||
|
||||
private Response handleEnableKeyRotation(JsonNode request, String region) {
|
||||
JsonNode rotationPeriod = request.path("RotationPeriodInDays");
|
||||
if (rotationPeriod.isNumber()) {
|
||||
validateRange("rotationPeriodInDays", rotationPeriod.asInt(), 90, 2560);
|
||||
}
|
||||
service.enableKeyRotation(request.path("KeyId").asText(), region);
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
@@ -567,7 +597,10 @@ public class KmsJsonHandler {
|
||||
"Custom key stores are not supported.",
|
||||
400);
|
||||
}
|
||||
int numberOfBytes = request.path("NumberOfBytes").asInt(0);
|
||||
if (!request.path("NumberOfBytes").isNumber()) {
|
||||
throw new AwsException("ValidationException", "NumberOfBytes is required.", 400);
|
||||
}
|
||||
int numberOfBytes = request.path("NumberOfBytes").asInt();
|
||||
byte[] randomBytes = service.generateRandom(numberOfBytes);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("Plaintext", Base64.getEncoder().encodeToString(randomBytes));
|
||||
@@ -616,6 +649,71 @@ public class KmsJsonHandler {
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
// The model check lists every KMS key spec, yet only the data key specs pass.
|
||||
private static String readDataKeySpec(JsonNode request) {
|
||||
String spec = request.path("KeySpec").asText(null);
|
||||
if (spec != null && !"AES_256".equals(spec) && !"AES_128".equals(spec)) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + spec
|
||||
+ "' at 'keySpec' failed to satisfy constraint: Member must satisfy enum value set: [RSA_2048, "
|
||||
+ "RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521, ECC_SECG_P256K1, "
|
||||
+ "ECC_NIST_EDWARDS25519, SYMMETRIC_DEFAULT, HMAC_224, HMAC_256, HMAC_384, HMAC_512, SM2, "
|
||||
+ "ML_DSA_44, ML_DSA_65, ML_DSA_87]", 400);
|
||||
}
|
||||
return spec;
|
||||
}
|
||||
|
||||
private static Integer readNumberOfBytes(JsonNode request) {
|
||||
JsonNode numberOfBytes = request.path("NumberOfBytes");
|
||||
if (!numberOfBytes.isNumber()) {
|
||||
return null;
|
||||
}
|
||||
validateRange("numberOfBytes", numberOfBytes.asInt(), 1, 1024);
|
||||
return numberOfBytes.asInt();
|
||||
}
|
||||
|
||||
private static void validateRange(String member, int value, int min, int max) {
|
||||
if (value < min) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + value + "' at '"
|
||||
+ member + "' failed to satisfy constraint: Member must have value greater than or equal to " + min, 400);
|
||||
}
|
||||
if (max < value) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + value + "' at '"
|
||||
+ member + "' failed to satisfy constraint: Member must have value less than or equal to " + max, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateKeyIdMember(JsonNode request, String member) {
|
||||
String name = Character.toLowerCase(member.charAt(0)) + member.substring(1);
|
||||
JsonNode value = request.path(member);
|
||||
if (value.isMissingNode() || value.isNull()) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value null at '" + name
|
||||
+ "' failed to satisfy constraint: Member must not be null", 400);
|
||||
}
|
||||
String keyId = value.asText();
|
||||
String pattern = "Value '" + keyId + "' at '" + name
|
||||
+ "' failed to satisfy constraint: Member must satisfy regular expression pattern: ^\\p{ASCII}+$";
|
||||
if (keyId.isEmpty()) {
|
||||
throw new AwsException("ValidationException", "2 validation errors detected: Value '' at '" + name
|
||||
+ "' failed to satisfy constraint: Member must have length greater than or equal to 1; " + pattern, 400);
|
||||
}
|
||||
if (!keyId.chars().allMatch(c -> c < 128)) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: " + pattern, 400);
|
||||
}
|
||||
}
|
||||
|
||||
// KMS hides the value of a sensitive member, even when it is null.
|
||||
private static byte[] requireSizedBlob(JsonNode request, String member, boolean sensitive, int max) {
|
||||
String name = Character.toLowerCase(member.charAt(0)) + member.substring(1);
|
||||
JsonNode value = request.path(member);
|
||||
if (value.isMissingNode() || value.isNull()) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value " + (sensitive ? "" : "null ")
|
||||
+ "at '" + name + "' failed to satisfy constraint: Member must not be null", 400);
|
||||
}
|
||||
byte[] blob = decodeBlob(request, member);
|
||||
KmsService.validateBlobLength(name, blob, max);
|
||||
return blob;
|
||||
}
|
||||
|
||||
private static String requireKeyId(JsonNode request) {
|
||||
String keyId = request.path("KeyId").asText(null);
|
||||
if (keyId == null || keyId.isBlank()) {
|
||||
|
||||
@@ -112,7 +112,7 @@ final class KmsKeyImport {
|
||||
return cipher.doFinal(encryptedKeyMaterial);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv(e, "Unwrapping imported key material failed for wrapping algorithm {0}", wrappingAlgorithm);
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
|
||||
|
||||
@@ -92,10 +93,13 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public byte[] generateRandom(int numberOfBytes) {
|
||||
if (numberOfBytes < 1 || numberOfBytes > 1024) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + numberOfBytes + "' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1 and less than or equal to 1024",
|
||||
400);
|
||||
if (numberOfBytes < 1) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + numberOfBytes
|
||||
+ "' at 'numberOfBytes' failed to satisfy constraint: Member must have value greater than or equal to 1", 400);
|
||||
}
|
||||
if (1024 < numberOfBytes) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + numberOfBytes
|
||||
+ "' at 'numberOfBytes' failed to satisfy constraint: Member must have value less than or equal to 1024", 400);
|
||||
}
|
||||
byte[] bytes = new byte[numberOfBytes];
|
||||
secureRandom.nextBytes(bytes);
|
||||
@@ -250,9 +254,11 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public KmsKey getPublicKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
requireImportedKeyMaterial(key);
|
||||
KmsKeySpec spec = key.getKeySpec();
|
||||
if (KmsKeySpec.SYMMETRIC_DEFAULT == spec || isHmac(spec)) {
|
||||
throw new AwsException("UnsupportedOperationException", "GetPublicKey is not supported for symmetric keys.", 400);
|
||||
throw new AwsException("UnsupportedOperationException", null, 400);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
@@ -395,6 +401,7 @@ public class KmsService implements ResourceProvider {
|
||||
validateGrantConstraints(constraints);
|
||||
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
String grantId = UUID.randomUUID().toString();
|
||||
byte[] tokenBytes = new byte[32];
|
||||
ThreadLocalRandom.current().nextBytes(tokenBytes);
|
||||
@@ -587,6 +594,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void scheduleKeyDeletion(String keyId, int pendingWindowInDays, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
key.setKeyState("PendingDeletion");
|
||||
key.setDeletionDate(Instant.now().plusSeconds((long) pendingWindowInDays * 86400).getEpochSecond());
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -651,6 +659,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void updateKeyDescription(String keyId, String description, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
key.setDescription(description);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
LOG.infov("Updated description for KMS key: {0} in {1}", key.getKeyId(), region);
|
||||
@@ -669,7 +678,9 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void enableKeyRotation(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
validateRotationSupported(key);
|
||||
validateRotationOrigin(key);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
validateRotationKeySpec(key);
|
||||
key.setKeyRotationEnabled(true);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
LOG.infov("Enabled key rotation for KMS key: {0} in {1}", key.getKeyId(), region);
|
||||
@@ -677,7 +688,8 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void disableKeyRotation(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
validateRotationSupported(key);
|
||||
validateRotationOrigin(key);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
key.setKeyRotationEnabled(false);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
LOG.infov("Disabled key rotation for KMS key: {0} in {1}", key.getKeyId(), region);
|
||||
@@ -685,11 +697,8 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void enableKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
if (PENDING_DELETION.equals(key.getKeyState())) {
|
||||
throw new AwsException("KMSInvalidStateException",
|
||||
"KMS key " + key.getKeyId() + " is pending deletion.", 400);
|
||||
}
|
||||
requireImportedKeyMaterial(key, "EnableKey");
|
||||
requireNotPendingDeletion(key);
|
||||
requireImportedKeyMaterial(key);
|
||||
key.setEnabled(true);
|
||||
key.setKeyState("Enabled");
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -698,7 +707,8 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void disableKey(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireImportedKeyMaterial(key, "DisableKey");
|
||||
requireNotPendingDeletion(key);
|
||||
requireImportedKeyMaterial(key);
|
||||
key.setEnabled(false);
|
||||
key.setKeyState("Disabled");
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -709,11 +719,12 @@ public class KmsService implements ResourceProvider {
|
||||
public String rotateKeyOnDemand(String keyId, String region) {
|
||||
synchronized (backingKeyMaterialLock) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException("DisabledException",
|
||||
"KMS key " + key.getKeyId() + " is disabled.", 400);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
validateRotationKeySpec(key);
|
||||
if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {
|
||||
throw new AwsException("KMSInvalidStateException",
|
||||
"No available key material pending rotation for the key: " + key.getArn() + ".", 400);
|
||||
}
|
||||
validateRotationSupported(key);
|
||||
if (key.getOnDemandRotationCount() >= ON_DEMAND_ROTATION_LIMIT) {
|
||||
throw new AwsException("LimitExceededException",
|
||||
"On-demand rotation quota for KMS key " + key.getKeyId() + " is exceeded.", 400);
|
||||
@@ -727,19 +738,16 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRotationSupported(KmsKey key) {
|
||||
private static void validateRotationOrigin(KmsKey key) {
|
||||
if (EXTERNAL_ORIGIN.equals(key.getOrigin())) {
|
||||
throw new AwsException(
|
||||
"UnsupportedOperationException",
|
||||
"You cannot enable automatic rotation of imported key material.",
|
||||
400);
|
||||
throw invalidOrigin(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateRotationKeySpec(KmsKey key) {
|
||||
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.",
|
||||
400);
|
||||
throw new AwsException("UnsupportedOperationException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,7 +759,7 @@ public class KmsService implements ResourceProvider {
|
||||
public ImportParameters getParametersForImport(String keyId, String wrappingAlgorithm,
|
||||
String wrappingKeySpec, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireExternalOrigin(key, "GetParametersForImport");
|
||||
requireExternalOrigin(key);
|
||||
requireNotPendingDeletion(key);
|
||||
KmsKeyImport.validateWrappingAlgorithm(wrappingAlgorithm);
|
||||
|
||||
@@ -777,7 +785,7 @@ public class KmsService implements ResourceProvider {
|
||||
public KmsKey importKeyMaterial(String keyId, String importToken, byte[] encryptedKeyMaterial,
|
||||
String expirationModel, Long validTo, String importType, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireExternalOrigin(key, "ImportKeyMaterial");
|
||||
requireExternalOrigin(key);
|
||||
requireNotPendingDeletion(key);
|
||||
validateImportType(importType, key);
|
||||
|
||||
@@ -831,7 +839,7 @@ public class KmsService implements ResourceProvider {
|
||||
*/
|
||||
public KmsKey deleteImportedKeyMaterial(String keyId, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireExternalOrigin(key, "DeleteImportedKeyMaterial");
|
||||
requireExternalOrigin(key);
|
||||
clearImportedKeyMaterial(key);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
LOG.infov("Deleted imported key material for KMS key {0} in {1}", key.getKeyId(), region);
|
||||
@@ -1029,26 +1037,26 @@ public class KmsService implements ResourceProvider {
|
||||
return EXTERNAL_ORIGIN;
|
||||
}
|
||||
|
||||
private static void requireExternalOrigin(KmsKey key, String operation) {
|
||||
private static void requireExternalOrigin(KmsKey key) {
|
||||
if (!EXTERNAL_ORIGIN.equals(key.getOrigin())) {
|
||||
throw new AwsException("UnsupportedOperationException",
|
||||
operation + " is only supported for KMS keys with Origin EXTERNAL; key "
|
||||
+ key.getKeyId() + " has origin " + key.getOrigin() + ".", 400);
|
||||
throw invalidOrigin(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException invalidOrigin(KmsKey key) {
|
||||
return new AwsException("UnsupportedOperationException",
|
||||
key.getArn() + " origin is " + key.getOrigin() + " which is not valid for this operation.", 400);
|
||||
}
|
||||
|
||||
private static void requireNotPendingDeletion(KmsKey key) {
|
||||
if (PENDING_DELETION.equals(key.getKeyState())) {
|
||||
throw new AwsException("KMSInvalidStateException",
|
||||
"KMS key " + key.getKeyId() + " is pending deletion.", 400);
|
||||
throw new AwsException("KMSInvalidStateException", key.getArn() + " is pending deletion.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireImportedKeyMaterial(KmsKey key, String operation) {
|
||||
private static void requireImportedKeyMaterial(KmsKey key) {
|
||||
if (PENDING_IMPORT.equals(key.getKeyState())) {
|
||||
throw new AwsException("KMSInvalidStateException",
|
||||
operation + " is not valid for KMS key " + key.getKeyId()
|
||||
+ " because it has no key material. Its state is PendingImport.", 400);
|
||||
throw new AwsException("KMSInvalidStateException", key.getArn() + " is pending import.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1059,6 +1067,7 @@ public class KmsService implements ResourceProvider {
|
||||
throw new AwsException("InvalidAliasNameException", "Alias name must begin with 'alias/'", 400);
|
||||
}
|
||||
KmsKey key = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID
|
||||
requireNotPendingDeletion(key);
|
||||
|
||||
String aliasArn = regionResolver.buildArn("kms", region, aliasName);
|
||||
KmsAlias alias = new KmsAlias(aliasName, aliasArn, key.getKeyId());
|
||||
@@ -1069,15 +1078,12 @@ public class KmsService implements ResourceProvider {
|
||||
public void updateAlias(String aliasName, String targetKeyId, String region) {
|
||||
String storageKey = region + "::" + aliasName;
|
||||
KmsAlias existing = aliasStore.get(storageKey)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + aliasName, 404));
|
||||
.orElseThrow(() -> aliasNotFound(aliasName, region));
|
||||
|
||||
KmsKey currentKey = resolveKey(existing.getTargetKeyId(), region);
|
||||
KmsKey newKey = resolveKey(targetKeyId, region); // Validate key exists and normalize to plain key ID
|
||||
|
||||
if ("PendingDeletion".equals(newKey.getKeyState())) {
|
||||
throw new AwsException("KMSInvalidStateException",
|
||||
"KMS key " + newKey.getKeyId() + " is pending deletion.", 400);
|
||||
}
|
||||
requireNotPendingDeletion(newKey);
|
||||
if (currentKey.getKeyUsage() != newKey.getKeyUsage() || !sameKeyFamily(currentKey.getKeySpec(), newKey.getKeySpec())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"The replacement KMS key must have the same key usage and key type "
|
||||
@@ -1093,7 +1099,7 @@ public class KmsService implements ResourceProvider {
|
||||
public void deleteAlias(String aliasName, String region) {
|
||||
String key = region + "::" + aliasName;
|
||||
if (aliasStore.get(key).isEmpty()) {
|
||||
throw new AwsException("NotFoundException", "Alias not found", 404);
|
||||
throw aliasNotFound(aliasName, region);
|
||||
}
|
||||
aliasStore.delete(key);
|
||||
}
|
||||
@@ -1138,12 +1144,8 @@ public class KmsService implements ResourceProvider {
|
||||
private static final int AES_KEY_BYTES = KmsKeySpec.SYMMETRIC_DEFAULT.materialByteLength();
|
||||
private static final String BLOB_PREFIX_V2 = "kms:v2:";
|
||||
private static final String BLOB_PREFIX_V1 = "kms:";
|
||||
private static final int MIN_MAC_MESSAGE_BYTES = 1;
|
||||
private static final int MAX_MAC_MESSAGE_BYTES = 4096;
|
||||
private static final int MIN_ENCRYPT_PLAINTEXT_BYTES = 1;
|
||||
private static final int MAX_ENCRYPT_PLAINTEXT_BYTES = 4096;
|
||||
private static final int MIN_MAC_BYTES = 1;
|
||||
private static final int MAX_MAC_BYTES = 6144;
|
||||
static final int MAX_PLAINTEXT_BYTES = 4096;
|
||||
static final int MAX_CIPHERTEXT_BYTES = 6144;
|
||||
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
|
||||
|
||||
public byte[] encrypt(String keyId, byte[] plaintext, String region) {
|
||||
@@ -1162,11 +1164,11 @@ public class KmsService implements ResourceProvider {
|
||||
private EncryptResult encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext,
|
||||
String encryptionAlgorithm, String region, String operation) {
|
||||
KmsKeySpec.Algorithm algorithm = resolveEncryptionAlgorithm(encryptionAlgorithm);
|
||||
validatePlaintextLength(plaintext, operation);
|
||||
validateBlobLength("plaintext", plaintext, MAX_PLAINTEXT_BYTES);
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
validateKeyUsage(kmsKey, KmsKeyUsage.ENCRYPT_DECRYPT, operation);
|
||||
validateKeyIsUsableForCryptoOperations(kmsKey);
|
||||
validateKeyUsageForEncryptionOperation(kmsKey, operation);
|
||||
validateEncryptionAlgorithmForSpec(algorithm, kmsKey.getKeySpec());
|
||||
validateAlgorithmForSpec(algorithm, kmsKey.getKeySpec());
|
||||
|
||||
if (algorithm != KmsKeySpec.Algorithm.SYMMETRIC_DEFAULT) {
|
||||
rejectEncryptionContextForAsymmetricKey(encryptionContext);
|
||||
@@ -1190,7 +1192,7 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
ParsedBlob parsed = parseBlob(ciphertext);
|
||||
if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
return decodePayload(parsed);
|
||||
}
|
||||
@@ -1231,9 +1233,9 @@ public class KmsService implements ResourceProvider {
|
||||
throw new AwsException("ValidationException", "KeyId must not be null", 400);
|
||||
}
|
||||
KmsKey requestKey = resolveKey(requestKeyId, region);
|
||||
validateKeyUsage(requestKey, KmsKeyUsage.ENCRYPT_DECRYPT, "Decrypt");
|
||||
validateKeyIsUsableForCryptoOperations(requestKey);
|
||||
validateKeyUsageForEncryptionOperation(requestKey, "Decrypt");
|
||||
validateEncryptionAlgorithmForSpec(algorithm, requestKey.getKeySpec());
|
||||
validateAlgorithmForSpec(algorithm, requestKey.getKeySpec());
|
||||
rejectEncryptionContextForAsymmetricKey(encryptionContext);
|
||||
byte[] plaintext = keyTypes.of(requestKey.getKeySpec()).decrypt(requestKey, algorithm, ciphertext);
|
||||
return new DecryptResult(plaintext, requestKey.getArn(), algorithm.getAlgName());
|
||||
@@ -1244,7 +1246,7 @@ public class KmsService implements ResourceProvider {
|
||||
KmsKey key = resolveEnvelopeKey(envelope.keyId(), region);
|
||||
// A key whose imported material was deleted or expired no longer holds the backing
|
||||
// key this blob names; answer with the key's state, as AWS does, not "invalid ciphertext".
|
||||
requireImportedKeyMaterial(key, "Decrypt");
|
||||
requireImportedKeyMaterial(key);
|
||||
byte[] plaintext = decryptEnvelopeV3(envelope, key, encryptionContext);
|
||||
|
||||
if (requestKeyId != null && !requestKeyId.isBlank()) {
|
||||
@@ -1252,7 +1254,7 @@ public class KmsService implements ResourceProvider {
|
||||
if (!requestKey.getKeyId().equals(key.getKeyId())) {
|
||||
throw new AwsException(
|
||||
"IncorrectKeyException",
|
||||
"The request was rejected because the specified KMS key cannot decrypt the data.",
|
||||
"The key ID in the request does not identify a CMK that can perform this operation.",
|
||||
400
|
||||
);
|
||||
}
|
||||
@@ -1270,7 +1272,7 @@ public class KmsService implements ResourceProvider {
|
||||
// InvalidCiphertextException, not InvalidKeyUsageException (measured in us-east-1).
|
||||
ParsedBlob parsed = parseBlob(ciphertext);
|
||||
if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
byte[] plaintext = decodePayload(parsed);
|
||||
|
||||
@@ -1279,7 +1281,7 @@ public class KmsService implements ResourceProvider {
|
||||
if (!requestKey.getKeyId().equals(parsed.keyId)) {
|
||||
throw new AwsException(
|
||||
"IncorrectKeyException",
|
||||
"The request was rejected because the specified KMS key cannot decrypt the data.",
|
||||
"The key ID in the request does not identify a CMK that can perform this operation.",
|
||||
400
|
||||
);
|
||||
}
|
||||
@@ -1337,7 +1339,7 @@ public class KmsService implements ResourceProvider {
|
||||
buffer.get(magic);
|
||||
byte version = buffer.get();
|
||||
if (version != ENVELOPE_VERSION_V3) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
byte[] keyIdBytes = new byte[buffer.getShort() & 0xFFFF];
|
||||
buffer.get(keyIdBytes);
|
||||
@@ -1349,7 +1351,7 @@ public class KmsService implements ResourceProvider {
|
||||
byte[] ciphertextAndTag = new byte[buffer.remaining()];
|
||||
buffer.get(ciphertextAndTag);
|
||||
if (ciphertextAndTag.length == 0) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
byte[] aadHeader = Arrays.copyOfRange(blob, 0, headerLength + GCM_IV_BYTES);
|
||||
return new EnvelopeV3(new String(keyIdBytes, StandardCharsets.UTF_8),
|
||||
@@ -1357,7 +1359,7 @@ public class KmsService implements ResourceProvider {
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (RuntimeException e) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1418,7 +1420,7 @@ public class KmsService implements ResourceProvider {
|
||||
try {
|
||||
return resolveKey(keyId, region);
|
||||
} catch (AwsException e) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1434,7 +1436,7 @@ public class KmsService implements ResourceProvider {
|
||||
materialB64 = key.getBackingKeys() == null ? null : key.getBackingKeys().get(envelope.backingKeyId());
|
||||
}
|
||||
if (materialB64 == null) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
byte[] dek = decodeBackingMaterial(materialB64);
|
||||
try {
|
||||
@@ -1442,7 +1444,7 @@ public class KmsService implements ResourceProvider {
|
||||
envelope.aadHeader(), contextFingerprint(encryptionContext).getBytes(StandardCharsets.UTF_8));
|
||||
return cipher.doFinal(envelope.ciphertextAndTag());
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1464,7 +1466,7 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
return material;
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1476,7 +1478,7 @@ public class KmsService implements ResourceProvider {
|
||||
// v2: keyId, nonce, contextFingerprint, payload
|
||||
String[] parts = data.substring(BLOB_PREFIX_V2.length()).split(":", 4);
|
||||
if (parts.length < 4) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
return new ParsedBlob(parts[0], parts[1], parts[2], parts[3]);
|
||||
}
|
||||
@@ -1488,7 +1490,7 @@ public class KmsService implements ResourceProvider {
|
||||
return new ParsedBlob(parts[0], "", "", parts[1]);
|
||||
}
|
||||
}
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
|
||||
/** A blob whose payload is not valid base64 is a bad ciphertext, not a server fault. */
|
||||
@@ -1496,7 +1498,7 @@ public class KmsService implements ResourceProvider {
|
||||
try {
|
||||
return Base64.getDecoder().decode(parsed.payload);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1528,7 +1530,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
/**
|
||||
* Resolves the wire EncryptionAlgorithm value. Real KMS models the enum as
|
||||
* [RSAES_OAEP_SHA_256, RSAES_OAEP_SHA_1, SYMMETRIC_DEFAULT, SM2PKE]. A null or blank
|
||||
* [RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, SM2PKE, SYMMETRIC_DEFAULT]. A null or blank
|
||||
* value falls back to the SYMMETRIC_DEFAULT default.
|
||||
*/
|
||||
private static KmsKeySpec.Algorithm resolveEncryptionAlgorithm(String encryptionAlgorithm) {
|
||||
@@ -1543,30 +1545,34 @@ public class KmsService implements ResourceProvider {
|
||||
default -> throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + name + "' at 'encryptionAlgorithm' failed to satisfy "
|
||||
+ "constraint: Member must satisfy enum value set: "
|
||||
+ "[RSAES_OAEP_SHA_256, RSAES_OAEP_SHA_1, SYMMETRIC_DEFAULT, SM2PKE]", 400);
|
||||
+ "[RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, SM2PKE, SYMMETRIC_DEFAULT]", 400);
|
||||
};
|
||||
}
|
||||
|
||||
private static void validateKeyUsageForEncryptionOperation(KmsKey key, String operation) {
|
||||
if (KmsKeyUsage.ENCRYPT_DECRYPT != key.getKeyUsage()) {
|
||||
private static void validateKeyUsage(KmsKey key, KmsKeyUsage keyUsage, String operation) {
|
||||
if (keyUsage != key.getKeyUsage()) {
|
||||
throw new AwsException("InvalidKeyUsageException",
|
||||
key.getArn() + " key usage is " + key.getKeyUsage() + " which is not valid for "
|
||||
+ operation + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateEncryptionAlgorithmForSpec(KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {
|
||||
private static void validateAlgorithmForSpec(KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {
|
||||
if (!spec.getAlgorithm().contains(algorithm)) {
|
||||
throw new AwsException("InvalidKeyUsageException",
|
||||
"Algorithm " + algorithm.getAlgName() + " is incompatible with key spec " + spec.name() + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validatePlaintextLength(byte[] plaintext, String operation) {
|
||||
int length = plaintext == null ? 0 : plaintext.length;
|
||||
if (length < MIN_ENCRYPT_PLAINTEXT_BYTES || length > MAX_ENCRYPT_PLAINTEXT_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Plaintext must be between 1 and 4096 bytes for " + operation + ".", 400);
|
||||
static void validateBlobLength(String member, byte[] value, int max) {
|
||||
int length = value == null ? 0 : value.length;
|
||||
if (length < 1) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value at '" + member
|
||||
+ "' failed to satisfy constraint: Member must have length greater than or equal to 1", 400);
|
||||
}
|
||||
if (max < length) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value at '" + member
|
||||
+ "' failed to satisfy constraint: Member must have length less than or equal to " + max, 400);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1577,14 +1583,40 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private static final List<String> SIGNING_ALGORITHMS = List.of(
|
||||
"RSASSA_PSS_SHA_256", "RSASSA_PSS_SHA_384", "RSASSA_PSS_SHA_512",
|
||||
"RSASSA_PKCS1_V1_5_SHA_256", "RSASSA_PKCS1_V1_5_SHA_384", "RSASSA_PKCS1_V1_5_SHA_512",
|
||||
"ECDSA_SHA_256", "ECDSA_SHA_384", "ECDSA_SHA_512", "ED25519_SHA_512", "ED25519_PH_SHA_512",
|
||||
"SM2DSA", "ML_DSA_SHAKE_256");
|
||||
|
||||
private static final List<String> MAC_ALGORITHMS =
|
||||
List.of("HMAC_SHA_384", "HMAC_SHA_256", "HMAC_SHA_224", "HMAC_SHA_512");
|
||||
|
||||
private static final Map<KmsKeySpec.Algorithm, Integer> DIGEST_BYTES = Map.of(
|
||||
KmsKeySpec.Algorithm.RSASSA_PSS_SHA_256, 32,
|
||||
KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_256, 32,
|
||||
KmsKeySpec.Algorithm.ECDSA_SHA_256, 32,
|
||||
KmsKeySpec.Algorithm.RSASSA_PSS_SHA_384, 48,
|
||||
KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_384, 48,
|
||||
KmsKeySpec.Algorithm.ECDSA_SHA_384, 48,
|
||||
KmsKeySpec.Algorithm.RSASSA_PSS_SHA_512, 64,
|
||||
KmsKeySpec.Algorithm.RSASSA_PKCS1_V1_5_SHA_512, 64,
|
||||
KmsKeySpec.Algorithm.ECDSA_SHA_512, 64,
|
||||
KmsKeySpec.Algorithm.ED25519_PH_SHA_512, 64);
|
||||
|
||||
public byte[] sign(String keyId, byte[] message, String algorithm, String region) {
|
||||
return sign(keyId, message, algorithm, RAW, region);
|
||||
}
|
||||
|
||||
public byte[] sign(String keyId, byte[] message, String algorithm, KmsMessageType messageType, String region) {
|
||||
KmsKeySpec.Algorithm signingAlgorithm = resolveSigningAlgorithm(algorithm);
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
validateKeyUsage(kmsKey, KmsKeyUsage.SIGN_VERIFY, "Sign");
|
||||
validateKeyIsUsableForCryptoOperations(kmsKey);
|
||||
validateAlgorithmForSpec(signingAlgorithm, kmsKey.getKeySpec());
|
||||
validateDigestLength(signingAlgorithm, messageType, message);
|
||||
try {
|
||||
return keyTypes.of(kmsKey.getKeySpec()).sign(kmsKey, message, algorithm, messageType);
|
||||
return keyTypes.of(kmsKey.getKeySpec()).sign(kmsKey, message, signingAlgorithm, messageType);
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -1592,34 +1624,72 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {
|
||||
return verify(keyId, message, signature, algorithm, RAW, region);
|
||||
private static void validateDigestLength(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType,
|
||||
byte[] message) {
|
||||
Integer expected = DIGEST_BYTES.get(algorithm);
|
||||
if (messageType == KmsMessageType.DIGEST && expected != null && expected != message.length) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Digest is invalid length for algorithm " + algorithm.getAlgName() + ".", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean verify(String keyId, byte[] message, byte[] signature, String algorithm, KmsMessageType messageType, String region) {
|
||||
private static KmsKeySpec.Algorithm resolveSigningAlgorithm(String algorithm) {
|
||||
if (!"SYMMETRIC_DEFAULT".equals(algorithm)) {
|
||||
validateEnumMember("signingAlgorithm", algorithm, SIGNING_ALGORITHMS);
|
||||
}
|
||||
return KmsKeySpec.Algorithm.valueOf(algorithm);
|
||||
}
|
||||
|
||||
private static void validateEnumMember(String member, String value, List<String> allowed) {
|
||||
if (value == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value null at '" + member + "' failed to satisfy "
|
||||
+ "constraint: Member must not be null", 400);
|
||||
}
|
||||
if (!allowed.contains(value)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"1 validation error detected: Value '" + value + "' at '" + member + "' failed to "
|
||||
+ "satisfy constraint: Member must satisfy enum value set: ["
|
||||
+ String.join(", ", allowed) + "]", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public void verify(String keyId, byte[] message, byte[] signature, String algorithm, String region) {
|
||||
verify(keyId, message, signature, algorithm, RAW, region);
|
||||
}
|
||||
|
||||
public void verify(String keyId, byte[] message, byte[] signature, String algorithm, KmsMessageType messageType, String region) {
|
||||
KmsKeySpec.Algorithm signingAlgorithm = resolveSigningAlgorithm(algorithm);
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
validateKeyUsage(kmsKey, KmsKeyUsage.SIGN_VERIFY, "Verify");
|
||||
validateKeyIsUsableForCryptoOperations(kmsKey);
|
||||
validateAlgorithmForSpec(signingAlgorithm, kmsKey.getKeySpec());
|
||||
validateDigestLength(signingAlgorithm, messageType, message);
|
||||
boolean valid;
|
||||
try {
|
||||
return keyTypes.of(kmsKey.getKeySpec()).verify(kmsKey, message, signature, algorithm, messageType);
|
||||
valid = keyTypes.of(kmsKey.getKeySpec()).verify(kmsKey, message, signature, signingAlgorithm, messageType);
|
||||
} catch (AwsException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Verification failed for key {0}: {1}", keyId, e.getMessage());
|
||||
return false;
|
||||
throw new AwsException("InternalFailure", "Failed to verify signature: " + e.getMessage(), 500);
|
||||
}
|
||||
if (!valid) {
|
||||
throw new AwsException("KMSInvalidSignatureException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
public byte[] generateMac(String keyId, byte[] message, String algorithm, String region) {
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "GenerateMac", region);
|
||||
return generateMac(kmsKey, message, algorithm);
|
||||
}
|
||||
|
||||
public GenerateMacResult generateMacAndResolveKey(String keyId, byte[] message, String algorithm, String region) {
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "GenerateMac", region);
|
||||
return new GenerateMacResult(generateMac(kmsKey, message, algorithm), kmsKey.getArn());
|
||||
}
|
||||
|
||||
private byte[] generateMac(KmsKey kmsKey, byte[] message, String algorithm) {
|
||||
validateMacMessageLength(message);
|
||||
validateBlobLength("message", message, MAX_PLAINTEXT_BYTES);
|
||||
|
||||
try {
|
||||
return keyTypes.of(kmsKey.getKeySpec()).generateMac(kmsKey, message, algorithm);
|
||||
@@ -1631,14 +1701,14 @@ public class KmsService implements ResourceProvider {
|
||||
}
|
||||
|
||||
public void verifyMac(String keyId, byte[] message, byte[] mac, String algorithm, String region) {
|
||||
validateMacLength(mac);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);
|
||||
validateBlobLength("mac", mac, MAX_CIPHERTEXT_BYTES);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "VerifyMac", region);
|
||||
verifyMac(kmsKey, message, mac, algorithm);
|
||||
}
|
||||
|
||||
public VerifyMacResult verifyMacAndResolveKey(String keyId, byte[] message, byte[] mac, String algorithm, String region) {
|
||||
validateMacLength(mac);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, region);
|
||||
validateBlobLength("mac", mac, MAX_CIPHERTEXT_BYTES);
|
||||
KmsKey kmsKey = validateMacOperationKey(keyId, algorithm, "VerifyMac", region);
|
||||
verifyMac(kmsKey, message, mac, algorithm);
|
||||
return new VerifyMacResult(kmsKey.getArn());
|
||||
}
|
||||
@@ -1646,56 +1716,55 @@ public class KmsService implements ResourceProvider {
|
||||
private void verifyMac(KmsKey kmsKey, byte[] message, byte[] mac, String algorithm) {
|
||||
byte[] expected = generateMac(kmsKey, message, algorithm);
|
||||
if (!MessageDigest.isEqual(expected, mac)) {
|
||||
throw new AwsException("KMSInvalidMacException", "The MAC is not valid.", 400);
|
||||
throw new AwsException("KMSInvalidMacException", null, 400);
|
||||
}
|
||||
}
|
||||
|
||||
private KmsKey validateMacOperationKey(String keyId, String algorithm, String region) {
|
||||
private KmsKey validateMacOperationKey(String keyId, String algorithm, String operation, String region) {
|
||||
validateEnumMember("macAlgorithm", algorithm, MAC_ALGORITHMS);
|
||||
KmsKey kmsKey = resolveKey(keyId, region);
|
||||
requireImportedKeyMaterial(kmsKey, "MAC operations");
|
||||
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 = kmsKey.getKeySpec().getAlgorithm().getFirst().getAlgName();
|
||||
if (!Objects.equals(expectedAlgorithm, algorithm)) {
|
||||
throw new AwsException("InvalidKeyUsageException",
|
||||
"MacAlgorithm " + algorithm + " is not valid for KeySpec " + spec + ".", 400);
|
||||
}
|
||||
validateKeyUsage(kmsKey, KmsKeyUsage.GENERATE_VERIFY_MAC, operation);
|
||||
validateKeyIsUsableForCryptoOperations(kmsKey);
|
||||
validateAlgorithmForSpec(KmsKeySpec.Algorithm.valueOf(algorithm), kmsKey.getKeySpec());
|
||||
return kmsKey;
|
||||
}
|
||||
|
||||
private static void validateMacMessageLength(byte[] message) {
|
||||
int length = message == null ? 0 : message.length;
|
||||
if (length < MIN_MAC_MESSAGE_BYTES || length > MAX_MAC_MESSAGE_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Message must be between 1 and 4096 bytes for MAC operations.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateMacLength(byte[] mac) {
|
||||
int length = mac == null ? 0 : mac.length;
|
||||
if (length < MIN_MAC_BYTES || length > MAX_MAC_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Mac must be between 1 and 6144 bytes for VerifyMac.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes, String region) {
|
||||
public Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes, String region) {
|
||||
return generateDataKey(keyId, keySpec, numberOfBytes, Map.of(), region);
|
||||
}
|
||||
|
||||
public Map<String, Object> generateDataKey(String keyId, String keySpec, int numberOfBytes,
|
||||
public Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes,
|
||||
Map<String, String> encryptionContext, String region) {
|
||||
resolveKey(keyId, region);
|
||||
int len = (keySpec != null && keySpec.contains("256")) ? 32 : (numberOfBytes > 0 ? numberOfBytes : 32);
|
||||
return generateDataKey(keyId, keySpec, numberOfBytes, encryptionContext, region, "GenerateDataKey");
|
||||
}
|
||||
|
||||
Map<String, Object> generateDataKeyWithoutPlaintext(String keyId, String keySpec, Integer numberOfBytes,
|
||||
Map<String, String> encryptionContext, String region) {
|
||||
Map<String, Object> dataKey = generateDataKey(keyId, keySpec, numberOfBytes, encryptionContext, region,
|
||||
"GenerateDataKeyWithoutPlaintext");
|
||||
dataKey.remove("Plaintext");
|
||||
return dataKey;
|
||||
}
|
||||
|
||||
private Map<String, Object> generateDataKey(String keyId, String keySpec, Integer numberOfBytes,
|
||||
Map<String, String> encryptionContext, String region,
|
||||
String operation) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
if ((keySpec == null) == (numberOfBytes == null)) {
|
||||
throw new AwsException("ValidationException", "Please specify either number of bytes or key spec.", 400);
|
||||
}
|
||||
validateKeyUsage(key, KmsKeyUsage.ENCRYPT_DECRYPT, operation);
|
||||
validateKeyIsUsableForCryptoOperations(key);
|
||||
if (KmsKeySpec.SYMMETRIC_DEFAULT != key.getKeySpec()) {
|
||||
throw new AwsException("InvalidKeyUsageException", "You cannot generate a data key with an asymmetric CMK", 400);
|
||||
}
|
||||
int len = keySpec == null ? numberOfBytes : "AES_128".equals(keySpec) ? 16 : 32;
|
||||
|
||||
byte[] plaintext = new byte[len];
|
||||
ThreadLocalRandom.current().nextBytes(plaintext);
|
||||
|
||||
EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, "GenerateDataKey");
|
||||
EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, operation);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("Plaintext", plaintext);
|
||||
@@ -1708,6 +1777,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void tagResource(String keyId, Map<String, String> tags, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
ReservedTags.rejectReservedTagsOnUpdate(tags);
|
||||
key.getTags().putAll(tags);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
@@ -1715,6 +1785,7 @@ public class KmsService implements ResourceProvider {
|
||||
|
||||
public void untagResource(String keyId, List<String> tagKeys, String region) {
|
||||
KmsKey key = resolveKey(keyId, region);
|
||||
requireNotPendingDeletion(key);
|
||||
tagKeys.forEach(key.getTags()::remove);
|
||||
keyStore.put(region + "::" + key.getKeyId(), key);
|
||||
}
|
||||
@@ -1722,6 +1793,12 @@ public class KmsService implements ResourceProvider {
|
||||
// ──────────────────────────── Helpers ────────────────────────────
|
||||
|
||||
private KmsKey resolveKey(String keyIdOrArn, String region) {
|
||||
if (AwsArnUtils.isArnFor(keyIdOrArn, "kms")) {
|
||||
String arnRegion = AwsArnUtils.parse(keyIdOrArn).region();
|
||||
if (!region.equals(arnRegion)) {
|
||||
throw new AwsException("NotFoundException", "Invalid arn " + arnRegion, 400);
|
||||
}
|
||||
}
|
||||
String id = keyIdOrArn;
|
||||
// Alias arn
|
||||
if (id.contains(":alias/")) {
|
||||
@@ -1729,7 +1806,7 @@ public class KmsService implements ResourceProvider {
|
||||
String aliasKey = region + "::" + aliasName;
|
||||
id = aliasStore.get(aliasKey)
|
||||
.map(KmsAlias::getTargetKeyId)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + keyIdOrArn, 404));
|
||||
.orElseThrow(() -> aliasNotFound(aliasName, region));
|
||||
} else if (AwsArnUtils.isArnFor(id, "kms")) {
|
||||
// Key arn
|
||||
id = id.substring(id.lastIndexOf("/") + 1);
|
||||
@@ -1738,30 +1815,48 @@ public class KmsService implements ResourceProvider {
|
||||
String aliasKey = region + "::" + id;
|
||||
id = aliasStore.get(aliasKey)
|
||||
.map(KmsAlias::getTargetKeyId)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Alias not found: " + keyIdOrArn, 404));
|
||||
.orElseThrow(() -> aliasNotFound(keyIdOrArn, region));
|
||||
}
|
||||
|
||||
// Key id
|
||||
String keyId = id;
|
||||
KmsKey key = keyStore.get(region + "::" + id)
|
||||
.orElseThrow(() -> new AwsException("NotFoundException", "Key not found: " + keyIdOrArn, 404));
|
||||
.orElseThrow(() -> keyNotFound(keyIdOrArn, keyId, region));
|
||||
key = expireImportedKeyMaterialIfDue(key, region);
|
||||
key = ensureBackingKeyMaterial(key, region);
|
||||
return key;
|
||||
}
|
||||
|
||||
private AwsException aliasNotFound(String aliasName, String region) {
|
||||
return new AwsException("NotFoundException",
|
||||
"Alias " + regionResolver.buildArn("kms", region, aliasName) + " is not found.", 400);
|
||||
}
|
||||
|
||||
private static final Pattern KEY_ID_PATTERN = Pattern.compile(
|
||||
"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|mrk-[0-9a-fA-F]{32}");
|
||||
|
||||
private AwsException keyNotFound(String keyIdOrArn, String keyId, String region) {
|
||||
if (!KEY_ID_PATTERN.matcher(keyId).matches()) {
|
||||
String shown = AwsArnUtils.isArnFor(keyIdOrArn, "kms") ? keyId : "'" + keyId + "'";
|
||||
return new AwsException("NotFoundException", "Invalid keyId " + shown, 400);
|
||||
}
|
||||
return new AwsException("NotFoundException",
|
||||
"Key '" + regionResolver.buildArn("kms", region, "key/" + keyId) + "' does not exist", 400);
|
||||
}
|
||||
|
||||
private static void validateKeyIsUsableForCryptoOperations(KmsKey key) {
|
||||
if (PENDING_DELETION.equals(key.getKeyState())) {
|
||||
throw new AwsException(
|
||||
"KMSInvalidStateException",
|
||||
"KMS key " + key.getKeyId() + " is pending deletion.",
|
||||
key.getArn() + " is pending deletion.",
|
||||
400
|
||||
);
|
||||
}
|
||||
requireImportedKeyMaterial(key, "This operation");
|
||||
requireImportedKeyMaterial(key);
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException(
|
||||
"DisabledException",
|
||||
"The request was rejected because the specified KMS key is not enabled.",
|
||||
key.getArn() + " is disabled.",
|
||||
400
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.security.NoSuchAlgorithmException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.SignatureException;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
@@ -24,15 +25,6 @@ final class AsymmetricKeys {
|
||||
private AsymmetricKeys() {
|
||||
}
|
||||
|
||||
static KmsKeySpec.Algorithm requireSpecAlgorithm(KmsKeySpec spec, String algorithm) {
|
||||
KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);
|
||||
if (!spec.getAlgorithm().contains(signingAlgorithm)) {
|
||||
throw new AwsException("InvalidKeyUsageException",
|
||||
"Algorithm " + algorithm + " is incompatible with key spec " + spec.name() + ".", 400);
|
||||
}
|
||||
return signingAlgorithm;
|
||||
}
|
||||
|
||||
static void requireRawMessage(KmsKeySpec spec, KmsMessageType messageType) {
|
||||
if (messageType != KmsMessageType.RAW) {
|
||||
throw new AwsException("ValidationException",
|
||||
@@ -67,7 +59,11 @@ final class AsymmetricKeys {
|
||||
Signature verifier = signatureFor(jcaAlgorithm);
|
||||
verifier.initVerify(publicKey);
|
||||
verifier.update(message);
|
||||
return verifier.verify(signature);
|
||||
try {
|
||||
return verifier.verify(signature);
|
||||
} catch (SignatureException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// KMS RSASSA_PSS uses MGF1 over the same digest, with a salt as long as the digest.
|
||||
|
||||
@@ -20,26 +20,23 @@ final class EccNistKeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws GeneralSecurityException {
|
||||
PrivateKey privateKey = AsymmetricKeys.privateKey(key, "EC");
|
||||
String jcaAlgorithm = switch (messageType) {
|
||||
case DIGEST -> "NONEwithECDSA";
|
||||
case RAW -> KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName();
|
||||
};
|
||||
return AsymmetricKeys.sign(privateKey, jcaAlgorithm, message);
|
||||
return AsymmetricKeys.sign(privateKey, jcaAlgorithm(algorithm, messageType), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws GeneralSecurityException {
|
||||
PublicKey publicKey = AsymmetricKeys.publicKey(key, "EC");
|
||||
// An unknown algorithm name fails even for DIGEST.
|
||||
KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);
|
||||
String jcaAlgorithm = switch (messageType) {
|
||||
return AsymmetricKeys.verify(publicKey, jcaAlgorithm(algorithm, messageType), message, signature);
|
||||
}
|
||||
|
||||
private static String jcaAlgorithm(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType) {
|
||||
return switch (messageType) {
|
||||
case DIGEST -> "NONEwithECDSA";
|
||||
case RAW -> signingAlgorithm.getJavaName();
|
||||
case RAW -> algorithm.getJavaName();
|
||||
};
|
||||
return AsymmetricKeys.verify(publicKey, jcaAlgorithm, message, signature);
|
||||
}
|
||||
}
|
||||
+21
-20
@@ -1,11 +1,9 @@
|
||||
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 io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
|
||||
import org.bouncycastle.asn1.ASN1Integer;
|
||||
import org.bouncycastle.asn1.ASN1Primitive;
|
||||
import org.bouncycastle.asn1.ASN1Sequence;
|
||||
import org.bouncycastle.asn1.DERSequenceGenerator;
|
||||
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
|
||||
@@ -36,13 +34,10 @@ final class EccSecgP256k1KeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws GeneralSecurityException, IOException {
|
||||
ECPrivateKeyParameters privateKey = BcEcKeys.privateKeyParameters(key, CURVE);
|
||||
byte[] hash = switch (messageType) {
|
||||
case DIGEST -> message;
|
||||
case RAW -> hashForEcdsa(message, KmsKeySpec.getSignVerifyAlgorithm(algorithm));
|
||||
};
|
||||
byte[] hash = hash(message, algorithm, messageType);
|
||||
|
||||
ECDSASigner signer = new ECDSASigner();
|
||||
signer.init(true, new ParametersWithRandom(privateKey, random));
|
||||
@@ -57,33 +52,39 @@ final class EccSecgP256k1KeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws GeneralSecurityException, IOException {
|
||||
ECPublicKeyParameters publicKey = BcEcKeys.publicKeyParameters(key, CURVE);
|
||||
// An unknown algorithm name fails even for DIGEST.
|
||||
KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);
|
||||
byte[] hash = switch (messageType) {
|
||||
case DIGEST -> message;
|
||||
case RAW -> hashForEcdsa(message, signingAlgorithm);
|
||||
};
|
||||
byte[] hash = hash(message, algorithm, messageType);
|
||||
|
||||
ASN1Sequence asn1 = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(signature));
|
||||
BigInteger r = ASN1Integer.getInstance(asn1.getObjectAt(0)).getValue();
|
||||
BigInteger s = ASN1Integer.getInstance(asn1.getObjectAt(1)).getValue();
|
||||
BigInteger r;
|
||||
BigInteger s;
|
||||
try {
|
||||
ASN1Sequence asn1 = ASN1Sequence.getInstance(signature);
|
||||
if (asn1.size() != 2) {
|
||||
return false;
|
||||
}
|
||||
r = ASN1Integer.getInstance(asn1.getObjectAt(0)).getValue();
|
||||
s = ASN1Integer.getInstance(asn1.getObjectAt(1)).getValue();
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ECDSASigner verifier = new ECDSASigner();
|
||||
verifier.init(false, publicKey);
|
||||
return verifier.verifySignature(hash, r, s);
|
||||
}
|
||||
|
||||
private static byte[] hashForEcdsa(byte[] message, KmsKeySpec.Algorithm algorithm)
|
||||
private static byte[] hash(byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws GeneralSecurityException {
|
||||
if (messageType == KmsMessageType.DIGEST) {
|
||||
return message;
|
||||
}
|
||||
String digest = switch (algorithm) {
|
||||
case ECDSA_SHA_256 -> "SHA-256";
|
||||
case ECDSA_SHA_384 -> "SHA-384";
|
||||
case ECDSA_SHA_512 -> "SHA-512";
|
||||
default -> throw new AwsException("InvalidSigningAlgorithmException",
|
||||
"Unsupported EC algorithm: " + algorithm.getJavaName(), 400);
|
||||
default -> throw new IllegalStateException("Not an ECDSA algorithm: " + algorithm);
|
||||
};
|
||||
return MessageDigest.getInstance(digest).digest(message);
|
||||
}
|
||||
|
||||
@@ -19,8 +19,6 @@ import java.security.interfaces.EdECPrivateKey;
|
||||
|
||||
final class Ed25519KeyType implements KmsKeyType {
|
||||
|
||||
private static final int SHA_512_DIGEST_BYTES = 64;
|
||||
|
||||
@Override
|
||||
public void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException {
|
||||
AsymmetricKeys.store(key, KeyPairGenerator.getInstance("Ed25519").generateKeyPair());
|
||||
@@ -28,11 +26,11 @@ final class Ed25519KeyType implements KmsKeyType {
|
||||
|
||||
// KMS runs Ed25519ph over the digest the caller sends, so the digest is hashed again.
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws GeneralSecurityException, CryptoException {
|
||||
KmsKeySpec.Algorithm signingAlgorithm = validateRequest(key.getKeySpec(), algorithm, messageType, message);
|
||||
validateMessageType(algorithm, messageType);
|
||||
PrivateKey privateKey = AsymmetricKeys.privateKey(key, "Ed25519");
|
||||
if (signingAlgorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {
|
||||
if (algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {
|
||||
return AsymmetricKeys.sign(privateKey, "Ed25519", message);
|
||||
}
|
||||
Ed25519phSigner signer = new Ed25519phSigner(new byte[0]);
|
||||
@@ -42,11 +40,11 @@ final class Ed25519KeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws GeneralSecurityException {
|
||||
KmsKeySpec.Algorithm signingAlgorithm = validateRequest(key.getKeySpec(), algorithm, messageType, message);
|
||||
validateMessageType(algorithm, messageType);
|
||||
PublicKey publicKey = AsymmetricKeys.publicKey(key, "Ed25519");
|
||||
if (signingAlgorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {
|
||||
if (algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512) {
|
||||
return AsymmetricKeys.verify(publicKey, "Ed25519", message, signature);
|
||||
}
|
||||
Ed25519phSigner verifier = new Ed25519phSigner(new byte[0]);
|
||||
@@ -55,19 +53,13 @@ final class Ed25519KeyType implements KmsKeyType {
|
||||
return verifier.verifySignature(signature);
|
||||
}
|
||||
|
||||
private static KmsKeySpec.Algorithm validateRequest(KmsKeySpec spec, String algorithm,
|
||||
KmsMessageType messageType, byte[] message) {
|
||||
KmsKeySpec.Algorithm algo = AsymmetricKeys.requireSpecAlgorithm(spec, algorithm);
|
||||
KmsMessageType required = algo == KmsKeySpec.Algorithm.ED25519_SHA_512 ? KmsMessageType.RAW : KmsMessageType.DIGEST;
|
||||
private static void validateMessageType(KmsKeySpec.Algorithm algorithm, KmsMessageType messageType) {
|
||||
KmsMessageType required = algorithm == KmsKeySpec.Algorithm.ED25519_SHA_512
|
||||
? KmsMessageType.RAW : KmsMessageType.DIGEST;
|
||||
if (messageType != required) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Message type " + messageType + " is incompatible with algorithm " + algorithm + ".", 400);
|
||||
"Message type " + messageType + " is incompatible with algorithm " + algorithm.getAlgName() + ".", 400);
|
||||
}
|
||||
if (algo == KmsKeySpec.Algorithm.ED25519_PH_SHA_512 && message.length != SHA_512_DIGEST_BYTES) {
|
||||
throw new AwsException("ValidationException",
|
||||
"Digest is invalid length for algorithm " + algorithm + ".", 400);
|
||||
}
|
||||
return algo;
|
||||
}
|
||||
|
||||
private static byte[] seed(PrivateKey privateKey) throws InvalidKeyException {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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 io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
|
||||
@@ -11,14 +10,14 @@ public interface KmsKeyType {
|
||||
|
||||
void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException;
|
||||
|
||||
default byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
default byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws Exception {
|
||||
throw new AwsException("UnsupportedOperationException", "Unsupported key spec for signing.", 400);
|
||||
throw new IllegalStateException(key.getKeySpec() + " does not sign");
|
||||
}
|
||||
|
||||
default boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
default boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws Exception {
|
||||
return false;
|
||||
throw new IllegalStateException(key.getKeySpec() + " does not verify");
|
||||
}
|
||||
|
||||
default byte[] encrypt(KmsKey key, KmsKeySpec.Algorithm algorithm, byte[] plaintext) {
|
||||
|
||||
@@ -11,8 +11,6 @@ import java.security.PublicKey;
|
||||
|
||||
final class MlDsaKeyType implements KmsKeyType {
|
||||
|
||||
private static final String JCA_ALGORITHM = KmsKeySpec.Algorithm.ML_DSA_SHAKE_256.getJavaName();
|
||||
|
||||
@Override
|
||||
public void generateKeyMaterial(KmsKey key, String region) throws GeneralSecurityException {
|
||||
String algorithm = key.getKeySpec().name().replace('_', '-');
|
||||
@@ -20,20 +18,18 @@ final class MlDsaKeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws GeneralSecurityException {
|
||||
AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);
|
||||
AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);
|
||||
PrivateKey privateKey = AsymmetricKeys.privateKey(key, "ML-DSA");
|
||||
return AsymmetricKeys.sign(privateKey, JCA_ALGORITHM, message);
|
||||
return AsymmetricKeys.sign(privateKey, algorithm.getJavaName(), message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws GeneralSecurityException {
|
||||
AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);
|
||||
AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);
|
||||
PublicKey publicKey = AsymmetricKeys.publicKey(key, "ML-DSA");
|
||||
return AsymmetricKeys.verify(publicKey, JCA_ALGORITHM, message, signature);
|
||||
return AsymmetricKeys.verify(publicKey, algorithm.getJavaName(), message, signature);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ import java.security.PublicKey;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
|
||||
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.DIGEST;
|
||||
import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;
|
||||
|
||||
final class RsaKeyType implements KmsKeyType {
|
||||
|
||||
@@ -51,34 +51,29 @@ final class RsaKeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType) throws Exception {
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws Exception {
|
||||
PrivateKey privateKey = AsymmetricKeys.privateKey(key, "RSA");
|
||||
if (messageType == DIGEST) {
|
||||
if (isPss(algorithm)) {
|
||||
return signPssDigest(privateKey, message, algorithm);
|
||||
}
|
||||
// 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).
|
||||
return AsymmetricKeys.sign(privateKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm));
|
||||
if (messageType == RAW) {
|
||||
return AsymmetricKeys.sign(privateKey, algorithm.getJavaName(), message);
|
||||
}
|
||||
return AsymmetricKeys.sign(privateKey, KmsKeySpec.getSignVerifyAlgorithm(algorithm).getJavaName(), message);
|
||||
if (isPss(algorithm)) {
|
||||
return signPssDigest(privateKey, message, algorithm);
|
||||
}
|
||||
return AsymmetricKeys.sign(privateKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws Exception {
|
||||
PublicKey publicKey = AsymmetricKeys.publicKey(key, "RSA");
|
||||
// An unknown algorithm name fails even for DIGEST.
|
||||
KmsKeySpec.Algorithm signingAlgorithm = KmsKeySpec.getSignVerifyAlgorithm(algorithm);
|
||||
if (messageType == DIGEST) {
|
||||
if (isPss(algorithm)) {
|
||||
return verifyPssDigest(publicKey, message, signature, algorithm);
|
||||
}
|
||||
// Mirror sign(): verify against DigestInfo{hashOID, digest} (RFC 8017 9.2).
|
||||
return AsymmetricKeys.verify(publicKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm), signature);
|
||||
if (messageType == RAW) {
|
||||
return AsymmetricKeys.verify(publicKey, algorithm.getJavaName(), message, signature);
|
||||
}
|
||||
return AsymmetricKeys.verify(publicKey, signingAlgorithm.getJavaName(), message, signature);
|
||||
if (isPss(algorithm)) {
|
||||
return verifyPssDigest(publicKey, message, signature, algorithm);
|
||||
}
|
||||
return AsymmetricKeys.verify(publicKey, "NONEwithRSA", wrapInDigestInfo(message, algorithm), signature);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -96,7 +91,6 @@ final class RsaKeyType implements KmsKeyType {
|
||||
return Integer.parseInt(spec.name().substring("RSA_".length()));
|
||||
}
|
||||
|
||||
/** RFC 8017 7.1.1: OAEP holds at most k - 2*hLen - 2 bytes, k being the modulus length. */
|
||||
private static void validatePlaintextLength(byte[] plaintext, KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {
|
||||
int modulusBytes = keySize(spec) / 8;
|
||||
int digestBytes = algorithm == KmsKeySpec.Algorithm.RSAES_OAEP_SHA_1 ? 20 : 32;
|
||||
@@ -124,29 +118,28 @@ final class RsaKeyType implements KmsKeyType {
|
||||
} catch (Exception e) {
|
||||
if (mode == Cipher.DECRYPT_MODE) {
|
||||
LOG.debugv(e, "RSA OAEP decrypt failed for key {0}", key.getKeyId());
|
||||
throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);
|
||||
throw new AwsException("InvalidCiphertextException", null, 400);
|
||||
}
|
||||
LOG.warnv(e, "RSA OAEP encrypt failed for key {0}", key.getKeyId());
|
||||
throw new AwsException("InternalFailure", "Failed to encrypt: " + e.getMessage(), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isPss(String algorithm) {
|
||||
return algorithm.startsWith("RSASSA_PSS");
|
||||
private static boolean isPss(KmsKeySpec.Algorithm algorithm) {
|
||||
return switch (algorithm) {
|
||||
case RSASSA_PSS_SHA_256, RSASSA_PSS_SHA_384, RSASSA_PSS_SHA_512 -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
// NONEwithRSA pads only the bytes it gets, so PKCS#1 v1.5 needs the DigestInfo wrapper (RFC 8017 9.2).
|
||||
private static byte[] wrapInDigestInfo(byte[] digest, String algorithm) {
|
||||
ASN1ObjectIdentifier hashOid;
|
||||
if (algorithm.endsWith("SHA_256")) {
|
||||
hashOid = NISTObjectIdentifiers.id_sha256;
|
||||
} else if (algorithm.endsWith("SHA_384")) {
|
||||
hashOid = NISTObjectIdentifiers.id_sha384;
|
||||
} else if (algorithm.endsWith("SHA_512")) {
|
||||
hashOid = NISTObjectIdentifiers.id_sha512;
|
||||
} else {
|
||||
throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + algorithm, 400);
|
||||
}
|
||||
private static byte[] wrapInDigestInfo(byte[] digest, KmsKeySpec.Algorithm algorithm) {
|
||||
ASN1ObjectIdentifier hashOid = switch (algorithm) {
|
||||
case RSASSA_PKCS1_V1_5_SHA_256 -> NISTObjectIdentifiers.id_sha256;
|
||||
case RSASSA_PKCS1_V1_5_SHA_384 -> NISTObjectIdentifiers.id_sha384;
|
||||
case RSASSA_PKCS1_V1_5_SHA_512 -> NISTObjectIdentifiers.id_sha512;
|
||||
default -> throw new IllegalStateException("Not a PKCS#1 v1.5 algorithm: " + algorithm);
|
||||
};
|
||||
try {
|
||||
return new DigestInfo(new AlgorithmIdentifier(hashOid, DERNull.INSTANCE), digest).getEncoded();
|
||||
} catch (IOException e) {
|
||||
@@ -155,27 +148,28 @@ final class RsaKeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
// The JDK RSASSA-PSS Signature always hashes its input, so a DIGEST request needs BC's raw PSS signer.
|
||||
private byte[] signPssDigest(PrivateKey privateKey, byte[] digest, String algorithm) throws Exception {
|
||||
private byte[] signPssDigest(PrivateKey privateKey, byte[] digest, KmsKeySpec.Algorithm algorithm)
|
||||
throws Exception {
|
||||
PSSSigner signer = rawPssSigner(algorithm);
|
||||
signer.init(true, new ParametersWithRandom(PrivateKeyFactory.createKey(privateKey.getEncoded()), random));
|
||||
signer.update(digest, 0, digest.length);
|
||||
return signer.generateSignature();
|
||||
}
|
||||
|
||||
private static boolean verifyPssDigest(PublicKey publicKey, byte[] digest, byte[] signature, String algorithm)
|
||||
throws IOException {
|
||||
private static boolean verifyPssDigest(PublicKey publicKey, byte[] digest, byte[] signature,
|
||||
KmsKeySpec.Algorithm algorithm) throws IOException {
|
||||
PSSSigner signer = rawPssSigner(algorithm);
|
||||
signer.init(false, PublicKeyFactory.createKey(publicKey.getEncoded()));
|
||||
signer.update(digest, 0, digest.length);
|
||||
return signer.verifySignature(signature);
|
||||
}
|
||||
|
||||
private static PSSSigner rawPssSigner(String algorithm) {
|
||||
private static PSSSigner rawPssSigner(KmsKeySpec.Algorithm algorithm) {
|
||||
Digest digest = switch (algorithm) {
|
||||
case "RSASSA_PSS_SHA_256" -> new SHA256Digest();
|
||||
case "RSASSA_PSS_SHA_384" -> new SHA384Digest();
|
||||
case "RSASSA_PSS_SHA_512" -> new SHA512Digest();
|
||||
default -> throw new AwsException("InvalidSigningAlgorithmException", "Unsupported algorithm: " + algorithm, 400);
|
||||
case RSASSA_PSS_SHA_256 -> new SHA256Digest();
|
||||
case RSASSA_PSS_SHA_384 -> new SHA384Digest();
|
||||
case RSASSA_PSS_SHA_512 -> new SHA512Digest();
|
||||
default -> throw new IllegalStateException("Not a PSS algorithm: " + algorithm);
|
||||
};
|
||||
return PSSSigner.createRawSigner(new RSABlindedEngine(), digest);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ 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 io.github.hectorvent.floci.services.kms.model.KmsKeySpec;
|
||||
import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
|
||||
import org.bouncycastle.crypto.CryptoException;
|
||||
import org.bouncycastle.crypto.params.ParametersWithRandom;
|
||||
@@ -31,9 +32,8 @@ final class Sm2KeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] sign(KmsKey key, byte[] message, String algorithm, KmsMessageType messageType)
|
||||
public byte[] sign(KmsKey key, byte[] message, KmsKeySpec.Algorithm algorithm, KmsMessageType messageType)
|
||||
throws IOException, CryptoException {
|
||||
AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);
|
||||
AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);
|
||||
SM2Signer signer = new SM2Signer();
|
||||
signer.init(true, new ParametersWithRandom(BcEcKeys.privateKeyParameters(key, CURVE), random));
|
||||
@@ -42,9 +42,8 @@ final class Sm2KeyType implements KmsKeyType {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, String algorithm,
|
||||
public boolean verify(KmsKey key, byte[] message, byte[] signature, KmsKeySpec.Algorithm algorithm,
|
||||
KmsMessageType messageType) throws IOException {
|
||||
AsymmetricKeys.requireSpecAlgorithm(key.getKeySpec(), algorithm);
|
||||
AsymmetricKeys.requireRawMessage(key.getKeySpec(), messageType);
|
||||
SM2Signer verifier = new SM2Signer();
|
||||
verifier.init(false, BcEcKeys.publicKeyParameters(key, CURVE));
|
||||
|
||||
@@ -129,14 +129,6 @@ public enum KmsKeySpec {
|
||||
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),
|
||||
|
||||
@@ -11,7 +11,9 @@ public enum KmsMessageType {
|
||||
try {
|
||||
return KmsMessageType.valueOf(messageType);
|
||||
} catch (IllegalArgumentException _) {
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + messageType + "' at 'MessageType' failed to satisfy constraint", 400);
|
||||
throw new AwsException("ValidationException", "1 validation error detected: Value '" + messageType
|
||||
+ "' at 'messageType' failed to satisfy constraint: Member must satisfy enum value set: "
|
||||
+ "[RAW, DIGEST, EXTERNAL_MU]", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -46,6 +46,7 @@ import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -124,7 +125,7 @@ class KmsServiceTest {
|
||||
assertEquals(KmsKeyUsage.SIGN_VERIFY, key.getKeyUsage());
|
||||
assertNotNull(key.getPrivateKeyEncoded());
|
||||
assertNotNull(key.getPublicKeyEncoded());
|
||||
assertTrue(kmsService.verify(key.getKeyId(), message, signature, "SM2DSA", region));
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, signature, "SM2DSA", region));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1167,7 +1168,8 @@ class KmsServiceTest {
|
||||
kmsService.encrypt(key.getKeyId(), new byte[0], Map.of(), "RSAES_OAEP_SHA_256", REGION));
|
||||
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertEquals("Plaintext must be between 1 and 4096 bytes for Encrypt.", ex.getMessage());
|
||||
assertEquals("1 validation error detected: Value at 'plaintext' failed to satisfy constraint: "
|
||||
+ "Member must have length greater than or equal to 1", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1203,10 +1205,10 @@ class KmsServiceTest {
|
||||
KmsKey key = createRsaKey();
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION));
|
||||
kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION));
|
||||
|
||||
assertEquals("InvalidKeyUsageException", ex.getErrorCode());
|
||||
assertEquals("Algorithm SYMMETRIC_DEFAULT is incompatible with key spec RSA_2048.", ex.getMessage());
|
||||
assertEquals("You cannot generate a data key with an asymmetric CMK", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1214,7 +1216,7 @@ class KmsServiceTest {
|
||||
KmsKey key = kmsService.createKey("sign key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION));
|
||||
kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION));
|
||||
|
||||
assertEquals("InvalidKeyUsageException", ex.getErrorCode());
|
||||
assertEquals(key.getArn() + " key usage is SIGN_VERIFY which is not valid for GenerateDataKey.",
|
||||
@@ -1558,14 +1560,19 @@ class KmsServiceTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521", "ECC_SECG_P256K1"})
|
||||
void signAndVerify(String keySpec) {
|
||||
@CsvSource({
|
||||
"ECC_NIST_P256, ECDSA_SHA_256",
|
||||
"ECC_NIST_P384, ECDSA_SHA_384",
|
||||
"ECC_NIST_P521, ECDSA_SHA_512",
|
||||
"ECC_SECG_P256K1, ECDSA_SHA_256",
|
||||
})
|
||||
void signAndVerify(String keySpec, String algorithm) {
|
||||
KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", keySpec, null, Map.of(), REGION);
|
||||
byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);
|
||||
byte[] sig = kmsService.sign(key.getKeyId(), message, algorithm, REGION);
|
||||
assertNotNull(sig);
|
||||
assertTrue(kmsService.verify(key.getKeyId(), message, sig, "ECDSA_SHA_256", REGION));
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, algorithm, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1575,7 +1582,7 @@ class KmsServiceTest {
|
||||
|
||||
byte[] sig = kmsService.sign(key.getKeyId(), message, "RSASSA_PKCS1_V1_5_SHA_256", REGION);
|
||||
assertNotNull(sig);
|
||||
assertTrue(kmsService.verify(key.getKeyId(), message, sig, "RSASSA_PKCS1_V1_5_SHA_256", REGION));
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, "RSASSA_PKCS1_V1_5_SHA_256", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1588,7 +1595,7 @@ class KmsServiceTest {
|
||||
"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION);
|
||||
|
||||
// floci's own Verify round-trips.
|
||||
assertTrue(kmsService.verify(key.getKeyId(), digest, sig,
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig,
|
||||
"RSASSA_PKCS1_V1_5_SHA_512", KmsMessageType.DIGEST, REGION));
|
||||
|
||||
// External verifier (standard JCA, standing in for openssl/python) reconstructs
|
||||
@@ -1631,9 +1638,9 @@ class KmsServiceTest {
|
||||
"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION);
|
||||
|
||||
// floci's own Verify round-trips, against the digest and against the raw message.
|
||||
assertTrue(kmsService.verify(key.getKeyId(), digest, sig,
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig,
|
||||
"RSASSA_PSS_SHA_256", KmsMessageType.DIGEST, REGION));
|
||||
assertTrue(kmsService.verify(key.getKeyId(), message, sig,
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig,
|
||||
"RSASSA_PSS_SHA_256", KmsMessageType.RAW, REGION));
|
||||
|
||||
// External verifier with the PSS parameters AWS documents for RSASSA_PSS_SHA_256.
|
||||
@@ -1647,34 +1654,52 @@ class KmsServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void signWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() {
|
||||
var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
void signWithInvalidAlgorithmFailsValidation() {
|
||||
KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.sign(key.getKeyId(), "sign me".getBytes(StandardCharsets.UTF_8), "NOT_AN_ALGORITHM", REGION));
|
||||
|
||||
assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode());
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
assertTrue(ex.getMessage().startsWith(
|
||||
"1 validation error detected: Value 'NOT_AN_ALGORITHM' at 'signingAlgorithm' failed to satisfy constraint"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyWithInvalidAlgorithmThrowsInvalidSigningAlgorithm() {
|
||||
var key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
var message = "sign me".getBytes(StandardCharsets.UTF_8);
|
||||
var sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);
|
||||
void verifyWithInvalidAlgorithmFailsValidation() {
|
||||
KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] sig = kmsService.sign(key.getKeyId(), message, "ECDSA_SHA_256", REGION);
|
||||
|
||||
var ex = assertThrows(AwsException.class, () ->
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.verify(key.getKeyId(), message, sig, "NOT_AN_ALGORITHM", REGION));
|
||||
|
||||
assertEquals("InvalidSigningAlgorithmException", ex.getErrorCode());
|
||||
assertEquals("ValidationException", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyWithWrongSignatureReturnsFalse() {
|
||||
void verifyWithWrongSignatureThrowsInvalidSignature() {
|
||||
KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
byte[] message = "sign me".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
assertFalse(kmsService.verify(key.getKeyId(), message,
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.verify(key.getKeyId(), message,
|
||||
"not-a-valid-sig".getBytes(StandardCharsets.UTF_8), "ECDSA_SHA_256", REGION));
|
||||
|
||||
assertEquals("KMSInvalidSignatureException", ex.getErrorCode());
|
||||
assertNull(ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void verifyWithCorruptKeyMaterialIsAnInternalFailure() {
|
||||
KmsKey key = kmsService.createKey("ecdsa key", "SIGN_VERIFY", "ECC_NIST_P256", null, Map.of(), REGION);
|
||||
KmsKey stored = keyStore.get(REGION + "::" + key.getKeyId()).orElseThrow();
|
||||
stored.setPublicKeyEncoded(Base64.getEncoder().encodeToString(new byte[16]));
|
||||
keyStore.put(REGION + "::" + key.getKeyId(), stored);
|
||||
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.verify(key.getKeyId(),
|
||||
"sign me".getBytes(StandardCharsets.UTF_8), new byte[64], "ECDSA_SHA_256", REGION));
|
||||
|
||||
assertEquals("InternalFailure", ex.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -1694,13 +1719,24 @@ class KmsServiceTest {
|
||||
@Test
|
||||
void generateDataKey() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
Map<String, Object> result = kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION);
|
||||
Map<String, Object> result = kmsService.generateDataKey(key.getKeyId(), "AES_256", null, REGION);
|
||||
|
||||
assertNotNull(result.get("Plaintext"));
|
||||
assertNotNull(result.get("CiphertextBlob"));
|
||||
assertEquals(32, ((byte[]) result.get("Plaintext")).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
void generateDataKeyWithoutPlaintextKeepsThePlaintextToItself() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
|
||||
Map<String, Object> result = kmsService.generateDataKeyWithoutPlaintext(key.getKeyId(), "AES_256", null,
|
||||
Map.of(), REGION);
|
||||
|
||||
assertFalse(result.containsKey("Plaintext"));
|
||||
assertNotNull(result.get("CiphertextBlob"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagResource() {
|
||||
KmsKey key = kmsService.createKey(null, REGION);
|
||||
@@ -2132,7 +2168,7 @@ class KmsServiceTest {
|
||||
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));
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), message, sig, algo, REGION));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -2150,7 +2186,7 @@ class KmsServiceTest {
|
||||
|
||||
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));
|
||||
assertDoesNotThrow(() -> kmsService.verify(key.getKeyId(), digest, sig, algorithm.getAlgName(), KmsMessageType.DIGEST, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2161,7 +2197,8 @@ class KmsServiceTest {
|
||||
String keyId = key.getKeyId();
|
||||
AwsException ex = assertThrows(AwsException.class, () ->
|
||||
kmsService.sign(keyId, message, "RSASSA_PKCS1_V1_5_SHA_256", REGION));
|
||||
assertEquals("UnsupportedOperationException", ex.getErrorCode());
|
||||
assertEquals("InvalidKeyUsageException", ex.getErrorCode());
|
||||
assertEquals(key.getArn() + " key usage is ENCRYPT_DECRYPT which is not valid for Sign.", ex.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2261,6 +2298,7 @@ class KmsServiceTest {
|
||||
AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(
|
||||
keyId, token, wrongly, "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));
|
||||
assertEquals("InvalidCiphertextException", ex.getErrorCode());
|
||||
assertNull(ex.getMessage());
|
||||
assertEquals("PendingImport", kmsService.describeKey(keyId, REGION).getKeyState());
|
||||
}
|
||||
|
||||
|
||||
+40
-34
@@ -7,7 +7,6 @@ import io.github.hectorvent.floci.services.kms.model.KmsMessageType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
@@ -16,9 +15,11 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.EnumMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -114,7 +115,8 @@ class KmsKeyTypesTest {
|
||||
"ECC_NIST_EDWARDS25519, ED25519_SHA_512",
|
||||
"ML_DSA_44, ML_DSA_SHAKE_256",
|
||||
})
|
||||
void rawSignatureVerifiesOnlyForTheSignedMessage(KmsKeySpec spec, String algorithm) throws Exception {
|
||||
void rawSignatureVerifiesOnlyForTheSignedMessage(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm)
|
||||
throws Exception {
|
||||
KmsKey key = generatedKey(spec, REGION);
|
||||
KmsKeyType keyType = keyTypes.of(spec);
|
||||
|
||||
@@ -125,6 +127,35 @@ class KmsKeyTypesTest {
|
||||
algorithm, KmsMessageType.RAW));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"RSA_2048, RSASSA_PKCS1_V1_5_SHA_256",
|
||||
"RSA_2048, RSASSA_PSS_SHA_256",
|
||||
"ECC_NIST_P256, ECDSA_SHA_256",
|
||||
"ECC_SECG_P256K1, ECDSA_SHA_256",
|
||||
"ECC_NIST_EDWARDS25519, ED25519_SHA_512",
|
||||
"ML_DSA_44, ML_DSA_SHAKE_256",
|
||||
})
|
||||
void malformedSignatureDoesNotVerify(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm) throws Exception {
|
||||
KmsKey key = generatedKey(spec, REGION);
|
||||
KmsKeyType keyType = keyTypes.of(spec);
|
||||
byte[] oversized = new byte[6144];
|
||||
Arrays.fill(oversized, (byte) 'a');
|
||||
|
||||
for (byte[] signature : List.of(new byte[]{1}, new byte[64], oversized)) {
|
||||
assertFalse(keyType.verify(key, MESSAGE, signature, algorithm, KmsMessageType.RAW));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void corruptPublicKeyThrowsInsteadOfFailingVerification() throws GeneralSecurityException {
|
||||
KmsKey key = generatedKey(KmsKeySpec.ECC_NIST_P256, REGION);
|
||||
key.setPublicKeyEncoded(Base64.getEncoder().encodeToString(new byte[16]));
|
||||
|
||||
assertThrows(GeneralSecurityException.class, () -> keyTypes.of(KmsKeySpec.ECC_NIST_P256)
|
||||
.verify(key, MESSAGE, new byte[64], KmsKeySpec.Algorithm.ECDSA_SHA_256, KmsMessageType.RAW));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"RSA_2048, RSASSA_PKCS1_V1_5_SHA_256, SHA-256",
|
||||
@@ -132,8 +163,8 @@ class KmsKeyTypesTest {
|
||||
"ECC_NIST_P256, ECDSA_SHA_256, SHA-256",
|
||||
"ECC_SECG_P256K1, ECDSA_SHA_256, SHA-256",
|
||||
})
|
||||
void digestSignatureVerifiesAsARawSignature(KmsKeySpec spec, String algorithm, String digestAlgorithm)
|
||||
throws Exception {
|
||||
void digestSignatureVerifiesAsARawSignature(KmsKeySpec spec, KmsKeySpec.Algorithm algorithm,
|
||||
String digestAlgorithm) throws Exception {
|
||||
KmsKey key = generatedKey(spec, REGION);
|
||||
KmsKeyType keyType = keyTypes.of(spec);
|
||||
byte[] digest = MessageDigest.getInstance(digestAlgorithm).digest(MESSAGE);
|
||||
@@ -150,22 +181,10 @@ class KmsKeyTypesTest {
|
||||
KmsKeyType keyType = keyTypes.of(KmsKeySpec.ECC_NIST_EDWARDS25519);
|
||||
byte[] digest = MessageDigest.getInstance("SHA-512").digest(MESSAGE);
|
||||
|
||||
byte[] signature = keyType.sign(key, digest, "ED25519_PH_SHA_512", KmsMessageType.DIGEST);
|
||||
byte[] signature = keyType.sign(key, digest, KmsKeySpec.Algorithm.ED25519_PH_SHA_512, KmsMessageType.DIGEST);
|
||||
|
||||
assertTrue(keyType.verify(key, digest, signature, "ED25519_PH_SHA_512", KmsMessageType.DIGEST));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = KmsKeySpec.class, names = {"ECC_NIST_EDWARDS25519", "ML_DSA_65", "SM2"})
|
||||
void keyTypesWithOneSigningAlgorithmRejectAnyOther(KmsKeySpec spec) throws GeneralSecurityException {
|
||||
KmsKey key = generatedKey(spec, "cn-north-1");
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> keyTypes.of(spec).sign(key, MESSAGE, "ECDSA_SHA_256", KmsMessageType.RAW));
|
||||
|
||||
assertEquals("InvalidKeyUsageException", exception.getErrorCode());
|
||||
assertEquals("Algorithm ECDSA_SHA_256 is incompatible with key spec " + spec.name() + ".",
|
||||
exception.getMessage());
|
||||
assertTrue(keyType.verify(key, digest, signature, KmsKeySpec.Algorithm.ED25519_PH_SHA_512,
|
||||
KmsMessageType.DIGEST));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@@ -214,9 +233,9 @@ class KmsKeyTypesTest {
|
||||
KmsKey key = generatedKey(KmsKeySpec.SM2, region);
|
||||
KmsKeyType keyType = keyTypes.of(KmsKeySpec.SM2);
|
||||
|
||||
byte[] signature = keyType.sign(key, MESSAGE, "SM2DSA", KmsMessageType.RAW);
|
||||
byte[] signature = keyType.sign(key, MESSAGE, KmsKeySpec.Algorithm.SM2DSA, KmsMessageType.RAW);
|
||||
|
||||
assertTrue(keyType.verify(key, MESSAGE, signature, "SM2DSA", KmsMessageType.RAW));
|
||||
assertTrue(keyType.verify(key, MESSAGE, signature, KmsKeySpec.Algorithm.SM2DSA, KmsMessageType.RAW));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -230,19 +249,6 @@ class KmsKeyTypesTest {
|
||||
assertNull(key.getPrivateKeyEncoded());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = KmsKeySpec.class, names = {"SYMMETRIC_DEFAULT", "HMAC_256"})
|
||||
void keyTypesWithoutSigningRefuseToSignAndNeverVerify(KmsKeySpec spec) throws Exception {
|
||||
KmsKey key = generatedKey(spec, REGION);
|
||||
KmsKeyType keyType = keyTypes.of(spec);
|
||||
|
||||
AwsException exception = assertThrows(AwsException.class,
|
||||
() -> keyType.sign(key, MESSAGE, "RSASSA_PSS_SHA_256", KmsMessageType.RAW));
|
||||
|
||||
assertEquals("UnsupportedOperationException", exception.getErrorCode());
|
||||
assertFalse(keyType.verify(key, MESSAGE, new byte[64], "RSASSA_PSS_SHA_256", KmsMessageType.RAW));
|
||||
}
|
||||
|
||||
private KmsKey generatedKey(KmsKeySpec spec, String region) throws GeneralSecurityException {
|
||||
KmsKey key = newKey(spec);
|
||||
keyTypes.of(spec).generateKeyMaterial(key, region);
|
||||
|
||||
Reference in new issue
Block a user