Light, fluffy, and always free - The AWS Local Emulator alternative
fix(kms): apply real RSAES-OAEP for RSA keys in Encrypt and Decrypt (#3038)
TATSUNO “Taz” Yasuhiroe5afe3518be8
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.javaindex 42439cc4d8..0fcef928e7 100644--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/KmsFeaturesTest.java@@ -8,6 +8,9 @@ import software.amazon.awssdk.services.kms.model.DisabledException;import software.amazon.awssdk.services.kms.model.EncryptionAlgorithmSpec;import software.amazon.awssdk.services.kms.model.GetKeyPolicyResponse;import software.amazon.awssdk.services.kms.model.IncorrectKeyException;+import software.amazon.awssdk.services.kms.model.InvalidKeyUsageException;+import software.amazon.awssdk.services.kms.model.KeySpec;+import software.amazon.awssdk.services.kms.model.KeyUsageType;import software.amazon.awssdk.services.kms.model.KmsInvalidStateException;import software.amazon.awssdk.services.kms.model.ListResourceTagsResponse;@@ -24,8 +27,9 @@ import static org.assertj.core.api.Assertions.*;* #DescribeKey — Returns proper EncryptionAlgorithms, SigningAlgorithms, and MacAlgorithms* #1844 — Decrypt enforces KeyId against the wrapping CMK (IncorrectKeyException)* #1844 — ReEncrypt enforces SourceKeyId against the wrapping CMK (IncorrectKeyException)+ * #3024: Encrypt/Decrypt apply real RSAES-OAEP for RSA keys*/-@DisplayName("KMS features (#258 #259 #269 #1844)")+@DisplayName("KMS features (#258 #259 #269 #1844 #3024)")@TestMethodOrder(MethodOrderer.OrderAnnotation.class)class KmsFeaturesTest {@@ -384,4 +388,83 @@ class KmsFeaturesTest {kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));}}++ // ── Issue #3024: Encrypt/Decrypt apply real RSAES-OAEP for RSA keys ──────++ @Test+ @Order(70)+ void rsaOaepEncryptDecryptRoundTrip() {+ var keyId = kms.createKey(b -> b+ .keyUsage(KeyUsageType.ENCRYPT_DECRYPT)+ .keySpec(KeySpec.RSA_2048))+ .keyMetadata().keyId();++ try {+ var encrypted = kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret payload", StandardCharsets.UTF_8))+ .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256));++ assertThat(encrypted.ciphertextBlob().asByteArray()).hasSize(256);+ assertThat(encrypted.encryptionAlgorithm()).isEqualTo(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256);++ var decrypted = kms.decrypt(b -> b+ .keyId(keyId)+ .ciphertextBlob(encrypted.ciphertextBlob())+ .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256));++ assertThat(decrypted.plaintext().asUtf8String()).isEqualTo("secret payload");+ assertThat(decrypted.encryptionAlgorithm()).isEqualTo(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256);+ } finally {+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ }+ }++ @Test+ @Order(71)+ void decryptAcceptsRsaOaepCiphertextMadeWithGetPublicKey() throws Exception {+ var keyId = kms.createKey(b -> b+ .keyUsage(KeyUsageType.ENCRYPT_DECRYPT)+ .keySpec(KeySpec.RSA_2048))+ .keyMetadata().keyId();++ try {+ var publicKeyDer = kms.getPublicKey(b -> b.keyId(keyId)).publicKey().asByteArray();+ var publicKey = java.security.KeyFactory.getInstance("RSA")+ .generatePublic(new java.security.spec.X509EncodedKeySpec(publicKeyDer));+ var cipher = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey, new javax.crypto.spec.OAEPParameterSpec(+ "SHA-256", "MGF1", java.security.spec.MGF1ParameterSpec.SHA256,+ javax.crypto.spec.PSource.PSpecified.DEFAULT));+ var localCiphertext = cipher.doFinal("secret payload".getBytes(StandardCharsets.UTF_8));++ var decrypted = kms.decrypt(b -> b+ .keyId(keyId)+ .ciphertextBlob(SdkBytes.fromByteArray(localCiphertext))+ .encryptionAlgorithm(EncryptionAlgorithmSpec.RSAES_OAEP_SHA_256));++ assertThat(decrypted.plaintext().asUtf8String()).isEqualTo("secret payload");+ } finally {+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ }+ }++ @Test+ @Order(72)+ void rsaEncryptWithDefaultAlgorithmRaisesInvalidKeyUsage() {+ var keyId = kms.createKey(b -> b+ .keyUsage(KeyUsageType.ENCRYPT_DECRYPT)+ .keySpec(KeySpec.RSA_2048))+ .keyMetadata().keyId();++ try {+ assertThatThrownBy(+ () -> kms.encrypt(b -> b+ .keyId(keyId)+ .plaintext(SdkBytes.fromString("secret payload", StandardCharsets.UTF_8)))+ ).isInstanceOf(InvalidKeyUsageException.class);+ } finally {+ kms.scheduleKeyDeletion(b -> b.keyId(keyId).pendingWindowInDays(7));+ }+ }}diff --git a/docs/services/kms.md b/docs/services/kms.mdindex e4ebc3fa36..50030ffab1 100644--- a/docs/services/kms.md+++ b/docs/services/kms.md@@ -48,6 +48,12 @@| `RotateKeyOnDemand` | Rotate key material on demand (symmetric keys only) |<!-- floci:actions:end -->+## Asymmetric Encryption++`Encrypt`, `Decrypt`, and `ReEncrypt` apply real RSAES-OAEP for RSA keys (`RSA_2048`, `RSA_3072`, `RSA_4096`) when `EncryptionAlgorithm` is `RSAES_OAEP_SHA_1` or `RSAES_OAEP_SHA_256`. The ciphertext is raw RSA output of the modulus length, for example exactly 256 bytes for `RSA_2048`. A ciphertext produced locally with the public key from `GetPublicKey` decrypts the same way it does on real AWS, which makes the usual envelope pattern work. Only the encrypting side needs the public key. As on real AWS, asymmetric `Decrypt` requires `KeyId`, an `EncryptionContext` is rejected for asymmetric keys, and plaintext larger than the OAEP capacity of the key fails validation.++Symmetric keys keep the emulator's internal ciphertext format, which is not compatible with ciphertexts from real AWS KMS.+## Grant Support ScopeGrant lifecycle operations (`CreateGrant`, `ListGrants`, `ListRetirableGrants`, `RevokeGrant`, `RetireGrant`) are supported. However, grant lifecycle support **does not** imply grant-based authorization enforcement on cryptographic operations (`Encrypt`, `Decrypt`, `Sign`, `Verify`, `GenerateDataKey`, etc.). Grants are stored and queryable but are not evaluated during crypto operations.diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.javaindex 368ea0765e..4a9ee1348a 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsJsonHandler.java@@ -274,11 +274,14 @@ public class KmsJsonHandler {String keyId = request.path("KeyId").asText();byte[] plaintext = decodeBlob(request, "Plaintext");Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));- byte[] ciphertext = service.encrypt(keyId, plaintext, context, region);+ String algorithm = request.path("EncryptionAlgorithm").asText(null);++ KmsService.EncryptResult result = service.encrypt(keyId, plaintext, context, algorithm, region);ObjectNode response = objectMapper.createObjectNode();- response.put("CiphertextBlob", Base64.getEncoder().encodeToString(ciphertext));- response.put("KeyId", service.describeKey(keyId, region).getArn());+ response.put("CiphertextBlob", Base64.getEncoder().encodeToString(result.ciphertext()));+ response.put("KeyId", result.keyArn());+ response.put("EncryptionAlgorithm", result.encryptionAlgorithm());return Response.ok(response).build();}@@ -286,14 +289,16 @@ public class KmsJsonHandler {byte[] ciphertext = decodeBlob(request, "CiphertextBlob");Map<String, String> context = readEncryptionContext(request.path("EncryptionContext"));String requestKeyId = request.path("KeyId").asText(null);+ String algorithm = request.path("EncryptionAlgorithm").asText(null);- KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region, requestKeyId);+ KmsService.DecryptResult result = service.decryptAndResolveKey(ciphertext, context, region, requestKeyId, algorithm);ObjectNode response = objectMapper.createObjectNode();response.put("Plaintext", Base64.getEncoder().encodeToString(result.plaintext()));if (result.keyArn() != null) {response.put("KeyId", result.keyArn());}+ response.put("EncryptionAlgorithm", result.encryptionAlgorithm());return Response.ok(response).build();}@@ -331,15 +336,21 @@ public class KmsJsonHandler {String destKeyId = request.path("DestinationKeyId").asText();Map<String, String> sourceContext = readEncryptionContext(request.path("SourceEncryptionContext"));Map<String, String> destContext = readEncryptionContext(request.path("DestinationEncryptionContext"));+ String sourceAlgorithm = request.path("SourceEncryptionAlgorithm").asText(null);+ String destAlgorithm = request.path("DestinationEncryptionAlgorithm").asText(null);String sourceKeyId = request.path("SourceKeyId").asText(null);- KmsService.DecryptResult source = service.decryptAndResolveKey(ciphertext, sourceContext, region, sourceKeyId);- byte[] newCiphertext = service.encrypt(destKeyId, source.plaintext(), destContext, region);+ KmsService.DecryptResult source = service.decryptAndResolveKey(+ ciphertext, sourceContext, region, sourceKeyId, sourceAlgorithm);+ KmsService.EncryptResult destination = service.encrypt(+ destKeyId, source.plaintext(), destContext, destAlgorithm, region);ObjectNode response = objectMapper.createObjectNode();- response.put("CiphertextBlob", Base64.getEncoder().encodeToString(newCiphertext));- response.put("KeyId", service.describeKey(destKeyId, region).getArn());+ response.put("CiphertextBlob", Base64.getEncoder().encodeToString(destination.ciphertext()));+ response.put("KeyId", destination.keyArn());response.put("SourceKeyId", source.keyArn());+ response.put("SourceEncryptionAlgorithm", source.encryptionAlgorithm());+ response.put("DestinationEncryptionAlgorithm", destination.encryptionAlgorithm());return Response.ok(response).build();}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.javaindex 02e5be981e..e4cb68f20c 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsService.java@@ -54,7 +54,10 @@ import org.bouncycastle.jce.ECNamedCurveTable;import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;import org.jboss.logging.Logger;+import javax.crypto.Cipher;import javax.crypto.Mac;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;import javax.crypto.spec.SecretKeySpec;import java.io.ByteArrayOutputStream;import java.io.IOException;@@ -789,6 +792,8 @@ public class KmsService implements ResourceProvider {private static final int NONCE_BYTES = 8;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;private static final SecureRandom SECURE_RANDOM = new SecureRandom();@@ -798,8 +803,29 @@ public class KmsService implements ResourceProvider {}public byte[] encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext, String region) {+ return encrypt(keyId, plaintext, encryptionContext, null, region).ciphertext();+ }++ public EncryptResult encrypt(String keyId, byte[] plaintext, Map<String, String> encryptionContext,+ String encryptionAlgorithm, String region) {+ return encrypt(keyId, plaintext, encryptionContext, encryptionAlgorithm, region, "Encrypt");+ }++ 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);KmsKey kmsKey = resolveKey(keyId, region);validateKeyIsUsableForCryptoOperations(kmsKey);+ validateKeyUsageForEncryptionOperation(kmsKey, operation);+ validateEncryptionAlgorithmForSpec(algorithm, kmsKey.getKeySpec());++ if (kmsKey.getKeySpec().getKeyType() == KmsKeySpec.KeyType.RSA) {+ rejectEncryptionContextForAsymmetricKey(encryptionContext);+ validateRsaPlaintextLength(plaintext, algorithm, kmsKey.getKeySpec());+ byte[] ciphertext = rsaOaep(Cipher.ENCRYPT_MODE, kmsKey, algorithm, plaintext);+ return new EncryptResult(ciphertext, kmsKey.getArn(), algorithm.getAlgName());+ }byte[] nonceBytes = new byte[NONCE_BYTES];SECURE_RANDOM.nextBytes(nonceBytes);@@ -810,7 +836,7 @@ public class KmsService implements ResourceProvider {+ nonceHex + ":"+ contextFingerprint(encryptionContext) + ":"+ Base64.getEncoder().encodeToString(plaintext);- return blob.getBytes(StandardCharsets.UTF_8);+ return new EncryptResult(blob.getBytes(StandardCharsets.UTF_8), kmsKey.getArn(), algorithm.getAlgName());}public byte[] decrypt(byte[] ciphertext, String region) {@@ -822,7 +848,7 @@ public class KmsService implements ResourceProvider {if (!parsed.contextFingerprint.equals(contextFingerprint(encryptionContext))) {throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);}- return Base64.getDecoder().decode(parsed.payload);+ return decodePayload(parsed);}public String decryptToKeyArn(byte[] ciphertext, String region) {@@ -843,11 +869,40 @@ public class KmsService implements ResourceProvider {String region,String requestKeyId) {+ return decryptAndResolveKey(ciphertext, encryptionContext, region, requestKeyId, null);+ }++ public DecryptResult decryptAndResolveKey(+ byte[] ciphertext,+ Map<String, String> encryptionContext,+ String region,+ String requestKeyId,+ String encryptionAlgorithm+ ) {+ KmsKeySpec.Algorithm algorithm = resolveEncryptionAlgorithm(encryptionAlgorithm);+ if (algorithm != KmsKeySpec.Algorithm.SYMMETRIC_DEFAULT) {+ // Raw asymmetric ciphertext carries no key metadata, so real KMS requires KeyId.+ if (requestKeyId == null || requestKeyId.isBlank()) {+ throw new AwsException("ValidationException", "KeyId must not be null", 400);+ }+ KmsKey requestKey = resolveKey(requestKeyId, region);+ validateKeyIsUsableForCryptoOperations(requestKey);+ validateKeyUsageForEncryptionOperation(requestKey, "Decrypt");+ validateEncryptionAlgorithmForSpec(algorithm, requestKey.getKeySpec());+ rejectEncryptionContextForAsymmetricKey(encryptionContext);+ byte[] plaintext = rsaOaep(Cipher.DECRYPT_MODE, requestKey, algorithm, ciphertext);+ return new DecryptResult(plaintext, requestKey.getArn(), algorithm.getAlgName());+ }++ // With the defaulted SYMMETRIC_DEFAULT algorithm, real KMS parses the ciphertext+ // before it compares the algorithm with the named key's spec: Decrypt of a raw RSA+ // ciphertext with an RSA KeyId but no EncryptionAlgorithm answers+ // 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);}- byte[] plaintext = Base64.getDecoder().decode(parsed.payload);+ byte[] plaintext = decodePayload(parsed);if (requestKeyId != null && !requestKeyId.isBlank()) {KmsKey requestKey = resolveKey(requestKeyId, region);@@ -860,7 +915,7 @@ public class KmsService implements ResourceProvider {}validateKeyIsUsableForCryptoOperations(requestKey);- return new DecryptResult(plaintext, requestKey.getArn());+ return new DecryptResult(plaintext, requestKey.getArn(), algorithm.getAlgName());}KmsKey key;@@ -870,13 +925,15 @@ public class KmsService implements ResourceProvider {key = null;}if (key == null) {- return new DecryptResult(plaintext, null);+ return new DecryptResult(plaintext, null, algorithm.getAlgName());}validateKeyIsUsableForCryptoOperations(key);- return new DecryptResult(plaintext, key.getArn());+ return new DecryptResult(plaintext, key.getArn(), algorithm.getAlgName());}- public record DecryptResult(byte[] plaintext, String keyArn) {}+ public record EncryptResult(byte[] ciphertext, String keyArn, String encryptionAlgorithm) {}++ public record DecryptResult(byte[] plaintext, String keyArn, String encryptionAlgorithm) {}public record GenerateMacResult(byte[] mac, String keyArn) {}@@ -905,6 +962,15 @@ public class KmsService implements ResourceProvider {throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);}+ /** A blob whose payload is not valid base64 is a bad ciphertext, not a server fault. */+ private static byte[] decodePayload(ParsedBlob parsed) {+ try {+ return Base64.getDecoder().decode(parsed.payload);+ } catch (IllegalArgumentException e) {+ throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ }+ }+/*** Stable fingerprint of an EncryptionContext map. AWS treats EncryptionContext as a* case-sensitive exact match, so we hash a length-prefixed serialization of the sorted@@ -931,6 +997,105 @@ 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+ * value falls back to the SYMMETRIC_DEFAULT default.+ */+ private static KmsKeySpec.Algorithm resolveEncryptionAlgorithm(String encryptionAlgorithm) {+ String name = (encryptionAlgorithm == null || encryptionAlgorithm.isBlank())+ ? "SYMMETRIC_DEFAULT" : encryptionAlgorithm;+ return switch (name) {+ case "SYMMETRIC_DEFAULT" -> KmsKeySpec.Algorithm.SYMMETRIC_DEFAULT;+ case "RSAES_OAEP_SHA_1" -> KmsKeySpec.Algorithm.RSAES_OAEP_SHA_1;+ case "RSAES_OAEP_SHA_256" -> KmsKeySpec.Algorithm.RSAES_OAEP_SHA_256;+ case "SM2PKE" -> throw new AwsException("UnsupportedOperationException",+ "SM2PKE is not supported.", 400);+ 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);+ };+ }++ private static void validateKeyUsageForEncryptionOperation(KmsKey key, String operation) {+ if (KmsKeyUsage.ENCRYPT_DECRYPT != 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) {+ 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);+ }+ }++ private static void rejectEncryptionContextForAsymmetricKey(Map<String, String> encryptionContext) {+ if (encryptionContext != null && !encryptionContext.isEmpty()) {+ throw new AwsException("ValidationException",+ "EncryptionContext is not supported when encrypting/decrypting with asymmetric CMKs.", 400);+ }+ }++ /** RFC 8017 7.1.1: OAEP holds at most k - 2*hLen - 2 bytes, k being the modulus length. */+ private static void validateRsaPlaintextLength(byte[] plaintext, KmsKeySpec.Algorithm algorithm, KmsKeySpec spec) {+ int modulusBytes = switch (spec) {+ case RSA_2048 -> 256;+ case RSA_3072 -> 384;+ case RSA_4096 -> 512;+ default -> throw new AwsException("InvalidKeyUsageException",+ "Algorithm " + algorithm.getAlgName() + " is incompatible with key spec " + spec.name() + ".", 400);+ };+ int digestBytes = algorithm == KmsKeySpec.Algorithm.RSAES_OAEP_SHA_1 ? 20 : 32;+ int maxBytes = modulusBytes - 2 * digestBytes - 2;+ if (plaintext.length > maxBytes) {+ throw new AwsException("ValidationException",+ "Algorithm " + algorithm.getAlgName() + " and key spec " + spec.name()+ + " cannot encrypt data larger than " + maxBytes + " bytes.", 400);+ }+ }++ /**+ * RSAES-OAEP with an explicit OAEPParameterSpec. The JDK's named OAEP transformations+ * default MGF1 to SHA-1 whatever the main digest is, while KMS RSAES_OAEP_SHA_256 uses+ * MGF1 over SHA-256, so the parameters are always spelled out.+ */+ private byte[] rsaOaep(int mode, KmsKey key, KmsKeySpec.Algorithm algorithm, byte[] input) {+ try {+ var digest = algorithm == KmsKeySpec.Algorithm.RSAES_OAEP_SHA_1 ? "SHA-1" : "SHA-256";+ var cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ var params = new OAEPParameterSpec(digest, "MGF1", new MGF1ParameterSpec(digest),+ PSource.PSpecified.DEFAULT);+ if (mode == Cipher.ENCRYPT_MODE) {+ cipher.init(mode, loadPublicKey(key.getPublicKeyEncoded(), key.getKeySpec()), params);+ } else {+ cipher.init(mode, loadPrivateKey(key.getPrivateKeyEncoded(), key.getKeySpec()), params);+ }+ return cipher.doFinal(input);+ } catch (Exception e) {+ if (mode == Cipher.DECRYPT_MODE) {+ // Real KMS answers any OAEP failure the same way: the padding check hides+ // whether the bytes were garbage, the wrong length, or made for another key.+ // The log line keeps broken key material or a missing cipher diagnosable.+ LOG.debugv(e, "RSA OAEP decrypt failed for key {0}", key.getKeyId());+ throw new AwsException("InvalidCiphertextException", "The ciphertext is invalid.", 400);+ }+ LOG.warnv(e, "RSA OAEP encrypt failed for key {0}", key.getKeyId());+ throw new AwsException("InternalFailure", "Failed to encrypt: " + e.getMessage(), 500);+ }+ }+public byte[] sign(String keyId, byte[] message, String algorithm, String region) {return sign(keyId, message, algorithm, RAW, region);}@@ -1171,12 +1336,12 @@ public class KmsService implements ResourceProvider {byte[] plaintext = new byte[len];ThreadLocalRandom.current().nextBytes(plaintext);- byte[] ciphertext = encrypt(keyId, plaintext, encryptionContext, region);+ EncryptResult encrypted = encrypt(keyId, plaintext, encryptionContext, null, region, "GenerateDataKey");Map<String, Object> result = new HashMap<>();result.put("Plaintext", plaintext);- result.put("CiphertextBlob", ciphertext);- result.put("KeyId", resolveKey(keyId, region).getArn());+ result.put("CiphertextBlob", encrypted.ciphertext());+ result.put("KeyId", encrypted.keyArn());return result;}diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.javaindex 103aafef30..6a646aacfd 100644--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsIntegrationTest.java@@ -1562,4 +1562,196 @@ class KmsIntegrationTest {throw new IllegalStateException(e);}}++ /**+ * Real KMS applies RSAES-OAEP with the key's actual RSA material, so the ciphertext for an+ * RSA_2048 key is exactly 256 bytes of raw RSA output, and both Encrypt and Decrypt echo the+ * EncryptionAlgorithm. Checked against real AWS in us-east-1.+ */+ @Test+ void rsaOaepEncryptDecryptRoundTripThroughJsonHandler() {+ String keyId = createRsaEncryptionKey();+ String plaintext = Base64.getEncoder().encodeToString("secret payload".getBytes(StandardCharsets.UTF_8));++ var encryptResponse = given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(keyId, plaintext))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("EncryptionAlgorithm", equalTo("RSAES_OAEP_SHA_256"))+ .extract().jsonPath();++ String ciphertext = encryptResponse.getString("CiphertextBlob");+ assertEquals(256, Base64.getDecoder().decode(ciphertext).length);++ given()+ .header("X-Amz-Target", "TrentService.Decrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"CiphertextBlob\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(keyId, ciphertext))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Plaintext", equalTo(plaintext))+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("EncryptionAlgorithm", equalTo("RSAES_OAEP_SHA_256"));+ }++ /**+ * The envelope pattern from issue #3024: only the encrypting side holds the public key from+ * GetPublicKey, encrypts locally with RSA-OAEP, and Decrypt accepts that ciphertext. Real+ * AWS returns the plaintext here.+ */+ @Test+ void decryptAcceptsRsaOaepCiphertextMadeWithGetPublicKey() throws Exception {+ String keyId = createRsaEncryptionKey();++ String publicKeyBase64 = given()+ .header("X-Amz-Target", "TrentService.GetPublicKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"" + keyId + "\"}")+ .when().post("/")+ .then().statusCode(200)+ .body("KeySpec", equalTo("RSA_2048"))+ .body("KeyUsage", equalTo("ENCRYPT_DECRYPT"))+ .body("EncryptionAlgorithms", equalTo(List.of("RSAES_OAEP_SHA_1", "RSAES_OAEP_SHA_256")))+ .extract().path("PublicKey");++ var publicKey = java.security.KeyFactory.getInstance("RSA").generatePublic(+ new java.security.spec.X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBase64)));+ var cipher = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey, new javax.crypto.spec.OAEPParameterSpec(+ "SHA-256", "MGF1", java.security.spec.MGF1ParameterSpec.SHA256,+ javax.crypto.spec.PSource.PSpecified.DEFAULT));+ byte[] localCiphertext = cipher.doFinal("secret payload".getBytes(StandardCharsets.UTF_8));++ given()+ .header("X-Amz-Target", "TrentService.Decrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"CiphertextBlob\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(keyId, Base64.getEncoder().encodeToString(localCiphertext)))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Plaintext", equalTo(Base64.getEncoder()+ .encodeToString("secret payload".getBytes(StandardCharsets.UTF_8))));+ }++ /**+ * Real KMS rejects Encrypt on an RSA key when EncryptionAlgorithm is left at its+ * SYMMETRIC_DEFAULT default: InvalidKeyUsageException with this exact message.+ */+ @Test+ void rsaEncryptWithDefaultAlgorithmReturnsInvalidKeyUsage() {+ String keyId = createRsaEncryptionKey();+ String plaintext = Base64.getEncoder().encodeToString("secret payload".getBytes(StandardCharsets.UTF_8));++ given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}".formatted(keyId, plaintext))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidKeyUsageException"))+ .body("message", equalTo("Algorithm SYMMETRIC_DEFAULT is incompatible with key spec RSA_2048."));+ }++ /**+ * The Decrypt-side twin of the test above, with the algorithm left at its default.+ * Real KMS parses the ciphertext before comparing the defaulted SYMMETRIC_DEFAULT+ * algorithm with the named key's spec, so a raw RSA ciphertext answers+ * InvalidCiphertextException, measured against real AWS in us-east-1.+ */+ @Test+ void rsaDecryptWithDefaultAlgorithmReturnsInvalidCiphertext() {+ String keyId = createRsaEncryptionKey();+ String plaintext = Base64.getEncoder().encodeToString("secret payload".getBytes(StandardCharsets.UTF_8));++ String ciphertext = given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(keyId, plaintext))+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CiphertextBlob");++ given()+ .header("X-Amz-Target", "TrentService.Decrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"CiphertextBlob\":\"%s\"}".formatted(keyId, ciphertext))+ .when().post("/")+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidCiphertextException"));+ }++ /**+ * ReEncrypt threads SourceEncryptionAlgorithm and DestinationEncryptionAlgorithm+ * independently. Re-wrapping a symmetric ciphertext under an RSA key makes the two+ * response fields differ, which pins the source/destination wiring.+ */+ @Test+ void reEncryptFromSymmetricToRsaEchoesBothAlgorithms() {+ String symmetricKeyId = given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"Description\":\"symmetric source\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");+ String rsaKeyId = createRsaEncryptionKey();+ String plaintext = Base64.getEncoder().encodeToString("secret payload".getBytes(StandardCharsets.UTF_8));++ String symmetricCiphertext = given()+ .header("X-Amz-Target", "TrentService.Encrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"Plaintext\":\"%s\"}".formatted(symmetricKeyId, plaintext))+ .when().post("/")+ .then().statusCode(200)+ .extract().path("CiphertextBlob");++ var reEncryptResponse = given()+ .header("X-Amz-Target", "TrentService.ReEncrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body(("{\"CiphertextBlob\":\"%s\",\"SourceKeyId\":\"%s\",\"DestinationKeyId\":\"%s\","+ + "\"DestinationEncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}")+ .formatted(symmetricCiphertext, symmetricKeyId, rsaKeyId))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyId", startsWith("arn:aws:kms:"))+ .body("SourceKeyId", startsWith("arn:aws:kms:"))+ .body("SourceEncryptionAlgorithm", equalTo("SYMMETRIC_DEFAULT"))+ .body("DestinationEncryptionAlgorithm", equalTo("RSAES_OAEP_SHA_256"))+ .extract().jsonPath();++ String rsaCiphertext = reEncryptResponse.getString("CiphertextBlob");+ assertEquals(256, Base64.getDecoder().decode(rsaCiphertext).length);++ given()+ .header("X-Amz-Target", "TrentService.Decrypt")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\",\"CiphertextBlob\":\"%s\",\"EncryptionAlgorithm\":\"RSAES_OAEP_SHA_256\"}"+ .formatted(rsaKeyId, rsaCiphertext))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("Plaintext", equalTo(plaintext));+ }++ private String createRsaEncryptionKey() {+ return given()+ .header("X-Amz-Target", "TrentService.CreateKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyUsage\":\"ENCRYPT_DECRYPT\",\"KeySpec\":\"RSA_2048\"}")+ .when().post("/")+ .then().statusCode(200)+ .extract().path("KeyMetadata.KeyId");+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.javaindex bb00b84195..446c9cc4af 100644--- a/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/kms/KmsServiceTest.java@@ -861,6 +861,309 @@ class KmsServiceTest {assertEquals(400, ex.getHttpStatus());}+ /**+ * RSAES-OAEP on RSA keys, issue #3024. Expected ciphertext sizes, error codes and+ * messages were measured against real AWS KMS in us-east-1.+ */+ @Nested+ class RsaEncryptDecryptTests {++ private static final byte[] PLAINTEXT = "secret payload".getBytes(StandardCharsets.UTF_8);++ private KmsKey createRsaKey() {+ return kmsService.createKey("rsa key", "ENCRYPT_DECRYPT", "RSA_2048", null, Map.of(), REGION);+ }++ @Test+ void oaepSha256RoundTripProducesRawRsaCiphertext() {+ KmsKey key = createRsaKey();++ KmsService.EncryptResult encrypted =+ kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(), "RSAES_OAEP_SHA_256", REGION);++ assertEquals(256, encrypted.ciphertext().length);+ assertEquals(key.getArn(), encrypted.keyArn());+ assertEquals("RSAES_OAEP_SHA_256", encrypted.encryptionAlgorithm());++ KmsService.DecryptResult decrypted = kmsService.decryptAndResolveKey(+ encrypted.ciphertext(), Map.of(), REGION, key.getKeyId(), "RSAES_OAEP_SHA_256");++ assertArrayEquals(PLAINTEXT, decrypted.plaintext());+ assertEquals(key.getArn(), decrypted.keyArn());+ assertEquals("RSAES_OAEP_SHA_256", decrypted.encryptionAlgorithm());+ }++ @Test+ void oaepSha1RoundTripAllowsUpTo214Bytes() {+ KmsKey key = createRsaKey();+ byte[] plaintext = new byte[214];++ KmsService.EncryptResult encrypted =+ kmsService.encrypt(key.getKeyId(), plaintext, Map.of(), "RSAES_OAEP_SHA_1", REGION);+ KmsService.DecryptResult decrypted = kmsService.decryptAndResolveKey(+ encrypted.ciphertext(), Map.of(), REGION, key.getKeyId(), "RSAES_OAEP_SHA_1");++ assertEquals(256, encrypted.ciphertext().length);+ assertArrayEquals(plaintext, decrypted.plaintext());+ }++ @Test+ void decryptAcceptsCiphertextMadeLocallyWithThePublicKey() throws Exception {+ KmsKey key = createRsaKey();+ var publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(+ Base64.getDecoder().decode(kmsService.getPublicKey(key.getKeyId(), REGION).getPublicKeyEncoded())));+ var cipher = javax.crypto.Cipher.getInstance("RSA/ECB/OAEPPadding");+ cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey, new javax.crypto.spec.OAEPParameterSpec(+ "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, javax.crypto.spec.PSource.PSpecified.DEFAULT));+ byte[] localCiphertext = cipher.doFinal(PLAINTEXT);++ KmsService.DecryptResult decrypted = kmsService.decryptAndResolveKey(+ localCiphertext, Map.of(), REGION, key.getKeyId(), "RSAES_OAEP_SHA_256");++ assertArrayEquals(PLAINTEXT, decrypted.plaintext());+ }++ @Test+ void encryptWithDefaultAlgorithmThrowsInvalidKeyUsage() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(), null, REGION));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals("Algorithm SYMMETRIC_DEFAULT is incompatible with key spec RSA_2048.", ex.getMessage());+ }++ @Test+ void encryptOnSymmetricKeyWithRsaAlgorithmThrowsInvalidKeyUsage() {+ KmsKey key = kmsService.createKey(null, REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(), "RSAES_OAEP_SHA_256", REGION));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals("Algorithm RSAES_OAEP_SHA_256 is incompatible with key spec SYMMETRIC_DEFAULT.",+ ex.getMessage());+ }++ @Test+ void encryptWithSignVerifyKeyThrowsInvalidKeyUsage() {+ KmsKey key = kmsService.createKey("sign key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(), "RSAES_OAEP_SHA_256", REGION));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals(key.getArn() + " key usage is SIGN_VERIFY which is not valid for Encrypt.",+ ex.getMessage());+ }++ @Test+ void encryptWithEncryptionContextThrowsValidation() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of("foo", "bar"), "RSAES_OAEP_SHA_256", REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("EncryptionContext is not supported when encrypting/decrypting with asymmetric CMKs.",+ ex.getMessage());+ }++ @Test+ void encryptOver190BytesWithOaepSha256ThrowsValidation() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), new byte[191], Map.of(), "RSAES_OAEP_SHA_256", REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("Algorithm RSAES_OAEP_SHA_256 and key spec RSA_2048 cannot encrypt data larger than 190 bytes.",+ ex.getMessage());+ }++ @Test+ void decryptWithoutKeyIdThrowsValidation() {+ KmsKey key = createRsaKey();+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(),+ "RSAES_OAEP_SHA_256", REGION).ciphertext();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, null, "RSAES_OAEP_SHA_256"));++ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("KeyId must not be null", ex.getMessage());+ }++ @Test+ void decryptGarbageThrowsInvalidCiphertext() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(new byte[256], Map.of(), REGION,+ key.getKeyId(), "RSAES_OAEP_SHA_256"));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void decryptWithWrongRsaKeyThrowsInvalidCiphertext() {+ KmsKey key = createRsaKey();+ KmsKey otherKey = createRsaKey();+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(),+ "RSAES_OAEP_SHA_256", REGION).ciphertext();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION,+ otherKey.getKeyId(), "RSAES_OAEP_SHA_256"));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void decryptWithWrongOaepHashThrowsInvalidCiphertext() {+ KmsKey key = createRsaKey();+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(),+ "RSAES_OAEP_SHA_256", REGION).ciphertext();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION,+ key.getKeyId(), "RSAES_OAEP_SHA_1"));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void decryptOnSymmetricKeyWithRsaAlgorithmThrowsInvalidKeyUsage() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION,+ key.getKeyId(), "RSAES_OAEP_SHA_256"));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals("Algorithm RSAES_OAEP_SHA_256 is incompatible with key spec SYMMETRIC_DEFAULT.",+ ex.getMessage());+ }++ @Test+ void symmetricDecryptStillReportsSymmetricDefaultAlgorithm() {+ KmsKey key = kmsService.createKey(null, REGION);+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, REGION);++ KmsService.DecryptResult result =+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, key.getKeyId(), null);++ assertArrayEquals(PLAINTEXT, result.plaintext());+ assertEquals("SYMMETRIC_DEFAULT", result.encryptionAlgorithm());+ }++ @Test+ void decryptWithRsaKeyIdAndDefaultAlgorithmThrowsInvalidCiphertext() {+ // Real KMS parses the ciphertext before comparing the defaulted SYMMETRIC_DEFAULT+ // algorithm with the key spec, so raw RSA bytes fail as a bad ciphertext.+ KmsKey key = createRsaKey();+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(),+ "RSAES_OAEP_SHA_256", REGION).ciphertext();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, key.getKeyId(), null));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void decryptWithEncryptionContextThrowsValidation() {+ KmsKey key = createRsaKey();+ byte[] ciphertext = kmsService.encrypt(key.getKeyId(), PLAINTEXT, Map.of(),+ "RSAES_OAEP_SHA_256", REGION).ciphertext();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of("foo", "bar"), REGION,+ key.getKeyId(), "RSAES_OAEP_SHA_256"));++ assertEquals("ValidationException", ex.getErrorCode());+ assertEquals("EncryptionContext is not supported when encrypting/decrypting with asymmetric CMKs.",+ ex.getMessage());+ }++ @Test+ void decryptWithSignVerifyKeyThrowsInvalidKeyUsage() {+ KmsKey key = kmsService.createKey("sign key", "SIGN_VERIFY", "RSA_2048", null, Map.of(), REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(new byte[256], Map.of(), REGION,+ key.getKeyId(), "RSAES_OAEP_SHA_256"));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals(key.getArn() + " key usage is SIGN_VERIFY which is not valid for Decrypt.",+ ex.getMessage());+ }++ @Test+ void encryptEmptyPlaintextThrowsValidation() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ 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());+ }++ @Test+ void encryptOver4096BytesThrowsValidation() {+ KmsKey key = kmsService.createKey(null, REGION);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt(key.getKeyId(), new byte[4097], REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void encryptWithUnknownAlgorithmOnMissingKeyThrowsValidation() {+ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.encrypt("no-such-key", PLAINTEXT, Map.of(), "RSAES_OAEP_SHA_384", REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void decryptBlobWithMalformedPayloadThrowsInvalidCiphertext() {+ byte[] ciphertext = "kms:v2:some-key:0011223344556677::@@@".getBytes(StandardCharsets.UTF_8);++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.decryptAndResolveKey(ciphertext, Map.of(), REGION, null, null));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ }++ @Test+ void generateDataKeyWithRsaKeyThrowsInvalidKeyUsage() {+ KmsKey key = createRsaKey();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.generateDataKey(key.getKeyId(), "AES_256", 0, REGION));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals("Algorithm SYMMETRIC_DEFAULT is incompatible with key spec RSA_2048.", ex.getMessage());+ }++ @Test+ void generateDataKeyWithSignVerifyKeyThrowsInvalidKeyUsage() {+ 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));++ assertEquals("InvalidKeyUsageException", ex.getErrorCode());+ assertEquals(key.getArn() + " key usage is SIGN_VERIFY which is not valid for GenerateDataKey.",+ ex.getMessage());+ }+ }+@Nestedclass DecryptAndReEncryptTests {