feat(paymentcryptography): the material of a key may be translated (#8941)

* feat(paymentcryptography): the material of a key may be translated
* test(paymentcryptography): the sample's key agreement in the compatibility test
* test(paymentcryptography): the wrapped key's format is the model's enum
* fix(paymentcryptography): a verification reads the formats the reference verifies
* docs(paymentcryptography): the deviations the reference's documentation shows
* test(compatibility-tests): a verification of a format the reference does not read
* fix(paymentcryptography): a translation holds to the rules the export and the import hold to
* fix(paymentcryptography): a translation refuses a key whose usage its algorithm does not serve
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-19 07:08:29 -04:00
1 parent d28bdf664b
commit d2fde68865
16 files changed
+1246 -51

No files matched your search

@@ -238,6 +238,58 @@ class PaymentCryptographyCryptoHandlerTest {
assertEquals(key.getArn(), verified.get("KeyArn"));
}
@Test
void aMacAlgorithmThisServiceDoesNotMakeIsRefused() {
// The reference's page for the operation says a HMAC, a CMAC, a DUKPT or an EMV MAC
// can be asked for, and its model names the HMAC family, the EMV MAC and the DUKPT
// CMAC beside the ones this service makes. This service makes the ISO 9797
// algorithms 1 and 3 and the CMAC, and a request that asks for another is refused
// with the error that names the ones it makes.
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
String message = hex("a message".getBytes());
for (String algorithm : new String[] {"HMAC", "HMAC_SHA256", "AS2805_4_1"}) {
ObjectNode attributes = mapper.createObjectNode();
attributes.put("Algorithm", algorithm);
AwsException refused = assertThrows(AwsException.class,
() -> handler.generateMac(request(Map.of(
"KeyIdentifier", key.getArn(), "MessageData", message,
"GenerationAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("CMAC"), refused.getMessage());
}
for (String variant : new String[] {"EmvMac", "DukptCmac"}) {
ObjectNode attributes = mapper.createObjectNode();
attributes.put(variant, mapper.createObjectNode());
AwsException refused = assertThrows(AwsException.class,
() -> handler.generateMac(request(Map.of(
"KeyIdentifier", key.getArn(), "MessageData", message,
"GenerationAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains(variant), refused.getMessage());
}
}
@Test
void anEncryptionModeThisServiceDoesNotMakeIsRefused() {
// The reference's model names eight block cipher modes for the symmetric
// encryption, and this service makes the CBC one, so a request that names another is
// refused rather than answered with a cipher of another kind.
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
for (String mode : new String[] {"ECB", "CFB", "CFB8", "OFB"}) {
ObjectNode symmetric = mapper.createObjectNode();
symmetric.put("Mode", mode);
ObjectNode attributes = mapper.createObjectNode();
attributes.set("Symmetric", symmetric);
AwsException refused = assertThrows(AwsException.class,
() -> handler.encryptData(request(Map.of(
"KeyIdentifier", key.getArn(),
"PlainText", hex("hello, world!!!!".getBytes()),
"EncryptionAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("CBC"), refused.getMessage());
}
}
@Test
void aMacUnderAThreeKeyTdesKeyIsComputedAndVerified() {
// The ISO 9797 MACs are defined over Triple DES, and the cipher takes the three keys
@@ -0,0 +1,186 @@
package io.floci.aws.services.paymentcryptography;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
/**
* The errors the reference documents, and the status it answers them with.
*
* <p>The reference's API pages state, for every action, the errors it raises and the status
* each one carries. The control plane answers them all with 400, the not-found error
* included, which is worth a test of its own: an emulator that answers a missing key with a
* 404 is a client-visible difference that no other test would catch.
*
* <p>The table is the reference's own: an action that names a resource that is not there
* answers with the not-found error.
*/
@QuarkusTest
class PaymentCryptographyDocumentedExceptionsTest {
/** The control plane of Payment Cryptography is an awsJson 1.0 service. */
private static final String CONTENT_TYPE = "application/x-amz-json-1.0";
private static final String TARGET = "PaymentCryptographyControlPlane.";
/** A key identifier of a key the service does not hold. */
private static final String MISSING_KEY = "arn:aws:payment-cryptography:us-east-1:"
+ "000000000000:key/0123456789abcdef0123456789abcdef";
/** The alias of an alias the service does not hold. */
private static final String MISSING_ALIAS = "alias/team/missing";
/** The key the requests that need one name, made once for the whole class. */
private static String keyArn;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
/**
* A key of the service, made once for the whole class.
*
* <p>The requests that name a key make one, so the ones that name a key that is not
* there are answered with the not-found error rather than with the error of a request
* that names nothing.
*
* @return the ARN of the key
*/
private static synchronized String keyArn() {
if (keyArn == null) {
keyArn = given()
.header("X-Amz-Target", TARGET + "CreateKey")
.contentType(CONTENT_TYPE)
.body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ "\"KeyClass\":\"SYMMETRIC_KEY\","
+ "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},"
+ "\"Exportable\":true}")
.when().post("/")
.then().statusCode(200)
.extract().path("Key.KeyArn");
}
return keyArn;
}
private static Response call(String action, String body) {
return given()
.header("X-Amz-Target", TARGET + action)
.contentType(CONTENT_TYPE)
.body(body)
.when().post("/");
}
/**
* The actions that name a key or an alias, with the body that names one that is not
* there.
*
* @return the action and the body of each of them
*/
private static Stream<Arguments> actionsThatNameAMissingResource() {
return Stream.of(
Arguments.of("GetKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("DeleteKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("RestoreKey", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("StartKeyUsage", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("StopKeyUsage", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + MISSING_KEY + "\"}"),
Arguments.of("AddKeyReplicationRegions", "{\"KeyIdentifier\":\"" + MISSING_KEY
+ "\",\"ReplicationRegions\":[\"us-west-2\"]}"),
Arguments.of("RemoveKeyReplicationRegions", "{\"KeyIdentifier\":\"" + MISSING_KEY
+ "\",\"ReplicationRegions\":[\"us-west-2\"]}"),
Arguments.of("TagResource", "{\"ResourceArn\":\"" + MISSING_KEY
+ "\",\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}"),
Arguments.of("UntagResource", "{\"ResourceArn\":\"" + MISSING_KEY
+ "\",\"TagKeys\":[\"Origin\"]}"),
Arguments.of("ListTagsForResource", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"),
Arguments.of("GetResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"),
Arguments.of("DeleteResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY + "\"}"),
Arguments.of("PutResourcePolicy", "{\"ResourceArn\":\"" + MISSING_KEY
+ "\",\"Policy\":\"{\\\"Version\\\":\\\"2012-10-17\\\",\\\"Statement\\\":[]}\"}"),
Arguments.of("GetAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"),
Arguments.of("DeleteAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"),
Arguments.of("UpdateAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\"}"),
Arguments.of("GetMpaTeamAssociation",
"{\"Action\":\"IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE\"}"));
}
@ParameterizedTest
@MethodSource("actionsThatNameAMissingResource")
void anActionThatNamesAKeyThatIsNotThereAnswersNotFound(String action, String body) {
// The reference answers a resource it cannot find with the not-found error, and the
// control plane answers every one of its errors with 400.
call(action, body)
.then().statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
}
@Test
void anActionThatNamesAnAliasThatIsNotThereAnswersNotFound() {
// The alias of the update is named, and the key it would point at is not there
// either, so the alias is what the request cannot find.
call("UpdateAlias", "{\"AliasName\":\"" + MISSING_ALIAS + "\",\"KeyArn\":\""
+ keyArn() + "\"}")
.then().statusCode(400)
.body("__type", containsString("ResourceNotFoundException"));
}
@Test
void anActionThatNamesNoResourceAtAllIsRefused() {
// The reference's model makes the member of each of these requests required, so a
// request that leaves it out is refused before the action does any work.
call("GetKey", "{}")
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
call("GetAlias", "{}")
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
call("ListTagsForResource", "{}")
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
}
@Test
void anActionThatIsNotServedIsRefused() {
call("NotAnAction", "{}")
.then().statusCode(400)
.body("__type", containsString("UnknownOperationException"));
}
@Test
void anActionThatChangesNothingAnswersWithAnEmptyBody() {
// The reference's pages for these three actions show a response with no members at
// all, so the answer carries nothing.
call("TagResource", "{\"ResourceArn\":\"" + keyArn()
+ "\",\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}")
.then().statusCode(200)
.body(equalTo("{}"));
call("UntagResource", "{\"ResourceArn\":\"" + keyArn() + "\",\"TagKeys\":[\"Origin\"]}")
.then().statusCode(200)
.body(equalTo("{}"));
// The policy is put first: a key that carries none has no policy to delete, and the
// reference answers that with the not-found error rather than with an empty answer.
// The document is carried in one line: a line break inside a JSON string is not a
// JSON string, and the request would never reach the service.
String policy = PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY
.replaceAll("\\s*\\n\\s*", " ");
call("PutResourcePolicy", "{\"ResourceArn\":\"" + keyArn()
+ "\",\"Policy\":\"" + policy.replace("\"", "\\\"") + "\"}")
.then().statusCode(200);
call("DeleteResourcePolicy", "{\"ResourceArn\":\"" + keyArn() + "\"}")
.then().statusCode(200)
.body(equalTo("{}"));
}
}
@@ -7,19 +7,28 @@ 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.Ecdh;
import io.floci.aws.services.paymentcryptography.crypto.PaymentCryptographyTr34RoundTripTest;
import io.floci.aws.services.paymentcryptography.crypto.RsaOaep;
import io.floci.aws.services.paymentcryptography.crypto.Tr34;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import io.floci.aws.testing.ManualClock;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.params.KeyParameter;
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.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
@@ -58,6 +67,13 @@ class PaymentCryptographyKeyExchangeTest {
/** The variant the terminal major key is bound to. */
private static final String MAJOR_VARIANT = "TERMINAL_MAJOR_KEY_VARIANT_00";
/**
* The shared information the sample passes: 32 bytes, the same bytes as the KDF's
* other info.
*/
private static final String SAMPLE_SHARED_INFORMATION =
"00112233445566778899AABBCCDDEEFF00112233445566778899AABBCCDDEEFF";
@BeforeEach
void setUp() {
service = new PaymentCryptographyService(
@@ -217,17 +233,7 @@ class PaymentCryptographyKeyExchangeTest {
@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);
Exchange exchange = agreedExchange();
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
@@ -244,19 +250,326 @@ class PaymentCryptographyKeyExchangeTest {
assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage());
}
@Test
void aKeyIsTranslatedFromAKeyTheTwoPartiesAgreedToAnotherKey() {
// The key comes under a key the two parties agreed with ECDH, and it goes out under
// the key the request names.
Exchange exchange = agreedExchange();
// The key that leaves under the agreed key.
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
// The key it is translated under.
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
Map<?, ?> translated = (Map<?, ?>) service.translateKeyMaterial("us-east-1",
translateRequest(exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing))
.get("WrappedKey");
assertEquals("TR31_KEY_BLOCK", translated.get("WrappedKeyMaterialFormat"));
// The block that goes out opens under the key the request named, and it holds the key
// that came in.
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
Map.of("WrappingKeyIdentifier", outgoing.getKeyId(),
"WrappedKeyBlock", translated.get("WrappedKeyMaterial")),
"", true, Map.of());
assertEquals(exchange.key().getKeyMaterialHex(), imported.getKeyMaterialHex());
assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage());
}
@Test
void aTranslatedBlockCarriesTheVersionAndTheOptionalBlocksOfTheBlockThatCameIn() {
// The block that came in is authenticated with its header and its optional blocks,
// so the block that goes out carries the same ones.
Exchange exchange = agreedExchange();
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
material.put("KeyBlockHeaders", Map.of(
"KeyVersion", "01",
"KeyExportability", "EXPORTABLE",
"OptionalBlocks", Map.of("AB", "0011")));
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey");
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
Map<?, ?> translated = (Map<?, ?>) service.translateKeyMaterial("us-east-1",
translateRequest(exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing))
.get("WrappedKey");
String block = (String) translated.get("WrappedKeyMaterial");
assertEquals("01", block.substring(9, 11), "the version 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 aKeyThatMayNotLeaveIsNotTranslatedOut() {
// The block that comes in says the key in it may not leave the service, and the
// block that goes out is handed to the caller, so the key may not be translated
// out of it.
Exchange exchange = agreedExchange();
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
material.put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE"));
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey");
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
AwsException refused = assertThrows(AwsException.class,
() -> service.translateKeyMaterial("us-east-1", translateRequest(
exchange.material(), (String) wrapped.get("KeyMaterial"), outgoing)));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("may not leave the service"), refused.getMessage());
}
@Test
void aKeyIsNotTranslatedUnderAKeyWeakerThanIt() {
// The wrapping key has to be at least as strong as the key it protects, the rule
// the export and the import enforce.
Exchange exchange = agreedExchange("ECC_NIST_P521");
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
material.put("DeriveKeyAlgorithm", "AES_256");
PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", key.getKeyId(),
"DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey");
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
AwsException refused = assertThrows(AwsException.class,
() -> service.translateKeyMaterial("us-east-1", translateRequest(
material, (String) wrapped.get("KeyMaterial"), outgoing)));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage());
}
@Test
void aKeyIsNotTranslatedUnderAnAgreementWeakerThanIt() throws Exception {
// The agreed key opens the block that comes in, so it has to be as strong as the
// key in it, the rule the import enforces.
Exchange exchange = agreedExchange();
Map<String, Object> material = sampleAgreement(exchange);
byte[] derived = sampleDerivedKey(exchange);
// The block carries an AES-256 key, and the agreement is on a curve that is
// weaker than it.
String incoming = PaymentCryptographyTr31.wrap(
HexFormat.of().parseHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"),
derived, true, "A", "D0", "B", "E");
PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY");
AwsException refused = assertThrows(AwsException.class,
() -> service.translateKeyMaterial("us-east-1",
translateRequest(material, incoming, outgoing)));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage());
}
@Test
void aKeyWithAUsageItsAlgorithmDoesNotServeIsNotTranslated() throws Exception {
// The usage binds the key to its purpose: a signature key is an asymmetric one, so an
// AES key may not carry that usage. The block that came in says it does, and the
// translation refuses it rather than answering with a block the import would refuse.
Exchange exchange = agreedExchange("ECC_NIST_P521");
Map<String, Object> material = sampleAgreement(exchange);
byte[] derived = sampleDerivedKey(exchange);
String incoming = PaymentCryptographyTr31.wrap(
HexFormat.of().parseHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"),
derived, true, "A", "S0", "B", "E");
PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY");
AwsException refused = assertThrows(AwsException.class,
() -> service.translateKeyMaterial("us-east-1",
translateRequest(material, incoming, outgoing)));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("may not be made of"), refused.getMessage());
}
@Test
void aKeyIsTranslatedWithTheCheckValueAlgorithmTheRequestNames() {
// The request may name the check value algorithm, and the one it names for an AES
// key is the CMAC.
Exchange exchange = agreedExchange();
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
Map<String, Object> request = translateRequest(exchange.material(),
(String) wrapped.get("KeyMaterial"), outgoing);
request.put("KeyCheckValueAlgorithm", "CMAC");
Map<?, ?> translated = (Map<?, ?>) service.translateKeyMaterial("us-east-1", request)
.get("WrappedKey");
assertEquals(cmacKeyCheckValue(exchange.key().getKeyMaterialHex()),
translated.get("KeyCheckValue"));
}
@Test
void aCheckValueAlgorithmTheKeyDoesNotHaveIsRefused() {
// The check value of an AES key is a CMAC, so a request that asks for the ANSI
// X9.24 one asks for a value this service does not compute.
Exchange exchange = agreedExchange();
Map<?, ?> wrapped = (Map<?, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
"DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
PaymentCryptographyKey outgoing = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
Map<String, Object> request = translateRequest(exchange.material(),
(String) wrapped.get("KeyMaterial"), outgoing);
request.put("KeyCheckValueAlgorithm", "ANSI_X9_24");
AwsException refused = assertThrows(AwsException.class,
() -> service.translateKeyMaterial("us-east-1", request));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("check value algorithm"),
refused.getMessage());
}
@Test
void aKeyIsTranslatedUnderTheKeyTheSampleDerives() throws Exception {
// The sample derives the one-time wrapping key with the Concat KDF of NIST SP
// 800-56A over the shared secret, with SHA-512 and a 32-byte shared information,
// and the emulator has to derive the same key from the request's parameters. The
// agreement is on a curve as strong as the key it opens, because the agreed key
// has to be at least as strong as the key in the block.
Exchange exchange = agreedExchange("ECC_NIST_P521");
Map<String, Object> material = sampleAgreement(exchange);
byte[] derived = sampleDerivedKey(exchange);
// The block that comes in is under the derived key, as the sample wraps it. The
// key in it may leave the service, because the translation hands it to the
// caller.
String incoming = PaymentCryptographyTr31.wrap(
HexFormat.of().parseHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"),
derived, true, "A", "D0", "B", "E");
// The wrapping key has to be at least as strong as the key it carries.
PaymentCryptographyKey outgoing = createKey("AES_256", "TR31_K0_KEY_ENCRYPTION_KEY");
Map<?, ?> translated = (Map<?, ?>) service.translateKeyMaterial("us-east-1",
translateRequest(material, incoming, outgoing)).get("WrappedKey");
// The block that goes out holds the key that came in, and the check value is the
// one the sample computes locally.
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
Map.of("WrappingKeyIdentifier", outgoing.getKeyId(),
"WrappedKeyBlock", translated.get("WrappedKeyMaterial")),
"", true, Map.of());
assertEquals("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
imported.getKeyMaterialHex());
assertEquals(cmacKeyCheckValue(imported.getKeyMaterialHex()), translated.get("KeyCheckValue"));
}
/**
* The request that translates a block that came in under the agreed key.
*
* @param material the material of the agreement
* @param block the block that comes in
* @param wrappingKey the key the block goes out under
* @return the request
*/
private static Map<String, Object> translateRequest(Map<String, Object> material, String block,
PaymentCryptographyKey wrappingKey) {
Map<String, Object> incoming = new LinkedHashMap<>(material);
incoming.put("WrappedKeyBlock", block);
Map<String, Object> request = new LinkedHashMap<>();
request.put("IncomingKeyMaterial", Map.of("DiffieHellmanTr31KeyBlock", incoming));
request.put("OutgoingKeyMaterial", Map.of(
"Tr31KeyBlock", Map.of("WrappingKeyIdentifier", wrappingKey.getKeyId())));
return request;
}
/**
* The material of the sample's agreement: a key derived with the Concat KDF of NIST
* SP 800-56A.
*
* @param exchange the exchange the two parties made
* @return the material of the agreement
*/
private static Map<String, Object> sampleAgreement(Exchange exchange) {
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
material.put("DeriveKeyAlgorithm", "AES_256");
material.put("KeyDerivationFunction", "NIST_SP800");
material.put("KeyDerivationHashAlgorithm", "SHA_512");
material.put("DerivationData", Map.of("SharedInformation", SAMPLE_SHARED_INFORMATION));
return material;
}
/**
* The key the sample derives from the secret the two parties made.
*
* @param exchange the exchange the two parties made
* @return the derived key
*/
private byte[] sampleDerivedKey(Exchange exchange) throws Exception {
return concatKdf("SHA-512", sharedSecret(exchange),
HexFormat.of().parseHex(SAMPLE_SHARED_INFORMATION), 32);
}
/**
* The Concat KDF of NIST SP 800-56A, as the standard writes it.
*
* <p>The key is the digest of the counter, the secret and the shared information, the
* counter over the blocks that are needed, so the derivation here does not use the
* service's own.
*/
private static byte[] concatKdf(String hash, byte[] secret, byte[] otherInfo, int length)
throws Exception {
MessageDigest digest = MessageDigest.getInstance(hash);
byte[] out = new byte[length];
int at = 0;
for (int counter = 1; at < length; counter++) {
digest.reset();
// The standard's order: the counter, then the secret, then the shared
// information.
digest.update(new byte[] {
(byte) (counter >>> 24), (byte) (counter >>> 16), (byte) (counter >>> 8),
(byte) counter});
digest.update(secret);
digest.update(otherInfo);
byte[] block = digest.digest();
int take = Math.min(block.length, length - at);
System.arraycopy(block, 0, out, at, take);
at += take;
}
return out;
}
/**
* The check value of a key: the leftmost three bytes of the CMAC of sixteen zero bytes.
*
* <p>The sample computes it the same way, so the emulator's answer is held to the
* sample's.
*/
private static String cmacKeyCheckValue(String keyHex) {
CMac mac = new CMac(new AESEngine());
mac.init(new KeyParameter(HexFormat.of().parseHex(keyHex)));
// The CMAC of sixteen zero bytes.
mac.update(new byte[16], 0, 16);
byte[] value = new byte[16];
mac.doFinal(value, 0);
return HexFormat.of().withUpperCase().formatHex(value).substring(0, 6);
}
/** The secret the two parties made, from the service's key and the counterparty's. */
private byte[] sharedSecret(Exchange exchange) throws Exception {
PaymentCryptographyKey agreement = service.findKey("us-east-1",
(String) exchange.material().get("PrivateKeyIdentifier"));
PrivateKey privateKey = PaymentCryptographyKeyExchange.privateKeyOf(agreement);
X509Certificate certificate = Certificates.parseCertificate(
(String) exchange.material().get("PublicKeyCertificate"));
return Ecdh.agree((ECPrivateKey) privateKey, (ECPublicKey) certificate.getPublicKey());
}
@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);
Exchange exchange = agreedExchange();
Map<String, Object> material = new LinkedHashMap<>(exchange.material());
material.put("KeyBlockHeaders", Map.of(
"KeyExportability", "NON_EXPORTABLE",
@@ -287,7 +600,8 @@ class PaymentCryptographyKeyExchangeTest {
// 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);
Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate,
"ECC_NIST_P256");
AwsException refused = assertThrows(AwsException.class,
() -> service.exportKey("us-east-1", exchange.key().getKeyId(),
@@ -1141,6 +1455,39 @@ class PaymentCryptographyKeyExchangeTest {
"KeyModesOfUse", Map.of("Verify", Boolean.TRUE));
}
/**
* A key exchange under a key the two parties agreed with ECDH, on the curve the
* cardholder-device flow uses.
*
* @return the material of the export, and the key that leaves under it
*/
private Exchange agreedExchange() {
return agreedExchange("ECC_NIST_P256");
}
/**
* A key exchange under a key the two parties agreed with ECDH, on the given curve.
*
* <p>The authority vouches for the counterparty's certificate, so the helper mints the
* two certificates and builds the agreement.
*
* @param curve the curve the agreement is made on
* @return the material of the export, and the key that leaves under it
*/
private Exchange agreedExchange(String curve) {
SecureRandom random = new SecureRandom();
KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
PaymentCryptographyKeyAlgorithm.from(curve), 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");
return agreedExchange(authorityCertificate, counterpartyCertificate, curve);
}
/**
* A key exchange under a key the two parties agreed with ECDH.
*
@@ -1151,12 +1498,13 @@ class PaymentCryptographyKeyExchangeTest {
* @param authorityCertificate the certificate of the authority that vouches for the
* counterparty
* @param counterpartyCertificate the certificate the counterparty brings
* @param curve the curve the agreement is made on
* @return the material of the export, and the key that leaves under it
*/
private Exchange agreedExchange(Certificates.Minted authorityCertificate,
Certificates.Minted counterpartyCertificate) {
Certificates.Minted counterpartyCertificate, String curve) {
PaymentCryptographyKey authority = createAuthority(authorityCertificate.pem());
PaymentCryptographyKey agreement = createKeyPair("ECC_NIST_P256",
PaymentCryptographyKey agreement = createKeyPair(curve,
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT");
Map<String, Object> material = new LinkedHashMap<>();
material.put("PrivateKeyIdentifier", agreement.getKeyId());
@@ -202,6 +202,29 @@ class PaymentCryptographyPinOperationsTest {
assertEquals(pvk.getArn(), verified.get("VerificationKeyArn"));
}
@Test
void aBlockInAFormatTheReferenceDoesNotVerifyIsRefused() {
// The reference names the formats it verifies: "AWS Payment Cryptography supports
// ISO_Format_0 and ISO_Format_3". The format 4 block is an AES block, and the
// verification reads the Triple DES blocks, so a request that names another format
// is refused rather than answered as if the reference read it.
PaymentCryptographyKey pek = pinEncryptionKey();
PaymentCryptographyKey pvk = visaVerificationKey();
for (String format : new String[] {"ISO_FORMAT_4", "ISO_FORMAT_1"}) {
AwsException refused = assertThrows(AwsException.class,
() -> pin.verifyPinData(request(Map.of(
"EncryptionKeyIdentifier", pek.getArn(),
"VerificationKeyIdentifier", pvk.getArn(),
"PinBlockFormat", format,
"PrimaryAccountNumber", PAN,
"EncryptedPinBlock", "00000000000000000000000000000000",
"VerificationAttributes", visaPin(1, "1234"))),
"us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("ISO_FORMAT_0"), refused.getMessage());
}
}
@Test
void aBlockWithTheWrongVerificationValueIsRefused() {
PaymentCryptographyKey pek = pinEncryptionKey();