mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(paymentcryptography): the key exchange, with TR-31, RSA-OAEP and ECDH (#7862)
This commit is contained in:
1 parent
f2a0bfce4e
commit
77d73ee4b7
32 files changed
+5863
-129
No files matched your search
+16
@@ -146,6 +146,22 @@ class PaymentCryptographyAuthCryptogramOperationsTest {
|
||||
"4111111111111111111", PSN)), HEX.formatHex(optionB));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestWithoutItsDerivationAttributesIsRefusedByTheModel() {
|
||||
// The shape check settles the members the model requires, so it is the refusal that
|
||||
// answers, and the message a caller sees is its own.
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
|
||||
"KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/"
|
||||
+ "0123456789abcdef",
|
||||
"TransactionData", TRANSACTION_DATA,
|
||||
"MajorKeyDerivationMode", "EMV_OPTION_A")), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("failed to satisfy constraint"), refused.getMessage());
|
||||
assertTrue(refused.getMessage().contains("SessionKeyDerivationAttributes"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEmv41DerivationIsRefusedRatherThanApproximated() {
|
||||
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
|
||||
|
||||
+332
-8
@@ -65,6 +65,12 @@ class PaymentCryptographyIntegrationTest {
|
||||
"KeyModesOfUse":{"Encrypt":true,"Decrypt":true}},
|
||||
"Exportable":true}""";
|
||||
|
||||
private static final String CREATE_KEY_PAIR = """
|
||||
{"KeyAttributes":{"KeyAlgorithm":"RSA_2048","KeyClass":"ASYMMETRIC_KEY_PAIR",
|
||||
"KeyUsage":"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
|
||||
"KeyModesOfUse":{"Sign":true,"Verify":true}},
|
||||
"Exportable":true}""";
|
||||
|
||||
@Test
|
||||
void aKeyIsCreatedAndReadBack() {
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
@@ -101,6 +107,276 @@ class PaymentCryptographyIntegrationTest {
|
||||
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInitialKeyLeavesUnderTheBaseKeyItIsDerivedFrom() {
|
||||
// The export names the key that leaves and the attributes that say which key of it
|
||||
// leaves: the initial key is derived from the base key and is not the base key.
|
||||
// The base derivation key is a double-length Triple DES key, which is what the
|
||||
// derivation is defined over.
|
||||
String base = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
|
||||
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_B0_BASE_DERIVATION_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"DeriveKey\":true}},"
|
||||
+ "\"Exportable\":true}")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
String protection = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
|
||||
+ "\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_K1_KEY_BLOCK_PROTECTION_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Wrap\":true,\"Unwrap\":true}},"
|
||||
+ "\"Exportable\":true}")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
call("ExportKey", """
|
||||
{"ExportKeyIdentifier":"%s",
|
||||
"ExportAttributes":{"ExportDukptInitialKey":
|
||||
{"KeySerialNumber":"12345678900000000001"}},
|
||||
"KeyMaterial":{"Tr31KeyBlock":{"WrappingKeyIdentifier":"%s"}}}
|
||||
""".formatted(base, protection))
|
||||
.then().statusCode(200)
|
||||
.body("WrappedKey.WrappedKeyMaterialFormat", equalTo("TR31_KEY_BLOCK"))
|
||||
.body("WrappedKey.WrappingKeyArn", equalTo(protection));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theImportParametersAreServedOverTheWire() {
|
||||
call("GetParametersForImport", """
|
||||
{"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"}
|
||||
""")
|
||||
.then().statusCode(200)
|
||||
.body("ImportToken", matchesPattern("import-token-[0-9a-zA-Z]{16,64}"))
|
||||
.body("WrappingKeyAlgorithm", equalTo("RSA_2048"))
|
||||
.body("WrappingKeyCertificate", notNullValue())
|
||||
.body("WrappingKeyCertificateChain", notNullValue())
|
||||
.body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theParametersCanBeReusedOverTheWire() {
|
||||
// A caller that asks for the last parameters gets them, token and certificate alike.
|
||||
String first = call("GetParametersForImport", """
|
||||
{"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"}
|
||||
""")
|
||||
.then().statusCode(200)
|
||||
.extract().path("ImportToken");
|
||||
|
||||
call("GetParametersForImport", """
|
||||
{"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048",
|
||||
"ReuseLastGeneratedToken":true}
|
||||
""")
|
||||
.then().statusCode(200)
|
||||
.body("ImportToken", equalTo(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExportParametersAreServedOverTheWire() {
|
||||
call("GetParametersForExport", """
|
||||
{"KeyMaterialType":"TR34_KEY_BLOCK","SigningKeyAlgorithm":"RSA_2048"}
|
||||
""")
|
||||
.then().statusCode(200)
|
||||
.body("ExportToken", matchesPattern("export-token-[0-9a-zA-Z]{16,64}"))
|
||||
.body("SigningKeyAlgorithm", equalTo("RSA_2048"))
|
||||
.body("SigningKeyCertificate", notNullValue())
|
||||
.body("SigningKeyCertificateChain", notNullValue())
|
||||
.body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedKeyCarriesTheEnabledFlagAndTheTags() {
|
||||
// The import names the key's state and its tags, and the key comes back that way.
|
||||
String wrapping = call("CreateKey", """
|
||||
{"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY",
|
||||
"KeyUsage":"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
|
||||
"KeyModesOfUse":{"Wrap":true,"Unwrap":true}},
|
||||
"Exportable":true}
|
||||
""")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
String block = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn
|
||||
+ "\",\"KeyMaterial\":{\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\""
|
||||
+ wrapping + "\"}}}")
|
||||
.then().statusCode(200)
|
||||
.extract().path("WrappedKey.KeyMaterial");
|
||||
|
||||
String importedArn = call("ImportKey", "{\"KeyMaterial\":{\"Tr31KeyBlock\":{"
|
||||
+ "\"WrappingKeyIdentifier\":\"" + wrapping + "\",\"WrappedKeyBlock\":\"" + block
|
||||
+ "\"}},\"Enabled\":false,\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}")
|
||||
.then().statusCode(200)
|
||||
.body("Key.Enabled", equalTo(false))
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
// The key's answer carries no tags, so they are read the way they are read elsewhere.
|
||||
call("ListTagsForResource", "{\"ResourceArn\":\"" + importedArn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("Tags[0].Key", equalTo("Origin"))
|
||||
.body("Tags[0].Value", equalTo("PRIMARY"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNamingTwoFormsIsRefused() {
|
||||
// The union holds one form per request, and naming two is not naming one.
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
|
||||
+ "\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\"" + arn + "\"},"
|
||||
+ "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn
|
||||
+ "\",\"WrappingKeyCertificate\":\"x\"}}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNamingAFormTheServiceDoesNotServeIsRefused() {
|
||||
// The TR-34 form is one the model has and this service does not make.
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
|
||||
+ "\"Tr34KeyBlock\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn
|
||||
+ "\",\"WrappingKeyCertificate\":\"x\",\"KeyBlockFormat\":\"X9_TR34_2012\"}}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", containsString("not a form the service exports"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape check settles the members the model requires, so a request missing one is
|
||||
* refused by it, before the operation does any work. The refusal a caller sees is
|
||||
* therefore the shape check's, and the service does not repeat the check.
|
||||
*/
|
||||
@Test
|
||||
void theModelCheckRefusesAnExportWithoutAWrappingKeyCertificate() {
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
|
||||
+ "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "WrappingKeyCertificate");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnImportWithoutItsKeyAttributes() {
|
||||
Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
|
||||
+ "\"Exportable\":true,"
|
||||
+ "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\","
|
||||
+ "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "KeyAttributes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnImportWhoseKeyAttributesHaveNoUsage() {
|
||||
Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
|
||||
+ "\"Exportable\":true,"
|
||||
+ "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\","
|
||||
+ "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\","
|
||||
+ "\"KeyAttributes\":{\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyAlgorithm\":\"AES_128\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}}}}");
|
||||
|
||||
assertTheModelRefused(answer, "KeyUsage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnImportOfAPublicKeyWithoutItsKeyAttributes() {
|
||||
Response answer = call("ImportKey", "{\"KeyMaterial\":{\"RootCertificatePublicKey\":{"
|
||||
+ "\"PublicKeyCertificate\":\"a certificate\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "KeyAttributes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnExportWithoutItsCertificateAuthorityPublicKeyIdentifier() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"KeyCryptogram\":{\"WrappingKeyCertificate\":\"a certificate\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "CertificateAuthorityPublicKeyIdentifier");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnImportWhoseCryptogramIsNotHexadecimal() {
|
||||
Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
|
||||
+ "\"Exportable\":true,"
|
||||
+ "\"WrappedKeyCryptogram\":\"not hexadecimal at all\","
|
||||
+ "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\","
|
||||
+ "\"KeyAttributes\":" + keyAttributes() + "}}}");
|
||||
|
||||
assertTheModelRefused(answer, "WrappedKeyCryptogram");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesACryptogramWithAWrappingSpecItDoesNotName() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"KeyCryptogram\":{"
|
||||
+ "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"WrappingKeyCertificate\":\"a certificate\","
|
||||
+ "\"WrappingSpec\":\"RSA_OAEP_SHA_1\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "WrappingSpec");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnAgreementWithADerivationFunctionItDoesNotName() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{"
|
||||
+ "\"PrivateKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"PublicKeyCertificate\":\"a certificate\","
|
||||
+ "\"DeriveKeyAlgorithm\":\"AES_128\","
|
||||
+ "\"KeyDerivationFunction\":\"NIST_SP800_X\","
|
||||
+ "\"KeyDerivationHashAlgorithm\":\"SHA_256\","
|
||||
+ "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}");
|
||||
|
||||
assertTheModelRefused(answer, "KeyDerivationFunction");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnAgreementWithADerivationHashItDoesNotName() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{"
|
||||
+ "\"PrivateKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"PublicKeyCertificate\":\"a certificate\","
|
||||
+ "\"DeriveKeyAlgorithm\":\"AES_128\","
|
||||
+ "\"KeyDerivationFunction\":\"NIST_SP800\","
|
||||
+ "\"KeyDerivationHashAlgorithm\":\"SHA_224\","
|
||||
+ "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}");
|
||||
|
||||
assertTheModelRefused(answer, "KeyDerivationHashAlgorithm");
|
||||
}
|
||||
|
||||
/** The ARN of a key the request may name. */
|
||||
private static String keyArn() {
|
||||
return call("CreateKey", CREATE_KEY).then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
}
|
||||
|
||||
/** The key attributes of a symmetric key, with every member the model requires. */
|
||||
private static String keyAttributes() {
|
||||
return "{\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
|
||||
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyAlgorithm\":\"AES_128\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}";
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal a caller sees when a request is missing a member the model requires: the
|
||||
* shape check's, because the shape check runs before the operation does.
|
||||
*/
|
||||
private static void assertTheModelRefused(Response answer, String member) {
|
||||
answer.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", containsString("failed to satisfy constraint"))
|
||||
.body("message", containsString(member));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatAsksForACheckValueOfAnotherKindIsRefused() {
|
||||
// The kind follows the algorithm, so a request that names another is refused
|
||||
@@ -206,20 +482,68 @@ class PaymentCryptographyIntegrationTest {
|
||||
.body("__type", containsString("UnknownOperationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOperationTheServiceDoesNotServeIsRefusedWhateverItsBodySays() {
|
||||
// The model names the operation and the service does not serve it, so it is refused
|
||||
// as the unknown operation it is. The body it carries does not change that: a body
|
||||
// that breaks the model's rules is not the answer to an operation that is not
|
||||
// served at all.
|
||||
call("RestoreKey", "{}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("UnknownOperationException"));
|
||||
call("RestoreKey", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:us-east-1:"
|
||||
+ "000000000000:key/abcdefghijklmnop\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("UnknownOperationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCertificateOfAKeyIsServedOverTheWire() {
|
||||
// The certificate of an asymmetric key, with the chain that goes with it.
|
||||
String arn = call("CreateKey", CREATE_KEY_PAIR)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + arn + "\"}")
|
||||
.then().statusCode(200)
|
||||
.body("KeyCertificate", notNullValue())
|
||||
.body("KeyCertificateChain", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCertificateOfAKeyIsNotServedForABareKeyId() {
|
||||
// The identifier of a key is its ARN, an alias ARN or an alias name, and the model's
|
||||
// pattern is what settles it, the same as for the other operations that take one. A
|
||||
// bare id names no key, so it is refused the way GetKey refuses it.
|
||||
String arn = call("CreateKey", CREATE_KEY_PAIR).then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
String id = arn.substring(arn.lastIndexOf('/') + 1);
|
||||
|
||||
call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + id + "\"}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key is created with the usage and the modes of use the reference
|
||||
* requires, and a request without either of them is refused.
|
||||
*/
|
||||
@Test
|
||||
void aKeyWithoutItsUsageOrItsModesIsRefused() {
|
||||
call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true}},\"Exportable\":true}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", containsString("ValidationException"));
|
||||
// The shape check settles the members the attributes must carry, so it is the refusal
|
||||
// that answers, and the message a caller sees is its own.
|
||||
assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
|
||||
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyModesOfUse\":{\"Encrypt\":true}},"
|
||||
+ "\"Exportable\":true}"), "KeyUsage");
|
||||
assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
|
||||
+ "\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}"),
|
||||
"KeyModesOfUse");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWithoutItsAttributesIsRefused() {
|
||||
assertTheModelRefused(call("CreateKey", "{\"Exportable\":true}"), "KeyAttributes");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+964
@@ -0,0 +1,964 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Certificates;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.CertificatesTest;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.RsaOaep;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
import io.floci.aws.testing.ManualClock;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The certificate-based half of the key exchange.
|
||||
*
|
||||
* <p>A key that leaves the service under a certificate is wrapped for the receiver, and the
|
||||
* certificates the two sides exchange are the ones the service mints for the occasion. A key
|
||||
* that comes back is checked against the authority that signed the certificate, and against
|
||||
* the signature the sender made over it.
|
||||
*/
|
||||
class PaymentCryptographyKeyExchangeTest {
|
||||
|
||||
private PaymentCryptographyService service;
|
||||
|
||||
/** The key a key block is wrapped under. */
|
||||
private PaymentCryptographyKey protection;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new PaymentCryptographyService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"));
|
||||
protection = service.createKey("us-east-1",
|
||||
Map.of("KeyAlgorithm", "AES_256",
|
||||
"KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true)),
|
||||
Map.of("Wrap", true, "Unwrap", true), true, true, Map.of());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void theImportParametersCarryACertificateAndAToken() {
|
||||
Map<String, Object> parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
|
||||
assertNotNull(parameters.get("ImportToken"));
|
||||
assertNotNull(parameters.get("WrappingKeyCertificate"));
|
||||
assertNotNull(parameters.get("WrappingKeyCertificateChain"));
|
||||
assertEquals("RSA_2048", parameters.get("WrappingKeyAlgorithm"));
|
||||
assertNotNull(parameters.get("ParametersValidUntilTimestamp"));
|
||||
assertNotNull(Certificates
|
||||
.parseCertificate((String) parameters.get("WrappingKeyCertificate")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExportParametersCarryACertificateAndAToken() {
|
||||
Map<String, Object> parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false);
|
||||
|
||||
assertNotNull(parameters.get("ExportToken"));
|
||||
assertNotNull(parameters.get("SigningKeyCertificate"));
|
||||
assertNotNull(parameters.get("SigningKeyCertificateChain"));
|
||||
assertEquals("RSA_2048", parameters.get("SigningKeyAlgorithm"));
|
||||
assertNotNull(parameters.get("ParametersValidUntilTimestamp"));
|
||||
assertNotNull(Certificates
|
||||
.parseCertificate((String) parameters.get("SigningKeyCertificate")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachTokenIsNamedForTheOperationThatIssuedIt() {
|
||||
String importToken = (String) service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false)
|
||||
.get("ImportToken");
|
||||
String exportToken = (String) service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false)
|
||||
.get("ExportToken");
|
||||
|
||||
assertTrue(importToken.startsWith("import-token-"), importToken);
|
||||
assertTrue(exportToken.startsWith("export-token-"), exportToken);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMaterialTypeThatTakesNoParametersIsRefused() {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.parametersForImport("TR31_KEY_BLOCK", "RSA_2048", false));
|
||||
AwsException refusedExport = assertThrows(AwsException.class,
|
||||
() -> service.parametersForExport("KEY_CRYPTOGRAM", "RSA_2048", false));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertEquals("ValidationException", refusedExport.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlgorithmThatIsNotAKeyAlgorithmIsRefused() {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.parametersForImport("TR34_KEY_BLOCK", "AES_256", false));
|
||||
AwsException refusedExport = assertThrows(AwsException.class,
|
||||
() -> service.parametersForExport("TR34_KEY_BLOCK", "AES_256", false));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertEquals("ValidationException", refusedExport.getErrorCode());
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
void theBlockCarriesTheHeadersTheRequestNames() {
|
||||
// The optional blocks are in the clear and are authenticated with the cipher text, and
|
||||
// the exportability and the version sit in the header.
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("WrappingKeyIdentifier", protection.getKeyId());
|
||||
material.put("KeyBlockHeaders", Map.of(
|
||||
"KeyExportability", "NON_EXPORTABLE",
|
||||
"KeyVersion", "01",
|
||||
"OptionalBlocks", Map.of("AB", "0011")));
|
||||
|
||||
Map<String, Object> answer = service.exportKey("us-east-1",
|
||||
createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(),
|
||||
"Tr31KeyBlock", material, "", "");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
// The header carries the version and the exportability the request asked for.
|
||||
assertEquals("01", block.substring(9, 11), "the version of the key");
|
||||
assertEquals("N", block.substring(11, 12), "the exportability of the key");
|
||||
// The optional block sits between the header and the cipher text, and its length is
|
||||
// in hexadecimal and covers the whole block, the identifier and the length included.
|
||||
assertEquals("AB", block.substring(16, 18), "the optional block's identifier");
|
||||
assertEquals("08", block.substring(18, 20), "the optional block's length");
|
||||
// The optional blocks take up a whole number of cipher blocks, so the block carries a
|
||||
// padding block that fills the rest.
|
||||
assertEquals("02", block.substring(12, 14), "the number of optional blocks");
|
||||
assertEquals("PB080000", block.substring(24, 32), "the padding block");
|
||||
|
||||
// And the block still opens, so the optional blocks are authenticated with it.
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"WrappedKeyBlock", block), "", true, Map.of());
|
||||
assertEquals("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", imported.getKeyUsage());
|
||||
}
|
||||
|
||||
/**
|
||||
* A key that leaves under a cryptogram comes back.
|
||||
*
|
||||
* <p>The import decrypts what the caller brought under the private key the parameters
|
||||
* issued, and that operation is blinded, so a wrong set of CRT values would decrypt to
|
||||
* nothing and the key would not come back.
|
||||
*/
|
||||
@Test
|
||||
void aKeyThatLeavesUnderACryptogramComesBack() { Map<String, Object> importParameters = service.parametersForImport("KEY_CRYPTOGRAM",
|
||||
"RSA_2048", false);
|
||||
|
||||
PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey authority = createAuthority(
|
||||
(String) importParameters.get("WrappingKeyCertificate"));
|
||||
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate"));
|
||||
material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
|
||||
material.put("WrappingSpec", "RSA_OAEP_SHA_256");
|
||||
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram",
|
||||
material, "", "");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat"));
|
||||
|
||||
Map<String, Object> incoming = new LinkedHashMap<>();
|
||||
incoming.put("ImportToken", importParameters.get("ImportToken"));
|
||||
incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial"));
|
||||
incoming.put("WrappingKeyIdentifier", authority.getKeyId());
|
||||
incoming.put("WrappingSpec", "RSA_OAEP_SHA_256");
|
||||
incoming.put("KeyAttributes", Map.of(
|
||||
"KeyAlgorithm", "TDES_2KEY",
|
||||
"KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)));
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming, "", true, Map.of());
|
||||
|
||||
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
void aKeyLeavesUnderAKeyTheTwoPartiesAgreed() {
|
||||
// The two parties agree a key with ECDH, and the key leaves in a block under it.
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
|
||||
PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
|
||||
Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
|
||||
"floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
|
||||
// The counterparty's certificate is signed by the authority, which is what lets the
|
||||
// service trust it.
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", authority.getPrivate(), "floci key-exchange CA");
|
||||
Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
|
||||
|
||||
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
|
||||
"DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
|
||||
|
||||
assertEquals("TR31_KEY_BLOCK", wrapped.get("WrappedKeyMaterialFormat"));
|
||||
|
||||
// The two parties agree the key again, so the block opens under it.
|
||||
Map<String, Object> incoming = new LinkedHashMap<>(exchange.material());
|
||||
incoming.put("WrappedKeyBlock", wrapped.get("KeyMaterial"));
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1",
|
||||
"DiffieHellmanTr31KeyBlock", incoming, "", true, Map.of());
|
||||
|
||||
assertEquals(exchange.key().getKeyMaterialHex(), imported.getKeyMaterialHex());
|
||||
assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeavesUnderAKeyTheTwoPartiesAgreedCarriesTheHeadersTheRequestNames() {
|
||||
// The block headers the request names travel with the block under the agreed key,
|
||||
// the same as they do under a key the service holds.
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
|
||||
PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
|
||||
Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
|
||||
"floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", authority.getPrivate(), "floci key-exchange CA");
|
||||
Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
|
||||
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
|
||||
material.put("KeyBlockHeaders", Map.of(
|
||||
"KeyExportability", "NON_EXPORTABLE",
|
||||
"KeyVersion", "01",
|
||||
"OptionalBlocks", Map.of("AB", "0011")));
|
||||
|
||||
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
|
||||
"DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
// The header carries the version and the exportability the request asked for, and
|
||||
// the optional block sits between the header and the cipher text.
|
||||
assertEquals("01", block.substring(9, 11), "the version of the key");
|
||||
assertEquals("N", block.substring(11, 12), "the exportability of the key");
|
||||
assertEquals("AB", block.substring(16, 18), "the optional block's identifier");
|
||||
assertEquals("08", block.substring(18, 20), "the optional block's length");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCounterpartyCertificateTheAuthorityDidNotSignIsRefused() {
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair other = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
|
||||
PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
|
||||
Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
|
||||
"floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
|
||||
// Signed by somebody else, so the authority cannot vouch for it.
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", other.getPrivate(), "floci somebody else");
|
||||
Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", exchange.key().getKeyId(),
|
||||
"DiffieHellmanTr31KeyBlock", exchange.material(), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("not signed by the certificate authority"),
|
||||
refused.getMessage());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void anInitialKeyLeavesInsteadOfTheBaseKey(boolean baseMayLeave) {
|
||||
// The initial key of the DUKPT derivation is derived from the base
|
||||
// derivation key, and it is the derived key that leaves. The base key may not
|
||||
// leave itself and still derive that initial key, which the export guide says
|
||||
// the standards allow.
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "TDES_2KEY");
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
|
||||
PaymentCryptographyKey base = service.createKey("us-east-1", attributes,
|
||||
Map.of("DeriveKey", Boolean.TRUE), baseMayLeave, true, Map.of());
|
||||
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()), "12345678900000000001", "");
|
||||
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
// The header names the derived key: an initial derivation key of Triple DES, which
|
||||
// the receiver may derive with and may export, but not as a plain working key.
|
||||
assertEquals("B1", block.substring(5, 7), "the usage of the derived key");
|
||||
assertEquals("T", block.substring(7, 8), "the algorithm of the derived key");
|
||||
assertEquals("X", block.substring(8, 9), "the derived key is a derivable one");
|
||||
assertEquals("S", block.substring(11, 12), "the derived key is a sensitive one");
|
||||
// And the check value is the derived key's, not the base key's.
|
||||
assertNotEquals(base.getKeyCheckValue(), wrapped.get("KeyCheckValue"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInitialKeyCannotBeDerivedFromAnotherKey() {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "TDES_2KEY");
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()),
|
||||
"12345678900000000001", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void anImportTokenWorksForEveryImportUntilItExpires() {
|
||||
// A caller that asks for the parameters once may import several keys under them.
|
||||
Map<String, Object> parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
String token = (String) parameters.get("ImportToken");
|
||||
// The cryptogram is built under the wrapping key the parameters carry, so it opens.
|
||||
X509Certificate certificate =
|
||||
Certificates.parseCertificate((String) parameters.get("WrappingKeyCertificate"));
|
||||
String cryptogram = HexFormat.of().withUpperCase().formatHex(RsaOaep.encrypt(
|
||||
certificate.getPublicKey(),
|
||||
HexFormat.of().parseHex("00112233445566778899AABBCCDDEEFF"), "SHA-256"));
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram",
|
||||
Map.of("ImportToken", token,
|
||||
"WrappedKeyCryptogram", cryptogram,
|
||||
"KeyAttributes", Map.of("KeyAlgorithm", "AES_128",
|
||||
"KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true))), "", true, Map.of());
|
||||
assertNotNull(imported, "the second import was refused");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
void theExpiredTokensAreSwept() {
|
||||
// A token that was issued and never quoted again would otherwise stay for the life
|
||||
// of the process, and it holds a private key. The clock moves past the token's life,
|
||||
// so the token is expired and the next issue sweeps it.
|
||||
ManualClock clock = new ManualClock(Instant.parse("2026-01-01T00:00:00Z"));
|
||||
PaymentCryptographyService timed = new PaymentCryptographyService(
|
||||
new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
new SecureRandom(),
|
||||
new PaymentCryptographyRequestContext(),
|
||||
new CertificateGenerator(),
|
||||
clock);
|
||||
timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
clock.advance(Duration.ofDays(31));
|
||||
timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
|
||||
assertEquals(1, timed.issuedTokenCount(),
|
||||
"the token that expired was not swept");
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePrivateKeyIsNotWrittenToTheStore() throws Exception {
|
||||
// The store is a file in the working directory, and a private key in clear in it is
|
||||
// a secret on disk.
|
||||
PaymentCryptographyKey pair = createKeyPair("RSA_2048");
|
||||
|
||||
String written = new ObjectMapper().writeValueAsString(pair);
|
||||
|
||||
assertFalse(written.contains(pair.getKeyPrivateKeyBase64()),
|
||||
"the private key was written to the store");
|
||||
assertFalse(written.contains("keyPrivateKeyBase64"),
|
||||
"the private key was written to the store");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFormTheServiceDoesNotKnowIsRefused() {
|
||||
PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Nonsense", Map.of(), "", ""));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
/** A symmetric key of the given algorithm and usage. */
|
||||
private PaymentCryptographyKey createKey(String algorithm, String usage) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", usage);
|
||||
return service.createKey("us-east-1", attributes,
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
}
|
||||
|
||||
/** A key pair of the given algorithm. */
|
||||
private PaymentCryptographyKey createKeyPair(String algorithm) {
|
||||
return createKeyPair(algorithm, "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
|
||||
}
|
||||
|
||||
/** A key pair of the given algorithm, for the given usage. */
|
||||
private PaymentCryptographyKey createKeyPair(String algorithm, String usage) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR");
|
||||
attributes.put("KeyUsage", usage);
|
||||
// The modes are the ones the purpose allows: a key agreement key derives, a signing
|
||||
// key signs and verifies.
|
||||
Map<String, Boolean> modes = "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT".equals(usage)
|
||||
? Map.of("DeriveKey", true)
|
||||
: Map.of("Sign", true, "Verify", true);
|
||||
return service.createKey("us-east-1", attributes, modes, true, true, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The authority of the exchange: the public half of the certificate the receiver brings.
|
||||
*
|
||||
* <p>A certificate that the service minted for the import is signed by the key it names,
|
||||
* so the key that holds its public half is the authority that can vouch for it.
|
||||
*/
|
||||
private PaymentCryptographyKey createAuthority(String certificate) {
|
||||
return createAuthority(certificate, true);
|
||||
}
|
||||
|
||||
/** An authority that vouches for a certificate, enabled or not. */
|
||||
private PaymentCryptographyKey createAuthority(String certificate, boolean enabled) {
|
||||
return service.importKey("us-east-1", "TrustedCertificatePublicKey", Map.of(
|
||||
"PublicKeyCertificate", certificate,
|
||||
"KeyAttributes", authorityAttributes()), "", enabled, Map.of());
|
||||
}
|
||||
|
||||
/** The attributes an authority carries: a public key that may verify. */
|
||||
private static Map<String, Object> authorityAttributes() {
|
||||
return Map.of(
|
||||
"KeyAlgorithm", "RSA_2048",
|
||||
"KeyClass", "PUBLIC_KEY",
|
||||
"KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
|
||||
"KeyModesOfUse", Map.of("Verify", Boolean.TRUE));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key exchange under a key the two parties agreed with ECDH.
|
||||
*
|
||||
* <p>The service trusts the certificate the counterparty brings because the authority
|
||||
* signed it, so the helper imports the authority, makes the agreement key and builds the
|
||||
* material of the export.
|
||||
*
|
||||
* @param authorityCertificate the certificate of the authority that vouches for the
|
||||
* counterparty
|
||||
* @param counterpartyCertificate the certificate the counterparty brings
|
||||
* @return the material of the export, and the key that leaves under it
|
||||
*/
|
||||
private Exchange agreedExchange(Certificates.Minted authorityCertificate,
|
||||
Certificates.Minted counterpartyCertificate) {
|
||||
PaymentCryptographyKey authority = createAuthority(authorityCertificate.pem());
|
||||
PaymentCryptographyKey agreement = createKeyPair("ECC_NIST_P256",
|
||||
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT");
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("PrivateKeyIdentifier", agreement.getKeyId());
|
||||
material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
|
||||
material.put("PublicKeyCertificate", counterpartyCertificate.pem());
|
||||
material.put("DeriveKeyAlgorithm", "AES_128");
|
||||
material.put("KeyDerivationFunction", "ANSI_X963");
|
||||
material.put("KeyDerivationHashAlgorithm", "SHA_256");
|
||||
material.put("DerivationData", Map.of(
|
||||
"SharedInformation", "00112233445566778899AABBCCDDEEFF"));
|
||||
return new Exchange(material,
|
||||
createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
|
||||
}
|
||||
|
||||
/** The material of a key exchange, and the key that leaves under it. */
|
||||
private record Exchange(Map<String, Object> material, PaymentCryptographyKey key) {
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void anAuthorityThatMayNotVerifyIsRefused() {
|
||||
// The authority vouches for the other party's certificate, so it has to be allowed to
|
||||
// verify.
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
// The cryptogram is wrapped under the receiver's certificate, and a certificate over
|
||||
// a 3072-bit modulus is as strong as the key it wraps.
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
|
||||
Instant now = Instant.now();
|
||||
Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA");
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), "floci counterparty", authority.getPrivate(), "floci CA");
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "RSA_2048");
|
||||
attributes.put("KeyClass", "PUBLIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
|
||||
attributes.put("KeyModesOfUse", Map.of("Encrypt", Boolean.TRUE));
|
||||
PaymentCryptographyKey ca = service.importKey("us-east-1", "TrustedCertificatePublicKey",
|
||||
Map.of("PublicKeyCertificate", caCertificate.pem(), "KeyAttributes", attributes),
|
||||
"", true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", createKey("AES_128",
|
||||
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram",
|
||||
Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("Verify"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredCertificateIsRefused() {
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
// The cryptogram is wrapped under the receiver's certificate, and a certificate over
|
||||
// a 3072-bit modulus is as strong as the key it wraps.
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
|
||||
Instant now = Instant.now();
|
||||
Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA");
|
||||
// The counterparty's certificate has expired, so it protects nothing.
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", authority.getPrivate(), "floci CA",
|
||||
now.minusSeconds(7200), now.minusSeconds(3600));
|
||||
PaymentCryptographyKey ca = createAuthority(caCertificate.pem());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", createKey("AES_128",
|
||||
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram",
|
||||
Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("validity window"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCertificateThatDoesNotParseIsRefused() {
|
||||
// The text is not a certificate, so it is refused rather than stored as one.
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> createAuthority("not a certificate at all"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("not a certificate"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledKeyDoesNotLeave() {
|
||||
// A disabled key does no work, so it may not be exported.
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)),
|
||||
Map.of("Encrypt", true, "Decrypt", true), true, false, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("disabled"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedKeyGetsEveryModeTheBlockStandsFor() {
|
||||
// The mode of use character of the block says what the key may be used for, and
|
||||
// both spellings of a direction stand for it. A block that says B gives the key all
|
||||
// four of Encrypt, Decrypt, Wrap and Unwrap, whichever use the key has.
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
String block = blockOf(key);
|
||||
assertEquals("B", block.substring(8, 9), "the mode of use of the block");
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
|
||||
"", true, Map.of());
|
||||
|
||||
Map<String, Boolean> modes = imported.getKeyModesOfUse();
|
||||
assertEquals(Boolean.TRUE, modes.get("Encrypt"), "the imported key may encrypt");
|
||||
assertEquals(Boolean.TRUE, modes.get("Decrypt"), "the imported key may decrypt");
|
||||
assertEquals(Boolean.TRUE, modes.get("Wrap"), "the imported key may wrap");
|
||||
assertEquals(Boolean.TRUE, modes.get("Unwrap"), "the imported key may unwrap");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExportMayNotGiveAKeyAPermissionItDoesNotHave() {
|
||||
// A key that may only encrypt is refused an export that says it may decrypt: the
|
||||
// modes of use a request names may only narrow the ones the key has.
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Encrypt", true)),
|
||||
Map.of("Encrypt", true), true, true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"KeyBlockHeaders", Map.of("KeyModesOfUse",
|
||||
Map.of("Encrypt", true, "Decrypt", true))),
|
||||
"", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("Decrypt"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExportMayNotLoosenTheExportability() {
|
||||
// The exportability says what the receiver may do with the key once it has it, and
|
||||
// the model states SENSITIVE as the loosest of the three: it lets the receiver
|
||||
// export under a key block, a TR-34 block or a cryptogram, where EXPORTABLE lets it
|
||||
// export under a key block or a TR-34 block only. So an exportable key may not
|
||||
// leave as SENSITIVE, because that is looser than what the key has.
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"KeyBlockHeaders", Map.of("KeyExportability", "SENSITIVE")),
|
||||
"", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("looser"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExportMayTightenTheExportability() {
|
||||
// The other way round: the initial key of the DUKPT derivation is sensitive, and
|
||||
// EXPORTABLE is stricter than that, so it may leave as one.
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "TDES_2KEY");
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
|
||||
PaymentCryptographyKey base = service.createKey("us-east-1", attributes,
|
||||
Map.of("DeriveKey", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"KeyBlockHeaders", Map.of("KeyExportability", "EXPORTABLE")),
|
||||
"12345678900000000001", "");
|
||||
String block = (String) ((Map<?, ?>) answer.get("WrappedKey")).get("KeyMaterial");
|
||||
|
||||
assertEquals("E", block.substring(11, 12), "the exportability of the derived key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledAuthorityDoesNotVouchForACertificate() {
|
||||
// The authority does work when it vouches for a certificate, and a disabled key does
|
||||
// no work, so a disabled authority is refused.
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA",
|
||||
authority.getPrivate(), "floci CA");
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", authority.getPrivate(), "floci CA");
|
||||
PaymentCryptographyKey ca = createAuthority(caCertificate.pem(), false);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "TrustedCertificatePublicKey",
|
||||
Map.of("PublicKeyCertificate", counterpartyCertificate.pem(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", ca.getKeyId(),
|
||||
"KeyAttributes", authorityAttributes()),
|
||||
"", true, Map.of()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("disabled"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedKeySaysItCameFromOutsideTheService() {
|
||||
// A key that came in says its origin is EXTERNAL, and a key the service made says
|
||||
// it is AWS_PAYMENT_CRYPTOGRAPHY.
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"WrappedKeyBlock", blockOf(createKey("AES_128",
|
||||
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"))),
|
||||
"", true, Map.of());
|
||||
|
||||
assertEquals("EXTERNAL", imported.getKeyOrigin(), "the origin of an imported key");
|
||||
assertEquals("AWS_PAYMENT_CRYPTOGRAPHY", protection.getKeyOrigin(),
|
||||
"the origin of a key the service made");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramCarriesNoCheckValue() {
|
||||
// A key block carries the check value of the key it carries, and a cryptogram
|
||||
// carries no key block at all, so it carries no check value either.
|
||||
SecureRandom random = new SecureRandom();
|
||||
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
|
||||
KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
|
||||
Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA",
|
||||
authority.getPrivate(), "floci CA");
|
||||
Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
|
||||
"floci counterparty", authority.getPrivate(), "floci CA");
|
||||
PaymentCryptographyKey ca = createAuthority(caCertificate.pem());
|
||||
|
||||
Map<String, Object> answer = service.exportKey("us-east-1",
|
||||
createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(),
|
||||
"KeyCryptogram",
|
||||
Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", "");
|
||||
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat"));
|
||||
assertFalse(wrapped.containsKey("KeyCheckValue"), "the cryptogram carries a check value");
|
||||
assertFalse(wrapped.containsKey("KeyCheckValueAlgorithm"),
|
||||
"the cryptogram carries a check value algorithm");
|
||||
}
|
||||
|
||||
/** The key block a key leaves under the protection key of the test. */
|
||||
private String blockOf(PaymentCryptographyKey key) {
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "");
|
||||
return (String) ((Map<?, ?>) answer.get("WrappedKey")).get("KeyMaterial");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDataEncryptionKeyMayNotWrapAnExport() {
|
||||
// The wrapping key of a key block is a key encryption key, and a data encryption key
|
||||
// is not one.
|
||||
PaymentCryptographyKey data = service.createKey("us-east-1",
|
||||
Map.of("KeyAlgorithm", "AES_256", "KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)),
|
||||
Map.of("Encrypt", true, "Decrypt", true), true, true, Map.of());
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", data.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("not a key encryption key"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportedKeyThatMayNotLeaveStaysThatWay() {
|
||||
// The exportability is a member of the form, beside the attributes and not inside
|
||||
// them.
|
||||
Map<String, Object> importParameters = service.parametersForImport("KEY_CRYPTOGRAM",
|
||||
"RSA_2048", false);
|
||||
PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey authority = createAuthority(
|
||||
(String) importParameters.get("WrappingKeyCertificate"));
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate"));
|
||||
material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
|
||||
material.put("WrappingSpec", "RSA_OAEP_SHA_256");
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram",
|
||||
material, "", "");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
|
||||
Map<String, Object> incoming = new LinkedHashMap<>();
|
||||
incoming.put("ImportToken", importParameters.get("ImportToken"));
|
||||
incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial"));
|
||||
incoming.put("WrappingKeyIdentifier", authority.getKeyId());
|
||||
incoming.put("WrappingSpec", "RSA_OAEP_SHA_256");
|
||||
incoming.put("Exportable", Boolean.FALSE);
|
||||
incoming.put("KeyAttributes", Map.of(
|
||||
"KeyAlgorithm", "TDES_2KEY",
|
||||
"KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
|
||||
"KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)));
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming,
|
||||
"", true, Map.of());
|
||||
|
||||
assertFalse(imported.isExportable(), "the key was imported as one that may leave");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfAnotherPurposeMayNotAgree() {
|
||||
// The key that agrees has to be a key agreement key.
|
||||
PaymentCryptographyKey signing = createKeyPair("ECC_NIST_P256");
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock",
|
||||
Map.of("PrivateKeyIdentifier", signing.getKeyId(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", signing.getKeyId(),
|
||||
"PublicKeyCertificate", "not a certificate",
|
||||
"DeriveKeyAlgorithm", "AES_128",
|
||||
"KeyDerivationFunction", "ANSI_X963",
|
||||
"KeyDerivationHashAlgorithm", "SHA_256",
|
||||
"DerivationData", Map.of(
|
||||
"SharedInformation", "00112233445566778899AABBCCDDEEFF")),
|
||||
"", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("key agreement"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotACurveKeyIsRefused() {
|
||||
// An RSA key cannot take part in an agreement, and it is refused rather than read as
|
||||
// a curve key.
|
||||
PaymentCryptographyKey rsa = createKeyPair("RSA_2048");
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock",
|
||||
Map.of("PrivateKeyIdentifier", rsa.getKeyId(),
|
||||
"CertificateAuthorityPublicKeyIdentifier", rsa.getKeyId(),
|
||||
"PublicKeyCertificate", "not a certificate",
|
||||
"DeriveKeyAlgorithm", "AES_128",
|
||||
"KeyDerivationFunction", "ANSI_X963",
|
||||
"KeyDerivationHashAlgorithm", "SHA_256",
|
||||
"DerivationData", Map.of(
|
||||
"SharedInformation", "00112233445566778899AABBCCDDEEFF")),
|
||||
"", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExportWithAnotherCheckValueAlgorithmIsRefused() {
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "ANSI_X9_24"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportWithAnotherCheckValueAlgorithmIsRefused() {
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(),
|
||||
"WrappedKeyBlock", block),
|
||||
"ANSI_X9_24", true, Map.of()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theParametersCanBeReused() {
|
||||
// A caller that asks for the last parameters gets them, token and certificate alike.
|
||||
Map<String, Object> first = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
Map<String, Object> again = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", true);
|
||||
Map<String, Object> fresh = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
|
||||
|
||||
assertEquals(first.get("ImportToken"), again.get("ImportToken"));
|
||||
assertEquals(first.get("WrappingKeyCertificate"), again.get("WrappingKeyCertificate"));
|
||||
assertNotEquals(first.get("ImportToken"), fresh.get("ImportToken"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExportParametersOutliveTheirCertificate() {
|
||||
// The parameters are good until the certificate they carry is not.
|
||||
Map<String, Object> parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048",
|
||||
false);
|
||||
String certificate = (String) parameters.get("SigningKeyCertificate");
|
||||
long validUntil = ((Number) parameters.get("ParametersValidUntilTimestamp")).longValue();
|
||||
X509Certificate parsed = Certificates.parseCertificate(certificate);
|
||||
|
||||
assertTrue(parsed.getNotAfter().toInstant().getEpochSecond() >= validUntil,
|
||||
"the certificate expires before the parameters do");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSensitiveKeyMayLeaveTheServiceAgain() {
|
||||
// The exportability of a block says whether the key that comes in may leave again.
|
||||
// A sensitive one may: it is only under a trusted key that it may not be worked with.
|
||||
//
|
||||
// The block is made here rather than exported, because the service writes the
|
||||
// exportability of the block it makes itself: a key it exports is exportable, and
|
||||
// the only key it exports as sensitive is the initial DUKPT key, whose usage the
|
||||
// model has no name for. A counterparty's block may carry the sensitive one all the
|
||||
// same.
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyKeyRules.material(
|
||||
createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY")),
|
||||
PaymentCryptographyKeyRules.material(protection),
|
||||
true, "A", "D0", "B", "S");
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
|
||||
"", true, Map.of());
|
||||
|
||||
assertTrue(imported.isExportable(), "the sensitive key may not leave the service again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotExportableDoesNotComeBackExportable() {
|
||||
// The exportability of a block says whether the key that comes in may leave again.
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("WrappingKeyIdentifier", protection.getKeyId());
|
||||
material.put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE"));
|
||||
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", key.getKeyId(),
|
||||
"Tr31KeyBlock", material, "", "").get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
|
||||
"", true, Map.of());
|
||||
|
||||
assertFalse(imported.isExportable(), "the key that may not leave came back exportable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModesOfUseTheRequestNamesAreReadTheWayTheKeyHasThem() {
|
||||
// A key encryption key wraps and unwraps rather than encrypting and decrypting, so
|
||||
// the modes the request names for one are read that way too.
|
||||
Map<String, Object> material = new LinkedHashMap<>();
|
||||
material.put("WrappingKeyIdentifier", protection.getKeyId());
|
||||
material.put("KeyBlockHeaders", Map.of(
|
||||
"KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true)));
|
||||
|
||||
PaymentCryptographyKey key = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", key.getKeyId(),
|
||||
"Tr31KeyBlock", material, "", "").get("WrappedKey");
|
||||
String block = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
assertEquals("B", block.substring(8, 9), "the mode of use of the key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCertificateOfAKeyCarriesItsChain() {
|
||||
// The certificate the service mints is signed by the service, so the chain is the
|
||||
// certificate itself.
|
||||
PaymentCryptographyKey key = createKeyPair("RSA_2048");
|
||||
|
||||
Map<String, Object> answer = service.publicKeyCertificate(key);
|
||||
|
||||
assertNotNull(answer.get("KeyCertificate"), "the certificate is missing");
|
||||
assertNotNull(answer.get("KeyCertificateChain"), "the chain of the certificate is missing");
|
||||
X509Certificate parsed = Certificates.parseCertificate(
|
||||
(String) answer.get("KeyCertificate"));
|
||||
long validity = parsed.getNotAfter().toInstant().getEpochSecond()
|
||||
- parsed.getNotBefore().toInstant().getEpochSecond();
|
||||
// The certificate is good for ninety days, and it starts an hour early so that a
|
||||
// clock a little behind the service's still accepts it.
|
||||
assertEquals(90L * 24 * 3600 + 3600, validity,
|
||||
"the certificate is not valid for ninety days");
|
||||
}
|
||||
|
||||
}
|
||||
+239
@@ -61,6 +61,23 @@ class PaymentCryptographyServiceTest {
|
||||
return service.createKey(region, attributes, modes, true, true, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a key block is wrapped under.
|
||||
*
|
||||
* <p>A key block is wrapped under a key encryption key, and not under a data encryption
|
||||
* key: the usages keep the two apart.
|
||||
*/
|
||||
private PaymentCryptographyKey createWrappingKey(String region) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "AES_256");
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY");
|
||||
Map<String, Boolean> modes = new LinkedHashMap<>();
|
||||
modes.put("Wrap", Boolean.TRUE);
|
||||
modes.put("Unwrap", Boolean.TRUE);
|
||||
return service.createKey(region, attributes, modes, true, true, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCreatedKeyIsInItsRegionAndCarriesMaterial() {
|
||||
PaymentCryptographyKey key = createKey("us-east-1");
|
||||
@@ -540,4 +557,226 @@ class PaymentCryptographyServiceTest {
|
||||
service.find("alias", List.of("alias/team/card-key"), "us-east-1"));
|
||||
assertEquals(Optional.empty(), service.find("approval-team", List.of("whatever"), "us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeavesTheServiceAndComesBack() {
|
||||
PaymentCryptographyKey protection = createWrappingKey("us-east-1");
|
||||
PaymentCryptographyKey key = createKey("us-east-1");
|
||||
|
||||
Map<String, Object> answer = exportTr31Answer("us-east-1", key.getKeyId(),
|
||||
protection.getKeyId());
|
||||
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
|
||||
String export = (String) wrapped.get("KeyMaterial");
|
||||
|
||||
assertEquals(protection.getArn(), wrapped.get("WrappingKeyArn"));
|
||||
assertEquals(key.getKeyCheckValue(), wrapped.get("KeyCheckValue"));
|
||||
assertTrue(export.length() > 32, "the block is only its header");
|
||||
|
||||
PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
|
||||
|
||||
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
|
||||
assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue());
|
||||
assertEquals(key.getKeyUsage(), imported.getKeyUsage());
|
||||
assertTrue(imported.isExportable(), "the block said the key is exportable");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeavesUnderATdesProtectionKeyAsATypeBBlock() {
|
||||
// The block type follows the protection key's family: a TDES key gives a type B block,
|
||||
// an AES one a type D block. That is the rule the emulator follows.
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("TDES_2KEY", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
attributes("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
|
||||
|
||||
assertTrue(export.startsWith("B"), "a TDES protection key gives a type B block");
|
||||
assertEquals("T", export.substring(7, 8), "the block carries a TDES key");
|
||||
|
||||
PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
|
||||
|
||||
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
|
||||
assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeavesUnderAnAesProtectionKeyAsATypeDBlock() {
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
|
||||
|
||||
assertTrue(export.startsWith("D"), "an AES protection key gives a type D block");
|
||||
assertEquals("A", export.substring(7, 8), "the block carries an AES key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyUnderAWeakerProtectionKeyIsRefused() {
|
||||
// The wrapping key has to be at least as strong as the key it protects, or the
|
||||
// protection buys nothing. The strengths are the ones the standards count, so a
|
||||
// two-key TDES key is 80 bits and an AES-128 one is 128.
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("AES_128", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyUnderAStrongerProtectionKeyIsAllowed() {
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
attributes("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
|
||||
|
||||
assertTrue(export.startsWith("D"), "an AES protection key gives a type D block");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfEveryUsageTheServiceMakesLeavesAsItsOwnUsage() {
|
||||
// A key block carries the usage of the key it carries, so every usage the service
|
||||
// makes has to have a code. A usage without one could not leave the service at all,
|
||||
// and the counterparty could not tell what it had.
|
||||
//
|
||||
// The asymmetric usage is not in the list: a key pair has no material a key block
|
||||
// could carry, so it leaves in a TR-34 block, which this service does not write.
|
||||
List<String[]> usages = List.of(
|
||||
new String[] {"TR31_B0_BASE_DERIVATION_KEY", "AES_256"},
|
||||
new String[] {"TR31_C0_CARD_VERIFICATION_KEY", "AES_256"},
|
||||
new String[] {"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "AES_256"},
|
||||
new String[] {"TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "AES_256"},
|
||||
new String[] {"TR31_E1_EMV_MKEY_CONFIDENTIALITY", "AES_256"},
|
||||
new String[] {"TR31_E2_EMV_MKEY_INTEGRITY", "AES_256"},
|
||||
new String[] {"TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS", "AES_256"},
|
||||
new String[] {"TR31_E5_EMV_MKEY_CARD_PERSONALIZATION", "AES_256"},
|
||||
new String[] {"TR31_E6_EMV_MKEY_OTHER", "AES_256"},
|
||||
new String[] {"TR31_K0_KEY_ENCRYPTION_KEY", "AES_256"},
|
||||
new String[] {"TR31_K1_KEY_BLOCK_PROTECTION_KEY", "AES_256"},
|
||||
// The ISO 9797 MACs are defined over Triple DES.
|
||||
new String[] {"TR31_M0_ISO_16609_MAC_KEY", "TDES_2KEY"},
|
||||
new String[] {"TR31_M1_ISO_9797_1_MAC_KEY", "TDES_2KEY"},
|
||||
new String[] {"TR31_M3_ISO_9797_3_MAC_KEY", "TDES_2KEY"},
|
||||
new String[] {"TR31_M6_ISO_9797_5_CMAC_KEY", "AES_256"},
|
||||
new String[] {"TR31_M7_HMAC_KEY", "AES_256"},
|
||||
new String[] {"TR31_P0_PIN_ENCRYPTION_KEY", "AES_256"},
|
||||
new String[] {"TR31_P1_PIN_GENERATION_KEY", "AES_256"},
|
||||
new String[] {"TR31_V1_IBM3624_PIN_VERIFICATION_KEY", "AES_256"},
|
||||
new String[] {"TR31_V2_VISA_PIN_VERIFICATION_KEY", "AES_256"});
|
||||
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
for (String[] usage : usages) {
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1",
|
||||
attributes(usage[1], usage[0]),
|
||||
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
|
||||
|
||||
PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
|
||||
|
||||
assertEquals(usage[0], imported.getKeyUsage(), usage[0] + " did not survive the round trip");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAsymmetricKeyDoesNotLeaveInAKeyBlock() {
|
||||
// The asymmetric usage is a key pair, and a key pair has no material a key block
|
||||
// could carry. It leaves in a TR-34 block, which this service does not write.
|
||||
PaymentCryptographyKey protection = service.createKey("us-east-1",
|
||||
attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "RSA_2048");
|
||||
attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR");
|
||||
attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
|
||||
Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE), true, true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotExportableDoesNotLeaveTheService() {
|
||||
PaymentCryptographyKey protection = createKey("us-east-1");
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", "AES_256");
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockThatIsNotTheKeysDoesNotOpen() {
|
||||
PaymentCryptographyKey protection = createWrappingKey("us-east-1");
|
||||
PaymentCryptographyKey other = createWrappingKey("us-east-1");
|
||||
PaymentCryptographyKey key = createKey("us-east-1");
|
||||
String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> importTr31("us-east-1", other.getKeyId(), export));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The TR-31 key block a key leaves the service in.
|
||||
*/
|
||||
private String exportTr31(String region, String keyId, String wrappingKeyId) {
|
||||
return (String) ((Map<?, ?>) exportTr31Answer(region, keyId, wrappingKeyId)
|
||||
.get("WrappedKey")).get("KeyMaterial");
|
||||
}
|
||||
|
||||
/**
|
||||
* The whole answer of an export, which carries the block and what wrapped it.
|
||||
*/
|
||||
private Map<String, Object> exportTr31Answer(String region, String keyId, String wrappingKeyId) {
|
||||
return service.exportKey(region, keyId, "Tr31KeyBlock",
|
||||
Map.of("WrappingKeyIdentifier", wrappingKeyId), "", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The key that comes into the service out of a TR-31 key block.
|
||||
*/
|
||||
private PaymentCryptographyKey importTr31(String region, String wrappingKeyId, String block) {
|
||||
return service.importKey(region, "Tr31KeyBlock", Map.of(
|
||||
"WrappingKeyIdentifier", wrappingKeyId,
|
||||
"WrappedKeyBlock", block), "", true, Map.of());
|
||||
}
|
||||
|
||||
/** The attributes of a key with that algorithm and usage. */
|
||||
private static Map<String, Object> attributes(String algorithm, String usage) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", usage);
|
||||
return attributes;
|
||||
}
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The TR-31 key block, against the vectors the standard's examples give.
|
||||
*
|
||||
* <p>The values here are the ones a key block must have, checked against an
|
||||
* independent implementation of the same formats. The block type follows the family of the
|
||||
* key that protects it: a type B block under a TDES key and a type D one under an AES key, and
|
||||
* the algorithm byte says which family the key the block carries belongs to.
|
||||
*
|
||||
* <p>Every vector here was computed by the emulator itself, so a block made here and a block
|
||||
* made there are the same bytes and a block made under one kind of protection key does not open
|
||||
* under another.
|
||||
*/
|
||||
class PaymentCryptographyTr31Test {
|
||||
|
||||
/** The hexadecimal the blocks are written in. */
|
||||
private static final HexFormat HEX = HexFormat.of().withUpperCase();
|
||||
|
||||
/** A two-key TDES key block protection key, sixteen bytes. */
|
||||
private static final String TDES_2KEY_KEK = "0123456789ABCDEFFEDCBA9876543210";
|
||||
|
||||
/** A three-key TDES key block protection key, twenty-four bytes. */
|
||||
private static final String TDES_3KEY_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210";
|
||||
|
||||
/** An AES-128 key block protection key, sixteen bytes. */
|
||||
private static final String AES_128_KEK = "0123456789ABCDEFFEDCBA9876543210";
|
||||
|
||||
/** An AES-192 key block protection key, twenty-four bytes. */
|
||||
private static final String AES_192_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210";
|
||||
|
||||
/** An AES-256 key block protection key, thirty-two bytes. */
|
||||
private static final String AES_256_KEK =
|
||||
"0123456789ABCDEFFEDCBA9876543210FEDCBA98765432100011223344556677";
|
||||
|
||||
/** The key a block carries. */
|
||||
private static final String CLEAR_KEY = "00112233445566778899AABBCCDDEEFF";
|
||||
|
||||
@Test
|
||||
void aTypeBBlockUnderATwoKeyTdesKeyIsTheOneTheEmulatorMakes() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
|
||||
false, "T", "D0", "B", "E");
|
||||
|
||||
assertEquals("B0080D0TB00E000026E528E7FBDBA2578329DDD6F427055C2D51AF1AF42ED5829C79F8ADD31152C8",
|
||||
block);
|
||||
assertEquals("D0", PaymentCryptographyTr31.usageOf(block));
|
||||
assertEquals("B", PaymentCryptographyTr31.modeOf(block));
|
||||
assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeBBlockUnderAThreeKeyTdesKeyIsTheOneTheEmulatorMakes() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(TDES_3KEY_KEK),
|
||||
false, "T", "D0", "B", "E");
|
||||
|
||||
assertEquals("B0080D0TB00E000001FF74012D3ABDE92191B91AA598383A0FD7CB744A9E4AFE9D34A369AD6552C3",
|
||||
block);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeDBlockUnderAnAes128KeyIsTheOneTheEmulatorMakes() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK),
|
||||
true, "A", "D0", "B", "E");
|
||||
|
||||
assertEquals("D0112D0AB00E00002BF9E2CB83E27A26C8790C18CAC198C415E9E78520142D81320789CFD5B9C09DEF03F7569177D33FD1BE0A1DAB4D33AB",
|
||||
block);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeDBlockUnderAnAes192KeyIsTheOneTheEmulatorMakes() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_192_KEK),
|
||||
true, "A", "D0", "B", "E");
|
||||
|
||||
assertEquals("D0112D0AB00E00003FF1AB040D384A3F1827C5EE54DC7CFA43635B0186A3A63A57E77958737CEA57B972DFE983F559525768746563BC6FF7",
|
||||
block);
|
||||
assertEquals("D0", PaymentCryptographyTr31.usageOf(block));
|
||||
assertEquals("B", PaymentCryptographyTr31.modeOf(block));
|
||||
assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeDBlockUnderAnAes256KeyIsTheOneTheEmulatorMakes() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_256_KEK),
|
||||
true, "A", "D0", "B", "E");
|
||||
|
||||
assertEquals("D0112D0AB00E00003E9F4789A8798032CEC87CBA5960E1D7F4512292784F56164C0A62AA2F184D2151167F8F8013169102F89530D9B0C647",
|
||||
block);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockOpensUnderTheKeyThatMadeIt() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
|
||||
false, "T", "D0", "B", "E");
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeDBlockOpensUnderTheAesKeyThatMadeIt() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_192_KEK),
|
||||
true, "A", "D0", "B", "E");
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(AES_192_KEK)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockDoesNotOpenUnderAnotherKey() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
|
||||
false, "T", "D0", "B", "E");
|
||||
|
||||
try {
|
||||
PaymentCryptographyTr31.unwrap(block,
|
||||
PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEF"));
|
||||
throw new AssertionError("the block opened under the wrong key");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("the key block did not authenticate under the key", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTypeDBlockDoesNotOpenUnderAnotherKeyOfTheSameLength() {
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_192_KEK),
|
||||
true, "A", "D0", "B", "E");
|
||||
|
||||
try {
|
||||
PaymentCryptographyTr31.unwrap(block,
|
||||
PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEFFEDCBA9876543210"));
|
||||
throw new AssertionError("the block opened under another key");
|
||||
} catch (IllegalArgumentException expected) {
|
||||
assertEquals("the key block did not authenticate under the key", expected.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWithOptionalBlocksIsImported() {
|
||||
// An optional block sits between the header and the cipher text in the clear, and it
|
||||
// is authenticated with it, so the cipher text starts after it.
|
||||
// The identifier, the length over two characters and the value. The length covers
|
||||
// the whole block, the identifier and the length included, and it is in hexadecimal.
|
||||
String block = blockWithOptionalBlock("00" + "0C" + "61626364");
|
||||
|
||||
byte[] key = PaymentCryptographyTr31.unwrap(block,
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK));
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOptionalBlockWithALengthInHexadecimalIsRead() {
|
||||
// The length of an optional block is in hexadecimal, so a length of "0E" is fourteen
|
||||
// characters and not a number at all.
|
||||
String block = blockWithOptionalBlock("TT" + "0E" + "0123456789");
|
||||
|
||||
byte[] key = PaymentCryptographyTr31.unwrap(block,
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK));
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOptionalBlockTheReferenceGivesIsWrittenAsItGivesIt() {
|
||||
// The reference gives the base derivation key identifier of a DUKPT key as "BI" with
|
||||
// the value "00ABCDEFABCD", and its length is written as "10": the whole block is
|
||||
// sixteen characters, the identifier and the length included.
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
|
||||
"A", "D0", "B", "E", "00",
|
||||
List.<String[]>of(new String[] {"BI", "00ABCDEFABCD"}));
|
||||
|
||||
assertEquals("BI1000ABCDEFABCD", block.substring(16, 32),
|
||||
"the optional block was not written as the standard says");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockIsPaddedSoThatItsOptionalBlocksStayAligned() {
|
||||
// The optional blocks take up a whole number of cipher blocks, so a block whose
|
||||
// optional blocks are not aligned gets a padding block that makes them so. The
|
||||
// optional block here is twenty-four characters and a cipher block is sixteen, so
|
||||
// the padding block carries four characters of filler.
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
|
||||
"A", "D0", "B", "E", "00",
|
||||
List.<String[]>of(new String[] {"KS", "00604B120F9292800000"}));
|
||||
|
||||
// The optional block and the padding block between the header and the cipher text.
|
||||
String optional = block.substring(16, 16 + 32);
|
||||
assertEquals("KS1800604B120F9292800000", optional.substring(0, 24),
|
||||
"the optional block was not written as the standard says");
|
||||
assertEquals("PB080000", optional.substring(24), "the padding block was not added");
|
||||
assertEquals(2, Integer.parseInt(block.substring(12, 14)),
|
||||
"the padding block was not counted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWhoseOptionalBlocksAreAlignedGetsNoPaddingBlock() {
|
||||
// Optional blocks that already fill whole cipher blocks are left alone, because a
|
||||
// padding block would break the alignment. Twelve characters of data make the
|
||||
// optional block sixteen characters long, which is one cipher block.
|
||||
String block = PaymentCryptographyTr31.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
|
||||
"A", "D0", "B", "E", "00",
|
||||
List.<String[]>of(new String[] {"KS", "00604B120F92"}));
|
||||
|
||||
assertEquals(1, Integer.parseInt(block.substring(12, 14)),
|
||||
"a padding block was added to aligned optional blocks");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWhoseKeyIsNotAWholeNumberOfBytesIsRefused() {
|
||||
// The length the block declares is in bits, and a key is a whole number of bytes.
|
||||
String block = blockWithLength("0081");
|
||||
|
||||
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
|
||||
() -> PaymentCryptographyTr31.unwrap(block,
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK)));
|
||||
|
||||
assertTrue(refused.getMessage().contains("whole number of bytes"), refused.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* A type D block with an optional block in the clear.
|
||||
*
|
||||
* <p>The optional block is its identifier over two characters, its length over four and
|
||||
* then its value. The header says how many of them there are.
|
||||
*/
|
||||
private String blockWithOptionalBlock(String optional) {
|
||||
byte[] lengthEncoded = PaymentCryptographyTr31.lengthEncode(
|
||||
PaymentCryptographyCrypto.fromHex(CLEAR_KEY), 16);
|
||||
byte[][] derived = PaymentCryptographyTr31.deriveKeys(
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK), true);
|
||||
int blockLength = 16 + optional.length() + lengthEncoded.length * 2 + 32;
|
||||
String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E"
|
||||
+ "01" + "00";
|
||||
byte[] mac = PaymentCryptographyTr31.computeMac(header + optional, lengthEncoded,
|
||||
derived[1], true);
|
||||
byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded);
|
||||
return header + optional + HEX.formatHex(cipherText) + HEX.formatHex(mac);
|
||||
}
|
||||
|
||||
/**
|
||||
* A type D block whose length field says the given bits.
|
||||
*
|
||||
* <p>The length is over the key the block carries, and the rest of the block is built the
|
||||
* way the emulator builds one.
|
||||
*/
|
||||
private String blockWithLength(String length) {
|
||||
byte[] clearKey = PaymentCryptographyCrypto.fromHex(CLEAR_KEY);
|
||||
byte[] lengthEncoded = new byte[32];
|
||||
lengthEncoded[0] = (byte) ((Integer.parseInt(length, 16) >> 8) & 0xff);
|
||||
lengthEncoded[1] = (byte) (Integer.parseInt(length, 16) & 0xff);
|
||||
System.arraycopy(clearKey, 0, lengthEncoded, 2, clearKey.length);
|
||||
byte[][] derived = PaymentCryptographyTr31.deriveKeys(
|
||||
PaymentCryptographyCrypto.fromHex(AES_128_KEK), true);
|
||||
int blockLength = 16 + lengthEncoded.length * 2 + 32;
|
||||
String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E"
|
||||
+ "00" + "00";
|
||||
byte[] mac = PaymentCryptographyTr31.computeMac(header, lengthEncoded, derived[1], true);
|
||||
byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded);
|
||||
return header + HEX.formatHex(cipherText) + HEX.formatHex(mac);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber;
|
||||
import org.bouncycastle.asn1.x500.X500Name;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/**
|
||||
* The certificates the key exchange hands out and reads.
|
||||
*
|
||||
* <p>The identifier a TR-34 block names its recipient with is the certificate's own issuer
|
||||
* and serial number, so the two are read back from the certificate the service minted and
|
||||
* compared with what the identifier carries.
|
||||
*/
|
||||
public class CertificatesTest {
|
||||
|
||||
private static final String CN = "floci key-exchange";
|
||||
|
||||
@Test
|
||||
void theIdentifierOfACertificateIsItsIssuerAndItsSerial() throws Exception {
|
||||
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
|
||||
Instant now = Instant.now();
|
||||
Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN);
|
||||
|
||||
byte[] identifier = Certificates.certificateId(certificate.der());
|
||||
|
||||
assertNotNull(identifier);
|
||||
IssuerAndSerialNumber parsed = IssuerAndSerialNumber.getInstance(identifier);
|
||||
X509Certificate certificateParsed = Certificates.parseCertificate(certificate.pem());
|
||||
assertEquals(certificateParsed.getSerialNumber(),
|
||||
parsed.getCertificateSerialNumber().getValue());
|
||||
assertEquals(certificateParsed.getIssuerX500Principal().getName(),
|
||||
parsed.getName().toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIdentifierOfACertificateThatDoesNotParseIsRefused() {
|
||||
try {
|
||||
Certificates.certificateId(new byte[] {0x30, 0x03, 0x02, 0x01, 0x05});
|
||||
} catch (RuntimeException refused) {
|
||||
assertEquals(true, refused.getMessage().contains("does not parse"));
|
||||
return;
|
||||
}
|
||||
throw new AssertionError("a certificate that does not parse was accepted");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSerialOfTheIdentifierIsTheCertificatesOwn() throws Exception {
|
||||
KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
|
||||
Instant now = Instant.now();
|
||||
Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN);
|
||||
|
||||
BigInteger serial = IssuerAndSerialNumber
|
||||
.getInstance(Certificates.certificateId(certificate.der()))
|
||||
.getCertificateSerialNumber().getValue();
|
||||
|
||||
assertEquals(Certificates.parseCertificate(certificate.pem()).getSerialNumber(), serial);
|
||||
}
|
||||
|
||||
/**
|
||||
* A certificate over a key pair, signed by an issuer.
|
||||
*
|
||||
* <p>The service mints its certificates through ACM's generator, and a test that needs a
|
||||
* certificate of its own mints it the same way.
|
||||
*/
|
||||
public static Certificates.Minted mint(PublicKey subjectKey, String subjectName,
|
||||
PrivateKey issuerKey, String issuerName) {
|
||||
return mint(subjectKey, subjectName, issuerKey, issuerName,
|
||||
Instant.now().minusSeconds(3600), Instant.now().plusSeconds(86400));
|
||||
}
|
||||
|
||||
/** A certificate over a key pair, signed by an issuer, with the given validity window. */
|
||||
public static Certificates.Minted mint(PublicKey subjectKey, String subjectName,
|
||||
PrivateKey issuerKey, String issuerName,
|
||||
Instant notBefore, Instant notAfter) {
|
||||
CertificateGenerator generator = new CertificateGenerator();
|
||||
try {
|
||||
X509Certificate certificate = generator.signCertificate(
|
||||
new X500Name("CN=" + subjectName), subjectKey,
|
||||
new X500Name("CN=" + issuerName), issuerKey,
|
||||
List.of(), false, null, notBefore, notAfter);
|
||||
byte[] der = certificate.getEncoded();
|
||||
return new Certificates.Minted(der, Certificates.toPem(der));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("cannot mint a certificate", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-3
@@ -148,7 +148,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() {
|
||||
void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() throws Exception {
|
||||
String smArn = createStateMachine("aws-sdk-start-execution-named", """
|
||||
{
|
||||
"QueryLanguage": "JSONata",
|
||||
@@ -164,8 +164,16 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
|
||||
}
|
||||
""".replace("CHILD_ARN", quickChildArn));
|
||||
|
||||
assertEquals("SUCCEEDED", waitForTerminalState(startExecution(smArn, "{}"))
|
||||
.jsonPath().getString("status"));
|
||||
Response first = waitForTerminalState(startExecution(smArn, "{}"));
|
||||
assertEquals("SUCCEEDED", first.jsonPath().getString("status"));
|
||||
|
||||
// The name is taken while the child's execution runs, and a start with that name and
|
||||
// the same input then returns that execution again, so the second start would
|
||||
// succeed. The name is a conflict once the child's execution is closed, so the test
|
||||
// waits for that.
|
||||
String childArn = mapper.readTree(first.jsonPath().getString("output"))
|
||||
.path("ExecutionArn").asText();
|
||||
waitForTerminalState(childArn);
|
||||
|
||||
Response describe = waitForTerminalState(startExecution(smArn, "{}"));
|
||||
assertEquals("FAILED", describe.jsonPath().getString("status"));
|
||||
|
||||
Reference in new issue
Block a user