Light, fluffy, and always free - The AWS Local Emulator alternative
feat(kms): support RSA imported key material (#4152)
Sergei Kesarev51b64851736b
diff --git a/docs/services/kms.md b/docs/services/kms.mdindex 41892c6fd6..293f38c4ef 100644--- a/docs/services/kms.md+++ b/docs/services/kms.md@@ -116,11 +116,17 @@ which puts the key in state `Enabled`. Wrapping material against the wrong key,different algorithm than the one requested, fails with `InvalidCiphertextException` the same wayit does on AWS.-Supported `WrappingAlgorithm` values are `RSAES_OAEP_SHA_256` and `RSAES_OAEP_SHA_1`, over-`WrappingKeySpec` `RSA_2048`, `RSA_3072` or `RSA_4096`. `RSAES_PKCS1_V1_5` is rejected, matching-AWS, which stopped supporting it on October 10, 2023. The `RSA_AES_KEY_WRAP_*` variants exist for-material longer than an RSA modulus can hold and are also rejected: no importable key spec here-carries more than 64 bytes.+Supported wrapping algorithms depend on the type of imported key material. Floci supports the+following combinations:++| Key material | Supported wrapping algorithm and spec |+| --- | --- |+| Symmetric encryption key (`SYMMETRIC_DEFAULT`) | **Wrapping algorithms:** `RSAES_OAEP_SHA_256`, `RSAES_OAEP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |+| HMAC key (`HMAC_*`) | **Wrapping algorithms:** `RSAES_OAEP_SHA_256`, `RSAES_OAEP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |+| Asymmetric RSA private key (`RSA_*`) | **Wrapping algorithms:** `RSA_AES_KEY_WRAP_SHA_256`, `RSA_AES_KEY_WRAP_SHA_1`<br>**Wrapping key specs:** `RSA_2048`, `RSA_3072`, `RSA_4096` |++The hybrid `RSA_AES_KEY_WRAP_*` algorithms require a 256-bit AES key. `RSAES_PKCS1_V1_5` is+rejected, matching AWS, which stopped supporting it on October 10, 2023.An import token is scoped to one key and spent by the import that uses it, and a second`GetParametersForImport` call invalidates the token the previous one returned. Tokens expire 24@@ -151,10 +157,8 @@ own the material and cannot rotate it.**Deviations:**-- `Origin=EXTERNAL` is supported only for `SYMMETRIC_DEFAULT` and the `HMAC_*` key specs, whose- material is a raw byte string. Real AWS KMS also imports asymmetric material as a DER-encoded- key pair; here an asymmetric spec with `Origin=EXTERNAL` is rejected at `CreateKey` with- `UnsupportedOperationException` rather than creating a key that could never sign or decrypt.+- `Origin=EXTERNAL` supports `SYMMETRIC_DEFAULT`, the `HMAC_*` key specs and the `RSA_*` key specs.+- Other asymmetric key specs are rejected at `CreateKey` with `UnsupportedOperationException`.- Holding several imported key materials on one symmetric key, which real KMS uses for on-demandrotation of imported material, is not emulated. `ImportType=NEW_KEY_MATERIAL` on a key thatalready has key material is rejected with `UnsupportedOperationException`, anddiff --git a/src/main/java/io/github/hectorvent/floci/services/kms/CipherUtils.java b/src/main/java/io/github/hectorvent/floci/services/kms/CipherUtils.javanew file mode 100644index 0000000000..d208d4c6dc--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/kms/CipherUtils.java@@ -0,0 +1,101 @@+package io.github.hectorvent.floci.services.kms;++import javax.crypto.Cipher;+import javax.crypto.SecretKey;+import javax.crypto.spec.OAEPParameterSpec;+import javax.crypto.spec.PSource;+import java.security.GeneralSecurityException;+import java.security.InvalidKeyException;+import java.security.Key;+import java.security.KeyFactory;+import java.security.PrivateKey;+import java.security.PublicKey;+import java.security.interfaces.RSAPrivateCrtKey;+import java.security.interfaces.RSAPrivateKey;+import java.security.spec.MGF1ParameterSpec;+import java.security.spec.PKCS8EncodedKeySpec;+import java.security.spec.RSAPublicKeySpec;+import java.util.Arrays;++public final class CipherUtils {+ private CipherUtils() {+ }++ /** Decodes a PKCS#8-encoded RSA private key. */+ public static PrivateKey generateRsaPrivateKey(byte[] encodedKey) throws GeneralSecurityException {+ return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(encodedKey));+ }++ /** Derives the public key from the modulus and public exponent of an RSA CRT private key. */+ public static PublicKey generateRsaPublicKey(RSAPrivateCrtKey privateKey) throws GeneralSecurityException {+ RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent());+ return KeyFactory.getInstance("RSA")+ .generatePublic(publicKeySpec);+ }++ public static byte[] encryptRsaOaep(PublicKey key, String digest, byte[] plaintext) throws GeneralSecurityException {+ return rsaOaepCipher(Cipher.ENCRYPT_MODE, key, digest)+ .doFinal(plaintext);+ }++ public static byte[] decryptRsaOaep(PrivateKey key, String digest, byte[] ciphertext) throws GeneralSecurityException {+ return rsaOaepCipher(Cipher.DECRYPT_MODE, key, digest)+ .doFinal(ciphertext);+ }++ /**+ * Unwraps key material encrypted with an {@code RSA_AES_KEY_WRAP_*} algorithm.+ *+ * <p>The input contains an RSA-OAEP-encrypted AES-256 wrapping key followed by key material+ * encrypted with that key using AES-KWP.+ *+ * @param wrappingKey RSA private key issued for import+ * @param digest digest used by RSA-OAEP+ * @param encryptedKeyMaterial encrypted key material payload+ * @return key material+ * @throws GeneralSecurityException if the wrapping key or key material cannot be unwrapped+ */+ public static byte[] unwrapRsaAes(PrivateKey wrappingKey, String digest, byte[] encryptedKeyMaterial) throws GeneralSecurityException {+ if (!(wrappingKey instanceof RSAPrivateKey rsaPrivateKey)) {+ throw new IllegalArgumentException("Wrapping key is not RSA private key.");+ }++ int wrappedAesKeyLength = (rsaPrivateKey.getModulus().bitLength() + 7) / 8;+ if (encryptedKeyMaterial.length <= wrappedAesKeyLength) {+ throw new IllegalArgumentException("Encrypted key material is too short.");+ }+ byte[] wrappedAesKey = Arrays.copyOfRange(encryptedKeyMaterial, 0, wrappedAesKeyLength);+ byte[] wrappedMaterial = Arrays.copyOfRange(encryptedKeyMaterial, wrappedAesKeyLength, encryptedKeyMaterial.length);++ SecretKey aesKey = (SecretKey) CipherUtils.rsaOaepUnwrapAesKey(rsaPrivateKey, digest, Cipher.SECRET_KEY, wrappedAesKey);+ byte[] aesKeyBytes = aesKey.getEncoded();+ if (aesKeyBytes == null || aesKeyBytes.length != 32) {+ throw new InvalidKeyException("RSA_AES_KEY_WRAP_* requires a 256-bit AES key.");+ }+ return CipherUtils.aesKwpDecrypt(aesKey, wrappedMaterial);+ }++ private static Key rsaOaepUnwrapAesKey(PrivateKey privateKey, String digest, int wrappedKeyType, byte[] wrappedKey) throws GeneralSecurityException {+ return rsaOaepCipher(Cipher.UNWRAP_MODE, privateKey, digest)+ .unwrap(wrappedKey, "AES", wrappedKeyType);+ }++ private static byte[] aesKwpDecrypt(SecretKey aesKey, byte[] wrappedMaterial) throws GeneralSecurityException {+ return aesKwpCipher(Cipher.DECRYPT_MODE, aesKey).doFinal(wrappedMaterial);+ }++ private static Cipher rsaOaepCipher(int mode, Key key, String digest) throws GeneralSecurityException {+ Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");+ OAEPParameterSpec parameterSpec = new OAEPParameterSpec(digest, "MGF1",+ new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT);++ cipher.init(mode, key, parameterSpec);+ return cipher;+ }++ private static Cipher aesKwpCipher(int mode, SecretKey aesKey) throws GeneralSecurityException {+ Cipher cipher = Cipher.getInstance("AES/KWP/NoPadding");+ cipher.init(mode, aesKey);+ return cipher;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java b/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.javaindex 197c297c8f..76c902bea4 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/KmsKeyImport.java@@ -1,18 +1,13 @@package io.github.hectorvent.floci.services.kms;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.kms.model.KmsKeySpec;import org.jboss.logging.Logger;-import javax.crypto.Cipher;-import javax.crypto.spec.OAEPParameterSpec;-import javax.crypto.spec.PSource;-import java.security.KeyFactory;import java.security.KeyPair;import java.security.KeyPairGenerator;import java.security.NoSuchAlgorithmException;import java.security.PrivateKey;-import java.security.spec.MGF1ParameterSpec;-import java.security.spec.PKCS8EncodedKeySpec;import java.util.Base64;/**@@ -31,6 +26,9 @@ final class KmsKeyImport {private static final String RSAES_PKCS1_V1_5 = "RSAES_PKCS1_V1_5";private static final String RSAES_OAEP_SHA_1 = "RSAES_OAEP_SHA_1";private static final String RSAES_OAEP_SHA_256 = "RSAES_OAEP_SHA_256";+ private static final String RSA_AES_KEY_WRAP_SHA_1 = "RSA_AES_KEY_WRAP_SHA_1";+ private static final String RSA_AES_KEY_WRAP_SHA_256 = "RSA_AES_KEY_WRAP_SHA_256";+ private static final String SM2PKE = "SM2PKE";private KmsKeyImport() {}@@ -73,19 +71,41 @@ final class KmsKeyImport {* refuse.** <p>RSAES_PKCS1_V1_5 stays in the modelled enum but AWS KMS stopped honouring it on- * October 10, 2023. The RSA_AES variants exist for material longer than an RSA modulus can- * hold; every spec that can be imported here carries at most 64 bytes.+ * October 10, 2023.*/- static void validateWrappingAlgorithm(String wrappingAlgorithm) {- switch (wrappingAlgorithm == null ? "" : wrappingAlgorithm) {- case RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256 -> { }+ static void validateWrappingAlgorithm(KmsKeySpec keySpec, String wrappingAlgorithm) {+ String algorithm = wrappingAlgorithm == null ? "" : wrappingAlgorithm;+ validateWrappingAlgorithmValue(algorithm, wrappingAlgorithm);++ switch (keySpec.getKeyType()) {+ case HMAC, SYMMETRIC -> {+ if (!RSAES_OAEP_SHA_1.equals(algorithm) && !RSAES_OAEP_SHA_256.equals(algorithm)) {+ throw new AwsException("UnsupportedOperationException",+ "WrappingAlgorithm " + wrappingAlgorithm + " is not supported for " + keySpec + " key. "+ + "Supported values are: RSAES_OAEP_SHA_1 and RSAES_OAEP_SHA_256.", 400);+ }+ }+ case RSA -> {+ if (!RSA_AES_KEY_WRAP_SHA_1.equals(algorithm) && !RSA_AES_KEY_WRAP_SHA_256.equals(algorithm)) {+ throw new AwsException("UnsupportedOperationException",+ "WrappingAlgorithm " + wrappingAlgorithm + " is not supported for " + keySpec + " key. "+ + "Supported values are: RSA_AES_KEY_WRAP_SHA_1 and RSA_AES_KEY_WRAP_SHA_256.", 400);+ }+ }+ default -> throw new AwsException("UnsupportedOperationException",+ "Importing key material for key spec " + keySpec + " is not supported.", 400);+ }+ }++ private static void validateWrappingAlgorithmValue(String algorithm, String wrappingAlgorithm) {+ switch (algorithm) {+ case RSAES_OAEP_SHA_1, RSAES_OAEP_SHA_256, RSA_AES_KEY_WRAP_SHA_1, RSA_AES_KEY_WRAP_SHA_256 -> { }+ case SM2PKE -> throw new AwsException("UnsupportedOperationException",+ "WrappingAlgorithm SM2PKE is not supported.", 400);case RSAES_PKCS1_V1_5 -> throw new AwsException("UnsupportedOperationException","AWS KMS stopped supporting the RSAES_PKCS1_V1_5 wrapping algorithm on October 10, 2023. "- + "Use RSAES_OAEP_SHA_256 or RSAES_OAEP_SHA_1.", 400);- case "RSA_AES_KEY_WRAP_SHA_1", "RSA_AES_KEY_WRAP_SHA_256", "SM2PKE" ->- throw new AwsException("UnsupportedOperationException",- "WrappingAlgorithm " + wrappingAlgorithm + " is not supported. Supported values are "- + "RSAES_OAEP_SHA_256 and RSAES_OAEP_SHA_1.", 400);+ + "Use RSA_AES_KEY_WRAP_SHA_1, RSA_AES_KEY_WRAP_SHA_256, "+ + "RSAES_OAEP_SHA_1 or RSAES_OAEP_SHA_256.", 400);default -> throw new AwsException("ValidationException","1 validation error detected: Value '" + wrappingAlgorithm + "' at 'wrappingAlgorithm' failed "+ "to satisfy constraint: Member must satisfy enum value set: "@@ -103,13 +123,18 @@ final class KmsKeyImport {*/static byte[] unwrap(String wrappingPrivateKeyEncoded, String wrappingAlgorithm, byte[] encryptedKeyMaterial) {try {- PrivateKey wrappingKey = KeyFactory.getInstance("RSA").generatePrivate(- new PKCS8EncodedKeySpec(Base64.getDecoder().decode(wrappingPrivateKeyEncoded)));- String digest = RSAES_OAEP_SHA_1.equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";- Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPPadding");- cipher.init(Cipher.DECRYPT_MODE, wrappingKey, new OAEPParameterSpec(digest, "MGF1",- new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT));- return cipher.doFinal(encryptedKeyMaterial);+ PrivateKey wrappingKey = CipherUtils.generateRsaPrivateKey(Base64.getDecoder().decode(wrappingPrivateKeyEncoded));++ return switch (wrappingAlgorithm) {+ case RSA_AES_KEY_WRAP_SHA_1 -> CipherUtils.unwrapRsaAes(wrappingKey, "SHA-1", encryptedKeyMaterial);+ case RSA_AES_KEY_WRAP_SHA_256 -> CipherUtils.unwrapRsaAes(wrappingKey, "SHA-256", encryptedKeyMaterial);+ case RSAES_OAEP_SHA_1 -> CipherUtils.decryptRsaOaep(wrappingKey, "SHA-1", encryptedKeyMaterial);+ case RSAES_OAEP_SHA_256 -> CipherUtils.decryptRsaOaep(wrappingKey, "SHA-256", encryptedKeyMaterial);+ default -> throw new AwsException("UnsupportedOperationException",+ "WrappingAlgorithm " + wrappingAlgorithm + " is not supported. Supported values are "+ + "RSA_AES_KEY_WRAP_SHA_1, RSA_AES_KEY_WRAP_SHA_256, RSAES_OAEP_SHA_1 and RSAES_OAEP_SHA_256.", 400);++ };} catch (Exception e) {LOG.debugv(e, "Unwrapping imported key material failed for wrapping algorithm {0}", wrappingAlgorithm);throw new AwsException("InvalidCiphertextException", null, 400);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 11acdb8ece..bbbfa8d439 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@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.kms.keytype.KmsKeyType;import io.github.hectorvent.floci.services.kms.keytype.KmsKeyTypes;import io.github.hectorvent.floci.services.kms.model.KmsAlias;import io.github.hectorvent.floci.services.kms.model.KmsGrant;@@ -866,7 +867,7 @@ public class KmsService implements ResourceProvider {KmsKey key = resolveKey(keyId, region);requireExternalOrigin(key);requireNotPendingDeletion(key);- KmsKeyImport.validateWrappingAlgorithm(wrappingAlgorithm);+ KmsKeyImport.validateWrappingAlgorithm(key.getKeySpec(), wrappingAlgorithm);KmsKeyImport.WrappingKeyPair wrappingKeyPair = KmsKeyImport.generateWrappingKeyPair(wrappingKeySpec);KmsImportParameters parameters = new KmsImportParameters();@@ -903,11 +904,12 @@ public class KmsService implements ResourceProvider {byte[] material = KmsKeyImport.unwrap(parameters.getWrappingPrivateKeyEncoded(),parameters.getWrappingAlgorithm(), encryptedKeyMaterial);- validateMaterialLength(key, material);String keyMaterialId = keyMaterialId(key.getKeyId(), material);requireSameMaterialAsFirstImport(key, keyMaterialId);- key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));+ KmsKeyType keyType = keyTypes.of(key.getKeySpec());+ keyType.importKeyMaterial(key, material);+if (KmsKeySpec.SYMMETRIC_DEFAULT == key.getKeySpec()) {installImportedBackingKey(key, keyMaterialId, material);}@@ -1081,15 +1083,6 @@ public class KmsService implements ResourceProvider {}}- private static void validateMaterialLength(KmsKey key, byte[] material) {- int expected = key.getKeySpec().materialByteLength();- if (material.length != expected) {- throw new AwsException("IncorrectKeyMaterialException",- "Key material for key spec " + key.getKeySpec() + " must be " + expected- + " bytes but was " + material.length + " bytes.", 400);- }- }-private static void requireSameMaterialAsFirstImport(KmsKey key, String keyMaterialId) {if (key.getKeyMaterialId() != null && !key.getKeyMaterialId().equals(keyMaterialId)) {throw new AwsException("IncorrectKeyMaterialException",@@ -1129,14 +1122,15 @@ public class KmsService implements ResourceProvider {}/**- * Imported material here is a raw byte string, which covers SYMMETRIC_DEFAULT and the HMAC- * specs. Real KMS also imports asymmetric material as a DER key pair; refusing it outright- * beats accepting a key that could never sign or decrypt anything.+ * Allows imports for symmetric, HMAC and RSA key specs. Other key specs are not supported.*/private static String requireImportableSpec(KmsKeySpec spec) {- if (spec != KmsKeySpec.SYMMETRIC_DEFAULT && spec.getKeyType() != KmsKeySpec.KeyType.HMAC) {+ if (spec != KmsKeySpec.SYMMETRIC_DEFAULT+ && spec.getKeyType() != KmsKeySpec.KeyType.HMAC+ && spec.getKeyType() != KmsKeySpec.KeyType.RSA) {+throw new AwsException("UnsupportedOperationException",- "Origin EXTERNAL is only supported for SYMMETRIC_DEFAULT and HMAC key specs, not "+ "Origin EXTERNAL is only supported for SYMMETRIC_DEFAULT, HMAC and RSA key specs, not "+ spec + ".", 400);}return EXTERNAL_ORIGIN;diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/HmacKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/HmacKeyType.javaindex ca6029acf8..7226e49f33 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/HmacKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/HmacKeyType.java@@ -43,4 +43,19 @@ final class HmacKeyType implements KmsKeyType {default -> throw new AwsException("InvalidMacAlgorithmException", "Unsupported MAC algorithm: " + awsAlgo, 400);};}++ @Override+ public void importKeyMaterial(KmsKey key, byte[] material) {+ validateKeyMaterialLength(key, material);+ key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));+ }++ private static void validateKeyMaterialLength(KmsKey key, byte[] material) {+ int expected = key.getKeySpec().materialByteLength();+ if (material.length != expected) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Key material for key spec " + key.getKeySpec() + " must be " + expected+ + " bytes but was " + material.length + " bytes.", 400);+ }+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.javaindex 77c321e069..58d62a38bf 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/KmsKeyType.java@@ -31,4 +31,14 @@ public interface KmsKeyType {default byte[] generateMac(KmsKey key, byte[] message, String algorithm) throws GeneralSecurityException {throw new IllegalStateException(key.getKeySpec() + " does not generate MACs");}++ /**+ * Validates and stores imported key material for the specified KMS key.+ *+ * @param key target KMS key+ * @param material key material after transport wrapping has been removed+ */+ default void importKeyMaterial(KmsKey key, byte[] material) {+ throw new IllegalStateException(key.getKeySpec() + " does not import key material");+ }}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.javaindex 53e971880a..28a081bbf5 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/RsaKeyType.java@@ -1,6 +1,7 @@package io.github.hectorvent.floci.services.kms.keytype;import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.kms.CipherUtils;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;@@ -29,7 +30,9 @@ import java.security.KeyPairGenerator;import java.security.PrivateKey;import java.security.PublicKey;import java.security.SecureRandom;+import java.security.interfaces.RSAPrivateCrtKey;import java.security.spec.MGF1ParameterSpec;+import java.util.Base64;import static io.github.hectorvent.floci.services.kms.model.KmsMessageType.RAW;@@ -87,6 +90,52 @@ final class RsaKeyType implements KmsKeyType {return oaep(Cipher.DECRYPT_MODE, key, algorithm, ciphertext);}+ @Override+ public void importKeyMaterial(KmsKey key, byte[] material) {+ PrivateKey privateKey = parsePrivateKey(material);++ if (!(privateKey instanceof RSAPrivateCrtKey rsaPrivateKey)) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Imported RSA key material must be a PKCS#8-encoded two-prime RSA private key.", 400);+ }++ requireExpectedModulusSize(key.getKeySpec(), rsaPrivateKey);++ PublicKey publicKey = generatePublicKey(rsaPrivateKey);++ Base64.Encoder encoder = Base64.getEncoder();+ key.setPrivateKeyEncoded(encoder.encodeToString(material));+ key.setPublicKeyEncoded(encoder.encodeToString(publicKey.getEncoded()));+ }++ private static PrivateKey parsePrivateKey(byte[] material) {+ try {+ return CipherUtils.generateRsaPrivateKey(material);+ } catch (GeneralSecurityException e) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Imported RSA key material is not a valid PKCS#8 RSA private key.", 400);+ }+ }++ private static PublicKey generatePublicKey(RSAPrivateCrtKey privateKey) {+ try {+ return CipherUtils.generateRsaPublicKey(privateKey);+ } catch (GeneralSecurityException e) {+ throw new AwsException("InternalFailure",+ "Failed to derive RSA public key: " + e.getMessage(), 500);+ }+ }++ private static void requireExpectedModulusSize(KmsKeySpec spec, RSAPrivateCrtKey privateKey) {+ int expectedBits = keySize(spec);+ int actualBits = privateKey.getModulus().bitLength();+ if (actualBits != expectedBits) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Key material for key spec " + spec + " must have a " + expectedBits+ + "-bit RSA modulus but was " + actualBits + " bits.", 400);+ }+ }+private static int keySize(KmsKeySpec spec) {return Integer.parseInt(spec.name().substring("RSA_".length()));}diff --git a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/SymmetricKeyType.java b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/SymmetricKeyType.javaindex 5938fb870f..765ee8fa3d 100644--- a/src/main/java/io/github/hectorvent/floci/services/kms/keytype/SymmetricKeyType.java+++ b/src/main/java/io/github/hectorvent/floci/services/kms/keytype/SymmetricKeyType.java@@ -1,5 +1,6 @@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;@@ -31,4 +32,19 @@ public final class SymmetricKeyType implements KmsKeyType {key.getBackingKeys().put(backingKeyId, Base64.getEncoder().encodeToString(material));key.setCurrentBackingKeyId(backingKeyId);}++ @Override+ public void importKeyMaterial(KmsKey key, byte[] material) {+ validateKeyMaterialLength(key, material);+ key.setPrivateKeyEncoded(Base64.getEncoder().encodeToString(material));+ }++ private static void validateKeyMaterialLength(KmsKey key, byte[] material) {+ int expected = key.getKeySpec().materialByteLength();+ if (material.length != expected) {+ throw new AwsException("IncorrectKeyMaterialException",+ "Key material for key spec " + key.getKeySpec() + " must be " + expected+ + " bytes but was " + material.length + " bytes.", 400);+ }+ }}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 4c03c93eb5..418104c775 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@@ -11,8 +11,11 @@ import org.junit.jupiter.params.provider.CsvSource;import javax.crypto.Cipher;import javax.crypto.spec.OAEPParameterSpec;import javax.crypto.spec.PSource;+import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;import java.security.KeyFactory;+import java.security.KeyPair;+import java.security.KeyPairGenerator;import java.security.PublicKey;import java.security.spec.MGF1ParameterSpec;import java.security.spec.X509EncodedKeySpec;@@ -3006,15 +3009,59 @@ class KmsIntegrationTest {}@Test- void importIsRejectedForAnAsymmetricKeySpec() {- given()+ void rsaImportRoundTripDerivesThePublicKey() throws Exception {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");+ generator.initialize(2048);+ KeyPair importedKeyPair = generator.generateKeyPair();++ String keyId = given().header("X-Amz-Target", "TrentService.CreateKey").contentType(KMS_CONTENT_TYPE)- .body("{\"Origin\":\"EXTERNAL\",\"KeyUsage\":\"ENCRYPT_DECRYPT\",\"KeySpec\":\"RSA_2048\"}")+ .body("{\"Origin\":\"EXTERNAL\",\"KeyUsage\":\"SIGN_VERIFY\",\"KeySpec\":\"RSA_2048\"}").when().post("/").then()- .statusCode(400)- .body("__type", equalTo("UnsupportedOperationException"));+ .statusCode(200)+ .body("KeyMetadata.KeyState", equalTo("PendingImport"))+ .extract().path("KeyMetadata.KeyId");++ var parameters = given()+ .header("X-Amz-Target", "TrentService.GetParametersForImport")+ .contentType(KMS_CONTENT_TYPE)+ .body(("{\"KeyId\":\"%s\",\"WrappingAlgorithm\":\"RSA_AES_KEY_WRAP_SHA_256\","+ + "\"WrappingKeySpec\":\"RSA_2048\"}").formatted(keyId))+ .when().post("/")+ .then()+ .statusCode(200)+ .extract().jsonPath();++ String wrapped = Base64.getEncoder().encodeToString(wrapWithRsaAesSha256(+ parameters.getString("PublicKey"), importedKeyPair.getPrivate().getEncoded()));+ given()+ .header("X-Amz-Target", "TrentService.ImportKeyMaterial")+ .contentType(KMS_CONTENT_TYPE)+ .body(("{\"KeyId\":\"%s\",\"ImportToken\":\"%s\",\"EncryptedKeyMaterial\":\"%s\","+ + "\"ExpirationModel\":\"KEY_MATERIAL_DOES_NOT_EXPIRE\"}")+ .formatted(keyId, parameters.getString("ImportToken"), wrapped))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeyMaterialId", matchesPattern("[a-f0-9]{64}"));++ String publicKey = given()+ .header("X-Amz-Target", "TrentService.GetPublicKey")+ .contentType(KMS_CONTENT_TYPE)+ .body("{\"KeyId\":\"%s\"}".formatted(keyId))+ .when().post("/")+ .then()+ .statusCode(200)+ .body("KeySpec", equalTo("RSA_2048"))+ .body("KeyUsage", equalTo("SIGN_VERIFY"))+ .extract().path("PublicKey");++ assertEquals(Base64.getEncoder().encodeToString(importedKeyPair.getPublic().getEncoded()), publicKey);+ describeKey(keyId)+ .body("KeyMetadata.KeyState", equalTo("Enabled"))+ .body("KeyMetadata.Enabled", equalTo(true));}@Test@@ -3088,4 +3135,17 @@ class KmsIntegrationTest {new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT));return cipher.doFinal(material);}++ private static byte[] wrapWithRsaAesSha256(String publicKeyEncoded, byte[] material) throws Exception {+ byte[] aesKeyBytes = new byte[32];+ Arrays.fill(aesKeyBytes, (byte) 23);+ Cipher aesKwp = Cipher.getInstance("AES/KWP/NoPadding");+ aesKwp.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKeyBytes, "AES"));+ byte[] wrappedMaterial = aesKwp.doFinal(material);+ byte[] wrappedAesKey = wrapWithRsaOaepSha256(publicKeyEncoded, aesKeyBytes);++ byte[] payload = Arrays.copyOf(wrappedAesKey, wrappedAesKey.length + wrappedMaterial.length);+ System.arraycopy(wrappedMaterial, 0, payload, wrappedAesKey.length, wrappedMaterial.length);+ return payload;+ }}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 bffde6f1ff..5f50f9cc83 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@@ -27,10 +27,12 @@ import javax.crypto.spec.OAEPParameterSpec;import javax.crypto.spec.PSource;import javax.crypto.spec.SecretKeySpec;import java.nio.charset.StandardCharsets;-import java.security.Security;import java.security.KeyFactory;+import java.security.KeyPair;+import java.security.KeyPairGenerator;import java.security.MessageDigest;import java.security.PublicKey;+import java.security.Security;import java.security.Signature;import java.security.spec.MGF1ParameterSpec;import java.security.spec.PSSParameterSpec;@@ -2408,6 +2410,8 @@ class KmsServiceTest {class ImportedKeyMaterial {private static final String OAEP_SHA_256 = "RSAES_OAEP_SHA_256";+ private static final String RSA_AES_SHA_1 = "RSA_AES_KEY_WRAP_SHA_1";+ private static final String RSA_AES_SHA_256 = "RSA_AES_KEY_WRAP_SHA_256";private KmsKey externalKey(String keySpec, String keyUsage) {return kmsService.createKey("external", keyUsage, keySpec, null, Map.of(), "EXTERNAL", REGION);@@ -2424,7 +2428,7 @@ class KmsServiceTest {}/** Wraps material the way a caller would, with the public key GetParametersForImport returned. */- private byte[] wrap(String publicKeyEncoded, String wrappingAlgorithm, byte[] material) throws Exception {+ private byte[] wrapOAEP(String publicKeyEncoded, String wrappingAlgorithm, byte[] material) throws Exception {PublicKey wrappingKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));String digest = "RSAES_OAEP_SHA_1".equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";@@ -2434,11 +2438,46 @@ class KmsServiceTest {return cipher.doFinal(material);}+ private byte[] wrapRsaAes(String publicKeyEncoded, String wrappingAlgorithm, byte[] material,+ byte[] aesKeyBytes) throws Exception {+ SecretKeySpec aesKey = new SecretKeySpec(aesKeyBytes, "AES");+ Cipher aesKwp = Cipher.getInstance("AES/KWP/NoPadding");+ aesKwp.init(Cipher.ENCRYPT_MODE, aesKey);+ byte[] wrappedMaterial = aesKwp.doFinal(material);++ PublicKey wrappingKey = KeyFactory.getInstance("RSA")+ .generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyEncoded)));+ String digest = RSA_AES_SHA_1.equals(wrappingAlgorithm) ? "SHA-1" : "SHA-256";+ Cipher rsaOaep = Cipher.getInstance("RSA/ECB/OAEPPadding");+ rsaOaep.init(Cipher.ENCRYPT_MODE, wrappingKey, new OAEPParameterSpec(digest, "MGF1",+ new MGF1ParameterSpec(digest), PSource.PSpecified.DEFAULT));+ byte[] wrappedAesKey = rsaOaep.doFinal(aesKeyBytes);++ byte[] payload = Arrays.copyOf(wrappedAesKey, wrappedAesKey.length + wrappedMaterial.length);+ System.arraycopy(wrappedMaterial, 0, payload, wrappedAesKey.length, wrappedMaterial.length);+ return payload;+ }++ private KeyPair rsaKeyPair(String keySpec) throws Exception {+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");+ generator.initialize(Integer.parseInt(keySpec.substring("RSA_".length())));+ return generator.generateKeyPair();+ }+private KmsKey importInto(KmsKey key, byte[] rawMaterial, String wrappingAlgorithm) throws Exception {+ return importInto(key, rawMaterial, wrappingAlgorithm, "RSA_2048");+ }++ private KmsKey importInto(KmsKey key, byte[] rawMaterial, String wrappingAlgorithm,+ String wrappingKeySpec) throws Exception {KmsService.ImportParameters parameters =- kmsService.getParametersForImport(key.getKeyId(), wrappingAlgorithm, "RSA_2048", REGION);+ kmsService.getParametersForImport(key.getKeyId(), wrappingAlgorithm, wrappingKeySpec, REGION);+ byte[] wrappedMaterial = wrappingAlgorithm.startsWith("RSA_AES_KEY_WRAP_")+ ? wrapRsaAes(parameters.publicKeyEncoded(), wrappingAlgorithm, rawMaterial,+ material(32, (byte) 91))+ : wrapOAEP(parameters.publicKeyEncoded(), wrappingAlgorithm, rawMaterial);return kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(),- wrap(parameters.publicKeyEncoded(), wrappingAlgorithm, rawMaterial),+ wrappedMaterial,"KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);}@@ -2501,7 +2540,7 @@ class KmsServiceTest {kmsService.getParametersForImport(otherKey.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);KmsService.ImportParameters own =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrongly = wrap(foreign.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrongly = wrapOAEP(foreign.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String token = own.importToken();@@ -2521,13 +2560,23 @@ class KmsServiceTest {assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());}+ @Test+ void hmacMaterialOfTheWrongLengthIsRejected() {+ KmsKey key = externalKey("HMAC_256", "GENERATE_VERIFY_MAC");++ AwsException ex = assertThrows(AwsException.class, () ->+ importInto(key, material(16, (byte) 1), OAEP_SHA_256));++ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ }+@Testvoid aSupersededImportTokenIsRejected() throws Exception {KmsKey key = externalSymmetricKey();KmsService.ImportParameters first =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(first.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrapped = wrapOAEP(first.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String staleToken = first.importToken();@@ -2551,7 +2600,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 3));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 3));kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,"KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION);@@ -2571,7 +2620,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 9));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 9));kmsService.importKeyMaterial(key.getKeyId(), parameters.importToken(), wrapped,"KEY_MATERIAL_EXPIRES", Instant.now().getEpochSecond() + 3600, null, REGION);@@ -2592,7 +2641,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2607,7 +2656,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2648,7 +2697,7 @@ class KmsServiceTest {importInto(key, material(32, (byte) 5), OAEP_SHA_256);KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2662,7 +2711,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2676,7 +2725,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 6));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2702,7 +2751,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2716,7 +2765,7 @@ class KmsServiceTest {KmsKey key = externalSymmetricKey();KmsService.ImportParameters parameters =kmsService.getParametersForImport(key.getKeyId(), OAEP_SHA_256, "RSA_2048", REGION);- byte[] wrapped = wrap(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));+ byte[] wrapped = wrapOAEP(parameters.publicKeyEncoded(), OAEP_SHA_256, material(32, (byte) 1));String keyId = key.getKeyId();String token = parameters.importToken();@@ -2843,10 +2892,62 @@ class KmsServiceTest {assertNull(deleted.getKeyMaterialId());}+ @ParameterizedTest+ @CsvSource({+ "RSA_2048, RSA_AES_KEY_WRAP_SHA_1, RSA_2048",+ "RSA_3072, RSA_AES_KEY_WRAP_SHA_256, RSA_3072",+ "RSA_4096, RSA_AES_KEY_WRAP_SHA_256, RSA_4096"+ })+ void supportedRsaKeyAndWrappingSpecsImportUsablePrivateKeyMaterial(+ String keySpec, String wrappingAlgorithm, String wrappingKeySpec) throws Exception {+ KmsKey key = externalKey(keySpec, "SIGN_VERIFY");+ KeyPair importedKeyPair = rsaKeyPair(keySpec);++ KmsKey imported = importInto(key, importedKeyPair.getPrivate().getEncoded(),+ wrappingAlgorithm, wrappingKeySpec);++ assertEquals("Enabled", imported.getKeyState());+ assertTrue(imported.isEnabled());+ assertArrayEquals(importedKeyPair.getPublic().getEncoded(),+ Base64.getDecoder().decode(imported.getPublicKeyEncoded()));++ byte[] message = "imported RSA key".getBytes(StandardCharsets.UTF_8);+ byte[] signature = kmsService.sign(key.getKeyId(), message,+ "RSASSA_PKCS1_V1_5_SHA_256", REGION);+ Signature verifier = Signature.getInstance("SHA256withRSA");+ verifier.initVerify(importedKeyPair.getPublic());+ verifier.update(message);+ assertTrue(verifier.verify(signature));+ }+@Test- void asymmetricKeySpecsCannotUseExternalOrigin() {+ void rsaImportRejectsAModulusThatDoesNotMatchTheKeySpec() throws Exception {+ KmsKey key = externalKey("RSA_2048", "SIGN_VERIFY");+ byte[] rsa3072Material = rsaKeyPair("RSA_3072").getPrivate().getEncoded();+AwsException ex = assertThrows(AwsException.class, () ->- externalKey("RSA_2048", "ENCRYPT_DECRYPT"));+ importInto(key, rsa3072Material, RSA_AES_SHA_256));++ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());+ }++ @Test+ void rsaImportRejectsInvalidPkcs8Material() {+ KmsKey key = externalKey("RSA_2048", "SIGN_VERIFY");++ AwsException ex = assertThrows(AwsException.class, () ->+ importInto(key, material(32, (byte) 7), RSA_AES_SHA_256));++ assertEquals("IncorrectKeyMaterialException", ex.getErrorCode());+ assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());+ }++ @Test+ void nonRsaAsymmetricKeySpecsCannotUseExternalOrigin() {+ AwsException ex = assertThrows(AwsException.class, () ->+ externalKey("ECC_NIST_P256", "SIGN_VERIFY"));+assertEquals("UnsupportedOperationException", ex.getErrorCode());}@@ -2871,14 +2972,51 @@ class KmsServiceTest {}@Test- void anUnsupportedWrappingAlgorithmIsRejectedBeforeParametersAreIssued() {+ void asymmetricKeyRejectsRsaAesWrappingBeforeParametersAreIssued() {String keyId = externalSymmetricKey().getKeyId();AwsException ex = assertThrows(AwsException.class, () ->- kmsService.getParametersForImport(keyId, "RSA_AES_KEY_WRAP_SHA_256", "RSA_2048", REGION));+ kmsService.getParametersForImport(keyId, RSA_AES_SHA_256, "RSA_2048", REGION));assertEquals("UnsupportedOperationException", ex.getErrorCode());}+ @Test+ void rsaKeyRejectsDirectRsaOaepWrappingBeforeParametersAreIssued() {+ String keyId = externalKey("RSA_2048", "ENCRYPT_DECRYPT").getKeyId();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.getParametersForImport(keyId, OAEP_SHA_256, "RSA_2048", REGION));++ assertEquals("UnsupportedOperationException", ex.getErrorCode());+ }++ @Test+ void unmodelledWrappingAlgorithmIsAValidationError() {+ String keyId = externalSymmetricKey().getKeyId();++ AwsException ex = assertThrows(AwsException.class, () ->+ kmsService.getParametersForImport(keyId, "NOT_AN_ALGORITHM", "RSA_2048", REGION));++ assertEquals("ValidationException", ex.getErrorCode());+ }++ @Test+ void rsaAesWrappingRejectsANon256BitAesKey() throws Exception {+ KmsKey key = externalKey("RSA_2048", "SIGN_VERIFY");+ KmsService.ImportParameters parameters = kmsService.getParametersForImport(+ key.getKeyId(), RSA_AES_SHA_256, "RSA_2048", REGION);+ byte[] rsaMaterial = rsaKeyPair("RSA_2048").getPrivate().getEncoded();+ byte[] wrapped = wrapRsaAes(parameters.publicKeyEncoded(), RSA_AES_SHA_256, rsaMaterial,+ material(16, (byte) 17));++ AwsException ex = assertThrows(AwsException.class, () -> kmsService.importKeyMaterial(+ key.getKeyId(), parameters.importToken(), wrapped,+ "KEY_MATERIAL_DOES_NOT_EXPIRE", null, null, REGION));++ assertEquals("InvalidCiphertextException", ex.getErrorCode());+ assertEquals("PendingImport", kmsService.describeKey(key.getKeyId(), REGION).getKeyState());+ }+@Testvoid aSymmetricKeyEncryptsWithTheMaterialThatWasImported() throws Exception {KmsKey key = externalSymmetricKey();