diff --git a/compatibility-tests/sdk-test-awscli/README.md b/compatibility-tests/sdk-test-awscli/README.md index d2a9f83cdb..4435fad035 100644 --- a/compatibility-tests/sdk-test-awscli/README.md +++ b/compatibility-tests/sdk-test-awscli/README.md @@ -22,6 +22,7 @@ Tests are plain bash scripts that call `aws` CLI commands with `--endpoint-url` | `s3-notifications` | S3 → SQS event notifications | | `payment-cryptography-data` | The Payment Cryptography data plane: encrypt, decrypt, MAC | | `payment-cryptography-pin` | The Payment Cryptography PIN operations: generate, verify, translate | +| `payment-cryptography-card` | The Payment Cryptography card operations: the card verification value and the authorization cryptogram | ## Requirements diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats new file mode 100644 index 0000000000..a4569bc673 --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-card.bats @@ -0,0 +1,150 @@ +#!/usr/bin/env bats +# Payment Cryptography card validation value and authorization cryptogram tests +# +# The card operations are the data plane's own routes, so a client of it reaches them +# under the internal prefix the router rewrites them onto. These tests drive them with +# the AWS CLI, which is such a client. + +setup() { + load 'test_helper/common-setup' + CVK_ARN="" + ACG_ARN="" + DATA_KEY_ARN="" +} + +teardown() { + for key in "$CVK_ARN" "$ACG_ARN" "$DATA_KEY_ARN"; do + if [ -n "$key" ]; then + aws_cmd payment-cryptography delete-key --key-identifier "$key" \ + --delete-key-in-days 7 >/dev/null 2>&1 || true + fi + done +} + +# A key of the card verification usage, for the value of the card account. +create_cvk() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_C0_CARD_VERIFICATION_KEY,KeyModesOfUse={Generate=true,Verify=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +# A key of the application cryptogram usage, for the cryptogram of the transaction. +create_acg() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS,KeyModesOfUse={Generate=true,DeriveKey=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +@test "Payment Cryptography card: a card verification value is generated and verifies" { + CVK_ARN=$(create_cvk) + [ -n "$CVK_ARN" ] + + run aws_cmd payment-cryptography-data generate-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_success + VALUE=$(json_get "$output" '.ValidationData') + [ -n "$VALUE" ] + # The value is three digits. + [ "${#VALUE}" -eq 3 ] + # The answer names the key the value was computed under. + [ "$(json_get "$output" '.KeyArn')" = "$CVK_ARN" ] + + run aws_cmd payment-cryptography-data verify-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --validation-data "$VALUE" \ + --verification-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_success +} + +@test "Payment Cryptography card: a card verification value that does not verify is refused" { + CVK_ARN=$(create_cvk) + [ -n "$CVK_ARN" ] + + # The value is not the one over the card account, so the verification fails. + run aws_cmd payment-cryptography-data verify-card-validation-data \ + --key-identifier "$CVK_ARN" \ + --primary-account-number "5081470082639564" \ + --validation-data "999" \ + --verification-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_failure + # A value that does not verify is a verification that failed, not a malformed request. + [[ "$output" == *"VerificationFailedException"* ]] +} + +@test "Payment Cryptography card: a key of the wrong usage is refused" { + # The card verification value is computed under the card verification key, and the + # usage is what says which key that is. + run aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text + assert_success + DATA_KEY_ARN="$output" + [ -n "$DATA_KEY_ARN" ] + + run aws_cmd payment-cryptography-data generate-card-validation-data \ + --key-identifier "$DATA_KEY_ARN" \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'CardVerificationValue1={CardExpiryDate=3003,ServiceCode=201}' + assert_failure + [[ "$output" == *"ValidationException"* ]] +} + +@test "Payment Cryptography card: the authorization cryptogram is generated and verifies" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + run aws_cmd payment-cryptography-data generate-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_success + CRYPTOGRAM=$(json_get "$output" '.AuthRequestCryptogram') + [ -n "$CRYPTOGRAM" ] + # The cryptogram is the eight bytes of the retail MAC, as hexadecimal. + [ "${#CRYPTOGRAM}" -eq 16 ] + + run aws_cmd payment-cryptography-data verify-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --auth-request-cryptogram "$CRYPTOGRAM" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_success +} + +@test "Payment Cryptography card: an authorization cryptogram that does not verify is refused" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + # The cryptogram is not the one over the transaction, so the verification fails. + run aws_cmd payment-cryptography-data verify-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --auth-request-cryptogram "0000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'EmvCommon={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01,ApplicationTransactionCounter=0001}' + assert_failure + [[ "$output" == *"VerificationFailedException"* ]] +} + +@test "Payment Cryptography card: the American Express cryptogram is refused" { + ACG_ARN=$(create_acg) + [ -n "$ACG_ARN" ] + + # The AEIPS session key derivation is proprietary, so the service answers with the + # error that says so rather than with a cryptogram of its own making. + run aws_cmd payment-cryptography-data generate-auth-request-cryptogram \ + --key-identifier "$ACG_ARN" \ + --transaction-data "00000000170000000000000008400080008000084016051700000000093800000B1F2201030000000000000000000000000000000000000000000000000000008000000000000000" \ + --major-key-derivation-mode EMV_OPTION_A \ + --session-key-derivation-attributes 'Amex={PrimaryAccountNumber=5081470082639564,PanSequenceNumber=01}' + assert_failure + [[ "$output" == *"ValidationException"* ]] +} diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java new file mode 100644 index 0000000000..cb68174516 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyCardTest.java @@ -0,0 +1,276 @@ +package com.floci.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient; +import software.amazon.awssdk.services.paymentcryptography.model.KeyAlgorithm; +import software.amazon.awssdk.services.paymentcryptography.model.KeyClass; +import software.amazon.awssdk.services.paymentcryptography.model.KeyModesOfUse; +import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; +import software.amazon.awssdk.services.paymentcryptographydata.PaymentCryptographyDataClient; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardGenerationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardVerificationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.CardVerificationValue1; +import software.amazon.awssdk.services.paymentcryptographydata.model.DynamicCardVerificationValue; +import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateAuthRequestCryptogramResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.GenerateCardValidationDataResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.MajorKeyDerivationMode; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyAmex; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyDerivation; +import software.amazon.awssdk.services.paymentcryptographydata.model.SessionKeyEmvCommon; +import software.amazon.awssdk.services.paymentcryptographydata.model.ValidationException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VerificationFailedException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VerificationFailedReason; + +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Payment Cryptography card validation values and authorization cryptograms") +class PaymentCryptographyCardTest { + + /** The account number the card values belong to. */ + private static final String PAN = "5081470082639564"; + + /** The expiry of the card, in the YYMM form the request takes. */ + private static final String EXPIRY = "3003"; + + /** The service code of the first card verification value. */ + private static final String SERVICE_CODE = "201"; + + /** The sequence number of the card, which the master key derivation takes. */ + private static final String PSN = "01"; + + /** The transaction counter the session key derivation takes. */ + private static final String ATC = "0001"; + + /** + * The transaction data the cryptogram is computed over. + * + *
The user guide tells the caller to pad the transaction data before sending + * it, and the data here is padded the way its example is: a whole number of + * eight-byte blocks, with the {@code 80} and the zeros that method 2 appends. + */ + private static final String TRANSACTION_DATA = + "00000000170000000000000008400080008000084016051700000000093800000B1F2201" + + "030000000000000000000000000000000000000000000000000000008000000000000000"; + + private static PaymentCryptographyDataClient client; + private static String cardVerificationKeyArn; + private static String dynamicValueKeyArn; + private static String applicationCryptogramKeyArn; + + @BeforeAll + static void setup() { + client = TestFixtures.paymentCryptographyDataClient(); + // The card verification value is computed under the card verification key, the dynamic + // one under a key of its own usage that may derive, and the cryptogram under the + // application cryptogram key. + cardVerificationKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_C0_CARD_VERIFICATION_KEY, m -> m.generate(true).verify(true)); + dynamicValueKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_E6_EMV_MKEY_OTHER, m -> m.generate(true).verify(true).deriveKey(true)); + applicationCryptogramKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS, m -> m.generate(true).deriveKey(true)); + } + + /** + * The ARN of a key of the given algorithm, usage and modes of use. + * + *
Every key this test needs is made the same way, so the request is written once
+ * and each key only differs in the attributes it carries.
+ *
+ * @param algorithm the key's algorithm
+ * @param usage the key's usage
+ * @param modes the modes of use the key allows
+ * @return the ARN of the key that was made
+ */
+ private static String createKeyArn(KeyAlgorithm algorithm, KeyUsage usage,
+ Consumer The model states the length of a hexadecimal member and does not always state an
+ * even one, so a member of an odd length is a request the model allows and the cipher
+ * cannot read. It is refused with the error the model names, rather than answered with
+ * a failure the caller cannot catch.
+ *
+ * @param member the member's path, for the refusal
+ * @param value the member's text
+ * @return the member's text, unchanged
+ */
+ static String hex(String member, String value) {
+ if (value.length() % 2 != 0) {
+ throw new AwsException("ValidationException",
+ member + " must be an even number of hexadecimal characters", 400);
+ }
+ return value;
+ }
+
+ /**
+ * A hexadecimal member that the cipher reads as whole blocks.
+ *
+ * The ISO 9797-1 MAC runs over eight-byte blocks, so the data it reads has to
+ * be a whole number of them. The user guide tells the caller to pad the
+ * transaction data before sending it, and a length that is not a whole number of
+ * blocks is a request the cipher cannot read, so it is refused rather than read
+ * as the blocks that fit.
+ *
+ * @param member the member's path, for the refusal
+ * @param value the member's text
+ * @return the member's text, unchanged
+ */
+ static String blocks(String member, String value) {
+ if (value.length() % 16 != 0) {
+ throw new AwsException("ValidationException",
+ member + " must be a whole number of eight-byte blocks", 400);
+ }
+ return value;
+ }
+
+ /**
+ * Refuses the wrapped-key form of a key.
+ *
+ * A wrapped key is a TR-31 key block that the service unwraps with a key-encryption
+ * key, and the unwrapping is part of the key exchange. Until it is made, a request that
+ * carries one is refused rather than answered as if the key were a fixed one.
+ *
+ * @param request the request to read
+ * @param member the member the wrapped key would come in
+ */
+ static void refuseWrappedKey(JsonNode request, String member) {
+ if (request.get(member) != null) {
+ throw new AwsException("ValidationException",
+ member + " is not supported by this service", 400);
+ }
+ }
+
/**
* The one variant an attributes member holds.
*
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java
new file mode 100644
index 0000000000..36b3961b4a
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperations.java
@@ -0,0 +1,328 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.services.paymentcryptography.crypto.EmvCrypto;
+import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
+
+/**
+ * The authorization request cryptograms.
+ *
+ * The ARQC is the cryptogram of an authorization request, computed under a session key that
+ * the transaction's key derivation produces. The session key is derived from the ICC AC master
+ * key, which is itself derived from the account number and the sequence number, so the whole
+ * chain is one derivation and the cryptogram is the ISO 9797-1 algorithm 3 retail MAC over the
+ * transaction data, cut to eight bytes.
+ *
+ * Three derivations are served. The EMV common session key is the one the EMV common
+ * specification gives. The Mastercard derivation is the proprietary one, which also
+ * diversifies with the unpredictable number. The Visa derivation derives no session key at
+ * all: the transaction data is enciphered under the ICC master key, which is the Visa Smart
+ * Debit and Credit method.
+ *
+ * Two derivations are refused rather than approximated. The American Express one is
+ * proprietary and there is nothing to verify it against, and a plausible wrong cryptogram is
+ * worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which needs the
+ * card's public key certificate.
+ */
+@ApplicationScoped
+public class PaymentCryptographyAuthCryptogramOperations {
+
+ /** The hexadecimal the data plane's blobs are written in. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ /** The session key derivations. */
+ private enum Scheme {
+ /** The EMV common session key, derived from the application transaction counter. */
+ EMV_COMMON,
+ /** The Mastercard proprietary derivation, which also diversifies with the number. */
+ MASTERCARD,
+ /** No session key: the transaction data is enciphered under the ICC master key. */
+ VSDC
+ }
+
+ /** The variants that use the EMV common session key. */
+ private static final Set The session key is derived per scheme, so this is the one place the choice is made; the
+ * cryptogram itself is always the ISO 9797-1 algorithm 3 retail MAC, cut to eight bytes.
+ */
+ private static EmvCrypto.Arqc computeArqc(SessionKey sk, byte[] imk, String transactionData) {
+ byte[] mk = masterKeyOf(sk, imk);
+ byte[] atc = HEX.parseHex(sk.atc);
+ byte[] sessionKey;
+ switch (sk.scheme) {
+ case MASTERCARD:
+ sessionKey = EmvCrypto.deriveSessionKeyMastercard(
+ mk, atc, HEX.parseHex(sk.unpredictableNumber));
+ break;
+ case EMV_COMMON:
+ sessionKey = EmvCrypto.deriveSessionKey(mk, atc);
+ break;
+ case VSDC:
+ default:
+ // No session key: the transaction data is enciphered under the ICC master key,
+ // which is the Visa Smart Debit method.
+ sessionKey = mk;
+ break;
+ }
+ byte[] mac = EmvCrypto.retailMac(sessionKey, HEX.parseHex(transactionData),
+ EmvCrypto.Padding.NONE);
+ return new EmvCrypto.Arqc(Arrays.copyOf(mac, 8), sessionKey);
+ }
+
+ /**
+ * The ICC AC master key for the resolved derivation, which is also the M/Chip ARPC key.
+ *
+ * A derivation the request cannot be read for is refused with the error the model
+ * names, rather than answered with a failure the caller cannot catch.
+ */
+ private static byte[] masterKeyOf(SessionKey sk, byte[] imk) {
+ try {
+ return sk.optionB
+ ? EmvCrypto.deriveIccMasterKeyOptionB(imk, sk.pan, sk.psn)
+ : EmvCrypto.deriveIccMasterKey(imk, sk.pan, sk.psn);
+ } catch (IllegalArgumentException e) {
+ throw validation(e.getMessage());
+ }
+ }
+
+ /**
+ * Resolves the master-key derivation mode and the session-key derivation attributes, which
+ * both cryptogram operations share.
+ */
+ private static SessionKey resolveDerivation(JsonNode request) {
+ boolean optionB = "EMV_OPTION_B".equals(text(request, "MajorKeyDerivationMode"));
+
+ JsonNode skd = request.get("SessionKeyDerivationAttributes");
+ if (skd == null) {
+ throw validation("SessionKeyDerivationAttributes is required");
+ }
+ String variant = soleVariant(skd);
+ if (variant == null) {
+ throw validation("SessionKeyDerivationAttributes must specify exactly one variant");
+ }
+ // Amex is refused rather than approximated: the AEIPS session key derivation is
+ // proprietary and there is nothing to verify a derivation against, and a plausible wrong
+ // cryptogram is the one outcome worse than an error.
+ if ("Amex".equals(variant)) {
+ throw validation("SessionKeyDerivationAttributes.Amex requires the AEIPS session key "
+ + "derivation, which this service does not implement. It is not approximated.");
+ }
+ if ("Emv2000".equals(variant)) {
+ throw validation("SessionKeyDerivationAttributes.Emv2000 requires the EMV 4.1 tree "
+ + "derivation, which this service does not implement. It is not approximated.");
+ }
+ boolean common = COMMON_SK.contains(variant);
+ boolean mastercard = "Mastercard".equals(variant);
+ if (!common && !mastercard && !DIRECT_SK.contains(variant)) {
+ throw validation("SessionKeyDerivationAttributes." + variant
+ + " is not a recognized variant");
+ }
+ JsonNode attrs = skd.get(variant);
+ String pan = text(attrs, "PrimaryAccountNumber");
+ String psn = text(attrs, "PanSequenceNumber");
+ String atc = text(attrs, "ApplicationTransactionCounter");
+ if (mastercard && optionB) {
+ // The reference implementation's own constraint: master key derivation option B is
+ // not used in practice with this scheme.
+ throw validation("MasterKeyDerivationMode EMV_OPTION_B is not used in practice with "
+ + "the Mastercard session key derivation (EMV_OPTION_A only)");
+ }
+ String unpredictableNumber = null;
+ if (mastercard) {
+ // Taken from the request, never inferred: the transaction data is an opaque
+ // concatenated block whose layout the caller chooses, so a fixed offset would be
+ // right for one CDOL and silently wrong for every other.
+ unpredictableNumber = text(attrs, "UnpredictableNumber");
+ }
+ Scheme scheme = mastercard ? Scheme.MASTERCARD
+ : (common ? Scheme.EMV_COMMON : Scheme.VSDC);
+ return new SessionKey(pan, psn, atc, scheme, unpredictableNumber, optionB);
+ }
+
+ // ---- the helpers ---------------------------------------------------------
+
+ private PaymentCryptographyKey requiredKey(String identifier, String region) {
+ PaymentCryptographyKey key = service.findKey(region, identifier);
+ if (key == null) {
+ throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
+ }
+ PaymentCryptographyKeyRules.requireEnabled(key);
+ return key;
+ }
+
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+
+ private static AwsException verificationFailed(String message, String reason) {
+ return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason));
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java
new file mode 100644
index 0000000000..eba6730798
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardController.java
@@ -0,0 +1,58 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.core.common.RegionResolver;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.Response;
+
+/**
+ * The data plane's card validation values and the authorization cryptograms.
+ *
+ * The routes are the ones the AWS SDK builds: the card validation value of a card account,
+ * and the cryptogram an authorization request carries.
+ */
+@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
+public class PaymentCryptographyCardController extends PaymentCryptographyDataPlaneController {
+
+ private final PaymentCryptographyCardValidationOperations cardValidation;
+
+ private final PaymentCryptographyAuthCryptogramOperations authCryptogram;
+
+ @Inject
+ public PaymentCryptographyCardController(PaymentCryptographyCardValidationOperations cardValidation,
+ PaymentCryptographyAuthCryptogramOperations authCryptogram,
+ ObjectMapper objectMapper,
+ RegionResolver regionResolver) {
+ super(objectMapper, regionResolver);
+ this.cardValidation = cardValidation;
+ this.authCryptogram = authCryptogram;
+ }
+
+ @POST
+ @Path("/cardvalidationdata/generate")
+ public Response generateCardValidationData(String body, @Context HttpHeaders headers) {
+ return respond(cardValidation.generate(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/cardvalidationdata/verify")
+ public Response verifyCardValidationData(String body, @Context HttpHeaders headers) {
+ return respond(cardValidation.verify(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/cryptogram/generate")
+ public Response generateAuthRequestCryptogram(String body, @Context HttpHeaders headers) {
+ return respond(authCryptogram.generate(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/cryptogram/verify")
+ public Response verifyAuthRequestCryptogram(String body, @Context HttpHeaders headers) {
+ return respond(authCryptogram.verify(parse(body), region(headers)));
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java
new file mode 100644
index 0000000000..786c9dea15
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCardValidationOperations.java
@@ -0,0 +1,246 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.services.paymentcryptography.crypto.CvvCrypto;
+import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
+
+/**
+ * The card validation operations.
+ *
+ * The card verification value is the value the issuer holds and the acquirer asks for: the
+ * three digits of the CVV, computed under the card verification key from the account number,
+ * the expiry and the service code.
+ *
+ * The dynamic variants compute the value from the transaction instead: the dynamic card
+ * verification value from the account number and the transaction counters, and the dynamic card
+ * verification code from the track data. They need a key of their own usage, and one that may
+ * derive.
+ */
+@ApplicationScoped
+public class PaymentCryptographyCardValidationOperations {
+
+ /** The length of the value when the request does not name one. */
+ private static final int DEFAULT_VALIDATION_DATA_LENGTH = 3;
+
+ /** The service code of the second card verification value, which the service fixes. */
+ private static final String CVV2_SERVICE_CODE = "000";
+
+ private final PaymentCryptographyService service;
+
+ @Inject
+ public PaymentCryptographyCardValidationOperations(PaymentCryptographyService service) {
+ this.service = service;
+ }
+
+ /**
+ * The card validation attributes of a request.
+ */
+ private static final class CardAttrs {
+ /** The static variants: the expiry and the service code. */
+ String expiry;
+ String serviceCode;
+ /** The dynamic variants. */
+ String panSequenceNumber;
+ String applicationTransactionCounter;
+ /** Which variant this is, for the key rules and the cipher. */
+ String variant;
+ }
+
+ // ---- GenerateCardValidationData ------------------------------------------
+
+ /**
+ * The card validation value of a card account.
+ */
+ Map A request the derivation cannot read is refused with the error the model names,
+ * rather than answered with a failure the caller cannot catch.
+ */
+ private static String computeValue(String pan, CardAttrs attrs, PaymentCryptographyKey key,
+ int length) {
+ try {
+ return compute(pan, attrs, key, length);
+ } catch (RuntimeException e) {
+ throw validation("Unable to compute the card validation value: " + e.getMessage());
+ }
+ }
+
+ /** The value for the variant, under the given key. */
+ private static String compute(String pan, CardAttrs attrs, PaymentCryptographyKey key,
+ int length) {
+ if ("DynamicCardVerificationValue".equals(attrs.variant)) {
+ return CvvCrypto.computeDynamicValue(pan, attrs.expiry, attrs.serviceCode,
+ attrs.applicationTransactionCounter,
+ PaymentCryptographyKeyRules.materialHex(key),
+ attrs.panSequenceNumber, length);
+ }
+ return CvvCrypto.computeCvv(pan, attrs.expiry, attrs.serviceCode,
+ PaymentCryptographyKeyRules.materialHex(key), length);
+ }
+
+ /**
+ * The key the variant needs, checked against the service's rules.
+ *
+ * Getting this wrong is the usual reason a call against the real service is rejected, so
+ * it is checked here rather than left to the cipher.
+ */
+ private static void requireKeyForVariant(PaymentCryptographyKey key, String variant, String mode) {
+ if ("DynamicCardVerificationValue".equals(variant)) {
+ PaymentCryptographyKeyRules.requireUsage(key,
+ List.of("TR31_E6_EMV_MKEY_OTHER"), "deriving a dynamic card verification value");
+ PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY",
+ "deriving a dynamic card verification value");
+ PaymentCryptographyKeyRules.requireDerive(key, "deriving a dynamic card verification value");
+ return;
+ }
+ // The static values use the card verification key.
+ PaymentCryptographyKeyRules.requireUsage(key,
+ List.of("TR31_C0_CARD_VERIFICATION_KEY"), "computing a card verification value");
+ PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY",
+ "computing a card verification value");
+ PaymentCryptographyKeyRules.requireMode(key, mode, "Generate".equals(mode)
+ ? "generating a card verification value"
+ : "verifying a card verification value");
+ }
+
+ /**
+ * The card validation attributes of a request.
+ *
+ * The attributes are a union, and exactly one variant of it may be given.
+ */
+ private static CardAttrs resolveCardAttrs(JsonNode attributes) {
+ String variant = soleVariant(attributes);
+ if (variant == null) {
+ throw validation("attributes must specify exactly one variant");
+ }
+ switch (variant) {
+ case "CardVerificationValue1": {
+ JsonNode value = attributes.get(variant);
+ String expiry = text(value, "CardExpiryDate");
+ String serviceCode = text(value, "ServiceCode");
+ CardAttrs out = new CardAttrs();
+ out.variant = variant;
+ out.expiry = expiry;
+ out.serviceCode = serviceCode;
+ return out;
+ }
+ case "CardVerificationValue2": {
+ JsonNode value = attributes.get(variant);
+ String expiry = text(value, "CardExpiryDate");
+ CardAttrs out = new CardAttrs();
+ out.variant = variant;
+ out.expiry = expiry;
+ out.serviceCode = CVV2_SERVICE_CODE;
+ return out;
+ }
+ case "DynamicCardVerificationValue": {
+ JsonNode value = attributes.get(variant);
+ String expiry = text(value, "CardExpiryDate");
+ String serviceCode = text(value, "ServiceCode");
+ String psn = text(value, "PanSequenceNumber");
+ String atc = PaymentCryptographyAttributes.hex(
+ variant + ".ApplicationTransactionCounter",
+ text(value, "ApplicationTransactionCounter"));
+ CardAttrs out = new CardAttrs();
+ out.variant = variant;
+ out.expiry = expiry;
+ out.serviceCode = serviceCode;
+ out.panSequenceNumber = psn;
+ out.applicationTransactionCounter = atc;
+ return out;
+ }
+ case "DynamicCardVerificationCode": {
+ // Refused rather than approximated: the dynamic code is a Mastercard
+ // proprietary construction, and there is nothing published to check a
+ // derivation against.
+ throw validation("the dynamic card verification code is not implemented: it is a "
+ + "Mastercard proprietary construction and it is not approximated");
+ }
+ default:
+ throw validation(variant + " not supported by this service "
+ + "(only CardVerificationValue1/CardVerificationValue2"
+ + "/DynamicCardVerificationValue/DynamicCardVerificationCode)");
+ }
+ }
+
+ private PaymentCryptographyKey requiredKey(String identifier, String region) {
+ PaymentCryptographyKey key = service.findKey(region, identifier);
+ if (key == null) {
+ throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
+ }
+ PaymentCryptographyKeyRules.requireEnabled(key);
+ return key;
+ }
+
+ /**
+ * Checks that the key has the mode of use the operation needs.
+ */
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+
+ private static AwsException verificationFailed(String message, String reason) {
+ return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason));
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java
index eb62ea9721..4e0505eed9 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java
@@ -86,6 +86,7 @@ public class PaymentCryptographyCryptoHandler {
public Map The algorithm is what the cipher runs, so the operation names the one it is
+ * defined over: a Triple DES key and an AES key are different ciphers, and so are
+ * the two Triple DES forms.
+ *
+ * @param key the key the operation runs under
+ * @param algorithm the algorithm the operation needs
+ * @param what the operation, for the message
+ */
+ static void requireAlgorithm(PaymentCryptographyKey key, String algorithm, String what) {
+ if (!algorithm.equals(key.getKeyAlgorithm())) {
+ throw new AwsException("ValidationException",
+ "the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
+ + what + " needs a " + algorithm + " one", 400);
+ }
+ }
+
+ /**
+ * The mode of use a key has to have to derive from it.
+ *
+ * A derivation reads the key, so the key has to allow it. A key with no modes
+ * of use allows nothing, and is refused here rather than read.
+ *
+ * @param key the key the operation runs under
+ * @param what the operation, for the message
+ */
+ static void requireDerive(PaymentCryptographyKey key, String what) {
+ Map One routine serves CVV1, CVV2 (service code 000) and iCVV (service code
+ * 999); only the inputs differ.
+ *
+ * Visa's construction: the leftmost four digits of the account number are replaced by
+ * the transaction counter, and the result, the expiry and the service code are
+ * enciphered under the card's unique derived key. The three leftmost decimal digits of
+ * the result are the value.
+ *
+ * The key is the unique derived key the card is personalised with, which the issuer
+ * derives from the master key with the account number and the PAN sequence number. The
+ * counter diversifies the value by the data it is inserted into, not by the key.
+ */
+ public static String computeDynamicValue(String pan, String expiryYYMM, String serviceCode,
+ String atcHex, String emkHex, String psn,
+ int length) {
+ byte[] udk = EmvCrypto.deriveIccMasterKey(HEX.parseHex(emkHex), pan, psn);
+ return decimalize(alteredPan(pan, atcHex) + PinCrypto.digits(expiryYYMM)
+ + PinCrypto.digits(serviceCode), udk, length);
+ }
+
+ /**
+ * The account number with its leftmost four digits replaced by the transaction counter.
+ *
+ * The counter is a binary coded decimal counter, so its digits are the four decimal
+ * digits of its bytes, and only the rightmost four of them are inserted.
+ */
+ private static String alteredPan(String pan, String atcHex) {
+ String digits = PinCrypto.digits(pan);
+ String counter = atcHex;
+ if (counter.length() > 4) {
+ counter = counter.substring(counter.length() - 4);
+ }
+ StringBuilder altered = new StringBuilder(counter.length() + digits.length());
+ for (int i = 0; i < counter.length(); i++) {
+ char c = counter.charAt(i);
+ if (c < '0' || c > '9') {
+ throw new IllegalArgumentException(
+ "the transaction counter must be a binary coded decimal counter");
+ }
+ altered.append(c);
+ }
+ while (altered.length() < 4) {
+ altered.insert(0, '0');
+ }
+ return altered.append(digits.substring(4)).toString();
+ }
+
+ /**
+ * The card verification cipher: two blocks, the left one enciphered with
+ * the key's left half, exclusive-or the right one, then enciphered again
+ * with the whole key.
+ *
+ * @param input hexadecimal input, at most 32 characters, zero-padded
+ */
+ private static String decimalize(String input, byte[] key, int length) {
+ if (input.length() > 32) {
+ throw new IllegalArgumentException("the input exceeds two blocks");
+ }
+ StringBuilder padded = new StringBuilder();
+ padded.append(input);
+ while (padded.length() < 32) {
+ padded.append('0');
+ }
+ String p = padded.substring(0, 32);
+ byte[] b1 = HEX.parseHex(p.substring(0, 16));
+ byte[] b2 = HEX.parseHex(p.substring(16, 32));
+
+ byte[] r = Ciphers.tdes2Encrypt(Ciphers.xor(Ciphers.tdesSingleDesEncrypt(b1, slice(key, 0, 8)), b2), key);
+ return Decimalize.of(HEX.formatHex(r), length);
+ }
+
+ private static byte[] slice(byte[] b, int from, int to) {
+ byte[] out = new byte[to - from];
+ System.arraycopy(b, from, out, 0, to - from);
+ return out;
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java
new file mode 100644
index 0000000000..a34baf1bef
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java
@@ -0,0 +1,348 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import io.floci.aws.core.common.Digests;
+
+import java.util.HexFormat;
+
+/**
+ * The canonical EMV ARQC/ARPC spine, and the primitives it rests on.
+ *
+ * The transaction data reaches the service already padded, because the caller pads it
+ * the way the card padded it before the card enciphered it. The service enciphers it as
+ * it was sent, and the padding the service applies is the one it applies to the input it
+ * builds itself, which is the issuer authentication cryptogram.
+ *
+ * All DES is done through three-key TDES rather than a single-DES provider:
+ * single DES is expressed as TDES with K||K||K.
+ *
+ * The full PAN flows into master key derivation, because the derivation is
+ * defined over the whole of it.
+ */
+public final class EmvCrypto {
+
+ /** The hexadecimal the data plane's blobs are written in. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ private EmvCrypto() {
+ }
+
+ // ---- primitives ---------------------------------------------------------
+
+ /** Force every DES key byte to odd parity. */
+ public static byte[] adjustDesParity(byte[] key) {
+ byte[] out = new byte[key.length];
+ for (int i = 0; i < key.length; i++) {
+ int b = key[i] & 0xff;
+ int p = 0;
+ // The parity bit is bit 0; XOR bits 1..7, then force the byte odd.
+ for (int bit = 1; bit < 8; bit++) {
+ p ^= (b >> bit) & 1;
+ }
+ out[i] = (byte) ((b & 0xfe) | ((p ^ 0x01) & 0x01));
+ }
+ return out;
+ }
+
+ /**
+ * The ISO 9797-1 padding method used for an application cryptogram.
+ *
+ * The transaction data reaches the service already padded: the user guide tells
+ * the caller to pad it before sending it, because the card padded it the same way
+ * before it enciphered it. The service therefore enciphers the data as it was
+ * given, and padding it again would encipher a block the card never enciphered.
+ */
+ public enum Padding {
+ /**
+ * No padding: the data is enciphered exactly as it was given.
+ */
+ NONE,
+ /**
+ * Method 2: append {@code 0x80}, then zeros to the next boundary,
+ * always adding a block even when the data is already aligned. The input of
+ * an issuer authentication cryptogram is built here rather than by the
+ * caller, so it is this one that is padded.
+ */
+ METHOD2
+ }
+
+ /** Pad according to the given method. */
+ public static byte[] pad(byte[] data, Padding padding) {
+ return switch (padding) {
+ case NONE -> data;
+ case METHOD2 -> pad80(data);
+ };
+ }
+
+ /**
+ * ISO/IEC 9797-1 padding method 2: append {@code 0x80}, then zeros to the
+ * next 8-byte boundary. Always pads a block, so a block-aligned input gains
+ * a whole extra block.
+ */
+ public static byte[] pad80(byte[] data) {
+ int total = data.length - (data.length % 8) + 8;
+ byte[] out = new byte[total];
+ System.arraycopy(data, 0, out, 0, data.length);
+ out[data.length] = (byte) 0x80;
+ return out;
+ }
+
+ /**
+ * ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key.
+ *
+ * This is single-DES chaining, not three-key TDES. The key splits into
+ * K1 (left 8) and K2 (right 8); each block is enciphered under K1, and a
+ * single D_KR then E_KL final transform closes the tag:
+ *
+ * Running a 3DES transform per block instead - the obvious reading -
+ * produces a different MAC.
+ */
+ /** The retail MAC over data padded with the given ISO 9797-1 method. */
+ public static byte[] retailMac(byte[] key16, byte[] data, Padding padding) {
+ byte[] kl = slice(key16, 0, 8);
+ byte[] kr = slice(key16, 8, 16);
+ byte[] padded = pad(data, padding);
+ int nBlocks = padded.length / 8;
+ byte[] h = new byte[8];
+ for (int i = 0; i < nBlocks; i++) {
+ h = Ciphers.tdesSingleDesEncrypt(Ciphers.xor(h, slice(padded, i * 8, i * 8 + 8)), kl);
+ }
+ return Ciphers.tdesSingleDesEncrypt(Ciphers.tdesSingleDesDecrypt(h, kr), kl);
+ }
+
+ // ---- EMV key derivation -------------------------------------------------
+
+ /**
+ * EMV Book 2 Option A ICC master key derivation.
+ *
+ * Y is the last sixteen digits, not the first. For a 16-digit PAN the two differ,
+ * and using the first changes the master key and every tag that follows. The rule is the
+ * one EMV 4.4 Book 2 Annex A1.4.1 gives, and the Visa Integrated Circuit Card
+ * Specification states it the same way: the rightmost sixteen digits of the PAN and the
+ * sequence number, padded on the left with zeros when they are shorter.
+ */
+ public static byte[] deriveIccMasterKey(byte[] imk16, String pan, String psn) {
+ byte[] y = masterKeyInput(pan, psn);
+ byte[] zr = new byte[8];
+ for (int i = 0; i < 8; i++) {
+ zr[i] = (byte) (y[i] ^ 0xff);
+ }
+ return adjustDesParity(concat(
+ Ciphers.tdes2Encrypt(y, imk16),
+ Ciphers.tdes2Encrypt(zr, imk16)));
+ }
+
+ /**
+ * EMV Book 2 Option B master key derivation, for PANs longer than 16 digits.
+ *
+ * The decimal digits of the hash come first, in the order they appear, and the
+ * nibbles that are not decimal digits follow them, each reduced modulo ten. A hash
+ * of a packed account number and sequence number holds sixteen decimal digits
+ * almost every time, so the second part is rarely reached.
+ *
+ * A PAN of sixteen digits or fewer is derived the Option A way: the hash is
+ * only there for the longer numbers.
+ */
+ public static byte[] deriveIccMasterKeyOptionB(byte[] imk16, String pan, String psn) {
+ if (PinCrypto.digits(pan).length() <= 16) {
+ return deriveIccMasterKey(imk16, pan, psn);
+ }
+ byte[] b = packedBcd(pan, psn);
+ String hash = HEX.formatHex(Digests.sha1(b));
+ StringBuilder decimal = new StringBuilder(hash.length());
+ StringBuilder other = new StringBuilder(hash.length());
+ for (int i = 0; i < hash.length(); i++) {
+ char c = hash.charAt(i);
+ if (c >= '0' && c <= '9') {
+ decimal.append(c);
+ } else {
+ other.append((char) ('0' + (c - 'A')));
+ }
+ }
+ StringBuilder y = new StringBuilder(decimal).append(other);
+ if (y.length() < 16) {
+ throw new IllegalArgumentException("Option B: the SHA-1 hash yields fewer than 16 digits");
+ }
+ byte[] zl = HEX.parseHex(y.substring(0, 16));
+ byte[] zr = new byte[8];
+ for (int i = 0; i < 8; i++) {
+ zr[i] = (byte) (zl[i] ^ 0xff);
+ }
+ return adjustDesParity(concat(
+ Ciphers.tdes2Encrypt(zl, imk16),
+ Ciphers.tdes2Encrypt(zr, imk16)));
+ }
+
+ /**
+ * The EMV common session key (EMV 4.2 Book 2 Annex A1.3.1).
+ *
+ * Each half carries odd DES parity.
+ */
+ public static byte[] deriveSessionKey(byte[] mk16, byte[] atc) {
+ byte[] r = new byte[8];
+ System.arraycopy(atc, 0, r, 0, Math.min(2, atc.length));
+ return sessionKeyFromDiversifier(mk16, r);
+ }
+
+ /**
+ * The MasterCard proprietary session key derivation (M/Chip).
+ *
+ * Identical to the EMV common session key except for the 8-byte
+ * diversification input, which here is the low two bytes of the application
+ * transaction counter followed by the low four bytes of the terminal's
+ * unpredictable number, rather than the counter followed by zeros.
+ *
+ * Both halves still carry odd DES parity, as the MasterCard method
+ * requires.
+ *
+ * @param unpredictableNumber the terminal-generated unpredictable number; its
+ * low four bytes are used
+ */
+ public static byte[] deriveSessionKeyMastercard(byte[] mk16, byte[] atc,
+ byte[] unpredictableNumber) {
+ byte[] r = new byte[8];
+ // The LOW bytes, so an over-long counter or
+ // unpredictable number gives the same result on both sides.
+ int atcFrom = Math.max(0, atc.length - 2);
+ System.arraycopy(atc, atcFrom, r, 0, Math.min(2, atc.length));
+ int unFrom = Math.max(0, unpredictableNumber.length - 4);
+ System.arraycopy(unpredictableNumber, unFrom, r, 4, Math.min(4, unpredictableNumber.length));
+ return sessionKeyFromDiversifier(mk16, r);
+ }
+
+ /** The shared tail of both derivations: the 0xF0/0x0F halves, enciphered, parity adjusted. */
+ private static byte[] sessionKeyFromDiversifier(byte[] mk16, byte[] r) {
+ byte[] f1 = r.clone();
+ f1[2] = (byte) 0xf0;
+ byte[] f2 = r.clone();
+ f2[2] = (byte) 0x0f;
+ return adjustDesParity(concat(
+ Ciphers.tdes2Encrypt(f1, mk16),
+ Ciphers.tdes2Encrypt(f2, mk16)));
+ }
+
+ // ---- cryptograms --------------------------------------------------------
+
+ /** An ARQC together with the session key it was computed under. */
+ public static final class Arqc {
+ public final byte[] arqc;
+ public final byte[] sessionKey;
+
+ public Arqc(byte[] arqc, byte[] sessionKey) {
+ this.arqc = arqc;
+ this.sessionKey = sessionKey;
+ }
+ }
+
+ /**
+ * ARPC method 1: {@code 3DES_EDE(SK, ARQC XOR (ARC || 00*6))}.
+ *
+ * @param arcHex the authorization response code, right-padded to 8 bytes
+ */
+ public static byte[] computeArpcMethod1(byte[] sk, byte[] arqc, String arcHex) {
+ byte[] arc = HEX.parseHex(arcHex);
+ byte[] x = new byte[8];
+ System.arraycopy(arc, 0, x, 0, Math.min(8, arc.length));
+ return Ciphers.tdes2Encrypt(Ciphers.xor(arqc, x), sk);
+ }
+
+ /**
+ * ARPC method 2, the CSU-based one: the leftmost 4 bytes of the retail MAC
+ * over {@code ARQC || CSU || proprietary} under the session key.
+ *
+ * The response code belongs in the input of the first method. The second
+ * method has none: the card status update and the proprietary data are what
+ * it is made from, and EMV Book 2 section 8.2.2 says so.
+ *
+ * The request carries no way to ask for the other form: the model gives
+ * the card status update and the proprietary data, and nothing else.
+ */
+ public static byte[] computeArpcMethod2(byte[] sk, byte[] arqc,
+ String csuHex, String padHex) {
+ byte[] data = concat(
+ arqc,
+ csuHex == null ? new byte[0] : HEX.parseHex(csuHex),
+ padHex == null ? new byte[0] : HEX.parseHex(padHex));
+ return slice(retailMac(sk, data, Padding.METHOD2), 0, 4);
+ }
+
+ // ---- helpers ------------------------------------------------------------
+
+ /** PAN concatenated with PSN as packed BCD, left-zero-padded to an even nibble count. */
+ static byte[] packedBcd(String pan, String psn) {
+ String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn);
+ if (digits.isEmpty()) {
+ throw new IllegalArgumentException("PAN and PSN must contain digits");
+ }
+ if (digits.length() % 2 != 0) {
+ digits = "0" + digits;
+ }
+ return HEX.parseHex(digits);
+ }
+
+ /**
+ * The block the ICC master key is derived over: the rightmost sixteen digits of the PAN
+ * and the PAN sequence number, padded on the left with zeros when they are shorter.
+ */
+ private static byte[] masterKeyInput(String pan, String psn) {
+ String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn);
+ if (digits.isEmpty()) {
+ throw new IllegalArgumentException("PAN and PSN must contain digits");
+ }
+ if (digits.length() > 16) {
+ digits = digits.substring(digits.length() - 16);
+ }
+ while (digits.length() < 16) {
+ digits = "0" + digits;
+ }
+ return HEX.parseHex(digits);
+ }
+
+ private static byte[] slice(byte[] b, int from, int to) {
+ byte[] out = new byte[to - from];
+ System.arraycopy(b, from, out, 0, to - from);
+ return out;
+ }
+
+ private static byte[] concat(byte[]... parts) {
+ int n = 0;
+ for (byte[] p : parts) {
+ n += p.length;
+ }
+ byte[] out = new byte[n];
+ int at = 0;
+ for (byte[] p : parts) {
+ System.arraycopy(p, 0, out, at, p.length);
+ at += p.length;
+ }
+ return out;
+ }
+}
diff --git a/src/main/resources/aws/payment-cryptography-data-request-shapes.json b/src/main/resources/aws/payment-cryptography-data-request-shapes.json
index da514ff260..458680d7f9 100644
--- a/src/main/resources/aws/payment-cryptography-data-request-shapes.json
+++ b/src/main/resources/aws/payment-cryptography-data-request-shapes.json
@@ -12,7 +12,11 @@
"GeneratePinData": "GeneratePinDataInput",
"VerifyPinData": "VerifyPinDataInput",
"TranslatePinData": "TranslatePinDataInput",
- "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput"
+ "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput",
+ "GenerateCardValidationData": "GenerateCardValidationDataInput",
+ "VerifyCardValidationData": "VerifyCardValidationDataInput",
+ "GenerateAuthRequestCryptogram": "GenerateAuthRequestCryptogramInput",
+ "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput"
},
"shapes": {
"AmexAttributes": {
@@ -33,6 +37,26 @@
"CurrentPinAttributes": "CurrentPinAttributes"
}
},
+ "AmexCardSecurityCodeVersion1": {
+ "type": "structure",
+ "required": [
+ "CardExpiryDate"
+ ],
+ "members": {
+ "CardExpiryDate": "CardExpiryDateType"
+ }
+ },
+ "AmexCardSecurityCodeVersion2": {
+ "type": "structure",
+ "required": [
+ "CardExpiryDate",
+ "ServiceCode"
+ ],
+ "members": {
+ "CardExpiryDate": "CardExpiryDateType",
+ "ServiceCode": "ServiceCodeType"
+ }
+ },
"ApplicationCryptogramType": {
"type": "string",
"min": 16,
@@ -56,6 +80,76 @@
"PaddingType": "PaddingType"
}
},
+ "AuthRequestCryptogramType": {
+ "type": "string",
+ "min": 16,
+ "max": 16,
+ "pattern": "[0-9a-fA-F]+"
+ },
+ "CardExpiryDateType": {
+ "type": "string",
+ "min": 4,
+ "max": 4,
+ "pattern": "[0-9]+"
+ },
+ "CardGenerationAttributes": {
+ "type": "structure",
+ "members": {
+ "AmexCardSecurityCodeVersion1": "AmexCardSecurityCodeVersion1",
+ "AmexCardSecurityCodeVersion2": "AmexCardSecurityCodeVersion2",
+ "CardVerificationValue1": "CardVerificationValue1",
+ "CardVerificationValue2": "CardVerificationValue2",
+ "CardHolderVerificationValue": "CardHolderVerificationValue",
+ "DynamicCardVerificationCode": "DynamicCardVerificationCode",
+ "DynamicCardVerificationValue": "DynamicCardVerificationValue"
+ }
+ },
+ "CardHolderVerificationValue": {
+ "type": "structure",
+ "required": [
+ "UnpredictableNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "UnpredictableNumber": "HexLengthBetween2And8",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthBetween2And4"
+ }
+ },
+ "CardVerificationAttributes": {
+ "type": "structure",
+ "members": {
+ "AmexCardSecurityCodeVersion1": "AmexCardSecurityCodeVersion1",
+ "AmexCardSecurityCodeVersion2": "AmexCardSecurityCodeVersion2",
+ "CardVerificationValue1": "CardVerificationValue1",
+ "CardVerificationValue2": "CardVerificationValue2",
+ "CardHolderVerificationValue": "CardHolderVerificationValue",
+ "DynamicCardVerificationCode": "DynamicCardVerificationCode",
+ "DynamicCardVerificationValue": "DynamicCardVerificationValue",
+ "DiscoverDynamicCardVerificationCode": "DiscoverDynamicCardVerificationCode"
+ }
+ },
+ "CardVerificationValue1": {
+ "type": "structure",
+ "required": [
+ "CardExpiryDate",
+ "ServiceCode"
+ ],
+ "members": {
+ "CardExpiryDate": "CardExpiryDateType",
+ "ServiceCode": "ServiceCodeType"
+ }
+ },
+ "CardVerificationValue2": {
+ "type": "structure",
+ "required": [
+ "CardExpiryDate"
+ ],
+ "members": {
+ "CardExpiryDate": "CardExpiryDateType"
+ }
+ },
"CertificateType": {
"type": "string",
"min": 1,
@@ -74,6 +168,32 @@
"max": 1024,
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
},
+ "CryptogramAuthResponse": {
+ "type": "structure",
+ "members": {
+ "ArpcMethod1": "CryptogramVerificationArpcMethod1",
+ "ArpcMethod2": "CryptogramVerificationArpcMethod2"
+ }
+ },
+ "CryptogramVerificationArpcMethod1": {
+ "type": "structure",
+ "required": [
+ "AuthResponseCode"
+ ],
+ "members": {
+ "AuthResponseCode": "HexLengthEquals4"
+ }
+ },
+ "CryptogramVerificationArpcMethod2": {
+ "type": "structure",
+ "required": [
+ "CardStatusUpdate"
+ ],
+ "members": {
+ "CardStatusUpdate": "HexLengthEquals8",
+ "ProprietaryAuthenticationData": "ProprietaryAuthenticationDataType"
+ }
+ },
"CurrentPinAttributes": {
"type": "structure",
"required": [
@@ -115,6 +235,19 @@
"Mastercard": "MasterCardAttributes"
}
},
+ "DiscoverDynamicCardVerificationCode": {
+ "type": "structure",
+ "required": [
+ "CardExpiryDate",
+ "UnpredictableNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "CardExpiryDate": "CardExpiryDateType",
+ "UnpredictableNumber": "HexLengthBetween2And8",
+ "ApplicationTransactionCounter": "HexLengthBetween2And4"
+ }
+ },
"DukptAttributes": {
"type": "structure",
"required": [
@@ -175,6 +308,36 @@
"RESPONSE"
]
},
+ "DynamicCardVerificationCode": {
+ "type": "structure",
+ "required": [
+ "UnpredictableNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter",
+ "TrackData"
+ ],
+ "members": {
+ "UnpredictableNumber": "HexLengthBetween2And8",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthBetween2And4",
+ "TrackData": "TrackDataType"
+ }
+ },
+ "DynamicCardVerificationValue": {
+ "type": "structure",
+ "required": [
+ "PanSequenceNumber",
+ "CardExpiryDate",
+ "ServiceCode",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "CardExpiryDate": "CardExpiryDateType",
+ "ServiceCode": "ServiceCodeType",
+ "ApplicationTransactionCounter": "HexLengthBetween2And4"
+ }
+ },
"EcdhDerivationAttributes": {
"type": "structure",
"required": [
@@ -303,6 +466,35 @@
"OFB"
]
},
+ "GenerateAuthRequestCryptogramInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "TransactionData",
+ "MajorKeyDerivationMode",
+ "SessionKeyDerivationAttributes"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "TransactionData": "TransactionDataType",
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "SessionKeyDerivationAttributes": "SessionKeyDerivation"
+ }
+ },
+ "GenerateCardValidationDataInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "PrimaryAccountNumber",
+ "GenerationAttributes"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "GenerationAttributes": "CardGenerationAttributes",
+ "ValidationDataLength": "IntegerRangeBetween3And5Type"
+ }
+ },
"GenerateMacEmvPinChangeInput": {
"type": "structure",
"required": [
@@ -368,6 +560,18 @@
"max": 24,
"pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{20}|[0-9a-fA-F]{24})"
},
+ "HexLengthBetween2And4": {
+ "type": "string",
+ "min": 2,
+ "max": 4,
+ "pattern": "[0-9a-fA-F]+"
+ },
+ "HexLengthBetween2And8": {
+ "type": "string",
+ "min": 2,
+ "max": 8,
+ "pattern": "[0-9a-fA-F]+"
+ },
"HexLengthEquals1": {
"type": "string",
"min": 1,
@@ -380,6 +584,12 @@
"max": 4,
"pattern": "[0-9a-fA-F]+"
},
+ "HexLengthEquals8": {
+ "type": "string",
+ "min": 8,
+ "max": 8,
+ "pattern": "[0-9a-fA-F]+"
+ },
"Ibm3624NaturalPin": {
"type": "structure",
"required": [
@@ -462,6 +672,11 @@
"min": 0,
"max": 6
},
+ "IntegerRangeBetween3And5Type": {
+ "type": "integer",
+ "min": 3,
+ "max": 5
+ },
"IntegerRangeBetween4And12": {
"type": "integer",
"min": 4,
@@ -683,6 +898,12 @@
"max": 19,
"pattern": "[0-9]+"
},
+ "ProprietaryAuthenticationDataType": {
+ "type": "string",
+ "min": 1,
+ "max": 16,
+ "pattern": "[0-9a-fA-F]+"
+ },
"ReEncryptDataInput": {
"type": "structure",
"required": [
@@ -710,12 +931,40 @@
"Dukpt": "DukptEncryptionAttributes"
}
},
+ "ServiceCodeType": {
+ "type": "string",
+ "min": 3,
+ "max": 3,
+ "pattern": "[0-9]+"
+ },
"SessionDerivationDataType": {
"type": "string",
"min": 16,
"max": 16,
"pattern": "[0-9a-fA-F]+"
},
+ "SessionKeyAmex": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2"
+ }
+ },
+ "SessionKeyDerivation": {
+ "type": "structure",
+ "members": {
+ "EmvCommon": "SessionKeyEmvCommon",
+ "Mastercard": "SessionKeyMastercard",
+ "Emv2000": "SessionKeyEmv2000",
+ "Amex": "SessionKeyAmex",
+ "Visa": "SessionKeyVisa",
+ "UnionPay": "SessionKeyUnionPay"
+ }
+ },
"SessionKeyDerivationMode": {
"type": "string",
"enum": [
@@ -734,6 +983,71 @@
"ApplicationTransactionCounter": "HexLengthEquals4"
}
},
+ "SessionKeyEmv2000": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4"
+ }
+ },
+ "SessionKeyEmvCommon": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4"
+ }
+ },
+ "SessionKeyMastercard": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter",
+ "UnpredictableNumber"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4",
+ "UnpredictableNumber": "HexLengthEquals8"
+ }
+ },
+ "SessionKeyUnionPay": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4"
+ }
+ },
+ "SessionKeyVisa": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber",
+ "PanSequenceNumber"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2"
+ }
+ },
"SharedInformation": {
"type": "string",
"min": 2,
@@ -777,12 +1091,24 @@
"max": 9984,
"pattern": "[0-9a-zA-Z]+"
},
+ "TrackDataType": {
+ "type": "string",
+ "min": 2,
+ "max": 160,
+ "pattern": "[0-9a-fA-F]+"
+ },
"TransactionAmountType": {
"type": "string",
"min": 12,
"max": 12,
"pattern": "[0-9]+"
},
+ "TransactionDataType": {
+ "type": "string",
+ "min": 2,
+ "max": 1024,
+ "pattern": "[0-9a-fA-F]+"
+ },
"TranslatePinDataInput": {
"type": "structure",
"required": [
@@ -837,12 +1163,51 @@
"type": "structure",
"members": {}
},
+ "ValidationDataType": {
+ "type": "string",
+ "min": 3,
+ "max": 5,
+ "pattern": "[0-9]+"
+ },
"VerificationValueType": {
"type": "string",
"min": 4,
"max": 12,
"pattern": "[0-9]+"
},
+ "VerifyAuthRequestCryptogramInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "TransactionData",
+ "AuthRequestCryptogram",
+ "MajorKeyDerivationMode",
+ "SessionKeyDerivationAttributes"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "TransactionData": "TransactionDataType",
+ "AuthRequestCryptogram": "AuthRequestCryptogramType",
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "SessionKeyDerivationAttributes": "SessionKeyDerivation",
+ "AuthResponseAttributes": "CryptogramAuthResponse"
+ }
+ },
+ "VerifyCardValidationDataInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "PrimaryAccountNumber",
+ "VerificationAttributes",
+ "ValidationData"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "VerificationAttributes": "CardVerificationAttributes",
+ "ValidationData": "ValidationDataType"
+ }
+ },
"VerifyMacInput": {
"type": "structure",
"required": [
diff --git a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java
index f4c8507814..2eba5b20fd 100644
--- a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java
+++ b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java
@@ -96,6 +96,18 @@ class PaymentCryptographyDataPlaneIamRouteTest {
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
}
+ @Test
+ void theCardOperationsResolveToTheirActions() {
+ assertEquals("payment-cryptography:GenerateCardValidationData",
+ resolve("/_paymentcryptography/cardvalidationdata/generate"));
+ assertEquals("payment-cryptography:VerifyCardValidationData",
+ resolve("/_paymentcryptography/cardvalidationdata/verify"));
+ assertEquals("payment-cryptography:GenerateAuthRequestCryptogram",
+ resolve("/_paymentcryptography/cryptogram/generate"));
+ assertEquals("payment-cryptography:VerifyAuthRequestCryptogram",
+ resolve("/_paymentcryptography/cryptogram/verify"));
+ }
+
/** The action the registry resolves for a POST to the path, for the service's scope. */
private String resolve(String path) {
return resolve("payment-cryptography", path);
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java
new file mode 100644
index 0000000000..1bd1ac8077
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java
@@ -0,0 +1,485 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+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.paymentcryptography.crypto.EmvCrypto;
+import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import java.util.HexFormat;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The authorization request cryptograms.
+ *
+ * The derivations in the first test are the emulator's, and the emulator checks them
+ * against an independent implementation: the ICC master key, the session key that
+ * comes from it, and the ARQC of a
+ * transaction.
+ */
+class PaymentCryptographyAuthCryptogramOperationsTest {
+
+ /** The hexadecimal the data plane's blobs are written in. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
+ private static final String PAN = "4111111111111111";
+ /** The PAN sequence number, which the model states is two digits. */
+ private static final String PSN = "01";
+ /** The application transaction counter, which the model states is two bytes. */
+ private static final String ATC = "0001";
+ /**
+ * The transaction data the cryptogram is computed over.
+ *
+ * The user guide tells the caller to pad the transaction data before sending
+ * it, because the card padded it the same way before it enciphered it. The
+ * data here is padded that way: a whole number of eight-byte blocks, with the
+ * {@code 80} and the zeros that method 2 appends.
+ */
+ /**
+ * Another transaction's data, of the same shape as the one above.
+ *
+ * The amount differs, so the cryptogram over it differs, and the data is still
+ * a whole number of eight-byte blocks.
+ */
+ private static final String ANOTHER_TRANSACTION_DATA =
+ "00000000180000000000000008400080008000084016051700000000093800000B1F2201"
+ + "030000000000000000000000000000000000000000000000000000008000000000000000";
+
+ private static final String TRANSACTION_DATA =
+ "00000000170000000000000008400080008000084016051700000000093800000B1F2201"
+ + "030000000000000000000000000000000000000000000000000000008000000000000000";
+
+ private PaymentCryptographyService service;
+ private PaymentCryptographyAuthCryptogramOperations cryptogram;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @BeforeEach
+ void setUp() {
+ service = new PaymentCryptographyService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"));
+ cryptogram = new PaymentCryptographyAuthCryptogramOperations(service);
+ }
+
+ /** The session key derivation attributes of the EMV common variant. */
+ /** The attributes of the EMV 4.1 tree derivation, which this service refuses. */
+ private static JsonNode emv2000() {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode value = mapper.createObjectNode();
+ value.put("PrimaryAccountNumber", PAN);
+ value.put("PanSequenceNumber", PSN);
+ value.put("ApplicationTransactionCounter", ATC);
+ ObjectNode outer = mapper.createObjectNode();
+ outer.set("Emv2000", value);
+ return outer;
+ }
+
+ private static JsonNode emvCommon() {
+ return emvCommon(PAN);
+ }
+
+ /** The session key derivation attributes of the EMV common variant, for an account number. */
+ private static JsonNode emvCommon(String pan) {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode value = mapper.createObjectNode();
+ value.put("PrimaryAccountNumber", pan);
+ value.put("PanSequenceNumber", PSN);
+ value.put("ApplicationTransactionCounter", ATC);
+ ObjectNode outer = mapper.createObjectNode();
+ outer.set("EmvCommon", value);
+ return outer;
+ }
+
+ @Test
+ void anAccountNumberShorterThanTheFieldIsRead() {
+ PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
+
+ // The model lets the account number be twelve digits, and the derivation reads the
+ // rightmost sixteen digits of it and the sequence number, so it is read rather than
+ // refused.
+ Map The values in the first test are the emulator's, and the emulator checks them against
+ * an independent implementation: the card verification value of an account number,
+ * an expiry and a service code.
+ */
+class PaymentCryptographyCardValidationOperationsTest {
+
+ private static final String PAN = "5081470082639564";
+ private static final String EXPIRY = "3003";
+ private static final String CVK = "0123456789ABCDEFFEDCBA9876543210";
+
+ private PaymentCryptographyService service;
+ private PaymentCryptographyCardValidationOperations cardValidation;
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @BeforeEach
+ void setUp() {
+ service = new PaymentCryptographyService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"));
+ cardValidation = new PaymentCryptographyCardValidationOperations(service);
+ }
+
+ /** The attributes of a card verification value: the expiry and the service code. */
+ private static JsonNode cardVerificationValue1(String expiry, String serviceCode) {
+ ObjectMapper mapper = new ObjectMapper();
+ ObjectNode value = mapper.createObjectNode();
+ value.put("CardExpiryDate", expiry);
+ value.put("ServiceCode", serviceCode);
+ ObjectNode outer = mapper.createObjectNode();
+ outer.set("CardVerificationValue1", value);
+ return outer;
+ }
+
+ @Test
+ void theCardVerificationValueIsTheOneTheStandardGives() {
+ assertEquals("131", CvvCrypto.computeCvv(PAN, EXPIRY, "201", CVK, 3));
+ assertEquals("886", CvvCrypto.computeCvv(PAN, EXPIRY, "000", CVK, 3));
+ assertEquals("660", CvvCrypto.computeCvv(PAN, EXPIRY, "999", CVK, 3));
+ }
+
+ @Test
+ void aGeneratedValueVerifies() {
+ PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
+ "Generate", "Verify");
+
+ Map A key and a request are built the same way whichever operation is under test, so
+ * they are built here once. A change to how they are built is then a change in one
+ * place.
+ */
+final class PaymentCryptographyTestFixtures {
+
+ private PaymentCryptographyTestFixtures() {
+ }
+
+ /**
+ * A key of the algorithm and the usage, with the modes of use the test names.
+ *
+ * @param service the service the key is made in
+ * @param algorithm the key's algorithm
+ * @param usage the key's usage
+ * @param modes the modes of use the key allows
+ * @return the key that was made
+ */
+ static PaymentCryptographyKey createKey(PaymentCryptographyService service, String algorithm,
+ String usage, String... modes) {
+ return key(service, algorithm, usage, true, modes);
+ }
+
+ /**
+ * A key that was made disabled, and may therefore not be used.
+ *
+ * @param service the service the key is made in
+ * @param algorithm the key's algorithm
+ * @param usage the key's usage
+ * @param modes the modes of use the key allows
+ * @return the key that was made
+ */
+ static PaymentCryptographyKey createDisabledKey(PaymentCryptographyService service, String algorithm,
+ String usage, String... modes) {
+ return key(service, algorithm, usage, false, modes);
+ }
+
+ private static PaymentCryptographyKey key(PaymentCryptographyService service, String algorithm,
+ String usage, boolean enabled, String... modes) {
+ Map The dynamic value is the one the Visa Contactless Payment Specification describes: the
+ * leftmost four digits of the account number are replaced by the transaction counter, and
+ * the result, the expiry and the service code are enciphered under the card's unique
+ * derived key. The expected value is computed here from the specification's own steps,
+ * with the cipher written out, so that a change to the service is a change against the
+ * specification rather than against itself.
+ */
+class CvvCryptoTest {
+
+ /** The issuer master key the unique derived key is derived from. */
+ private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
+
+ /** The account number of the card. */
+ private static final String PAN = "5081470082639564";
+
+ /** The expiry of the card, in the YYMM form the request carries. */
+ private static final String EXPIRY = "3003";
+
+ /** The service code of the value. */
+ private static final String SERVICE_CODE = "201";
+
+ /** The transaction counter, in the binary coded decimal the track data carries. */
+ private static final String ATC = "0001";
+
+ /** The PAN sequence number, which the unique derived key is derived with. */
+ private static final String PSN = "01";
+
+ @Test
+ void theDynamicValueIsTheOneTheSpecificationGives() {
+ assertEquals(dcvv(), CvvCrypto.computeDynamicValue(
+ PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3));
+ }
+
+ @Test
+ void theDynamicValueIsNotTheStaticValue() {
+ // The counter is inserted into the account number, so the value is bound to the
+ // transaction and is not the value of the card's fields.
+ assertEquals(false, CvvCrypto.computeDynamicValue(
+ PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3)
+ .equals(CvvCrypto.computeCvv(PAN, EXPIRY, SERVICE_CODE, IMK, 3)));
+ }
+
+ /**
+ * The dynamic value, written from the specification's steps.
+ *
+ * The ICC master key is the one EMV 4.4 Book 2 Annex A1.4.1 Option A gives, and the
+ * Visa Integrated Circuit Card Specification states the same rule. The session keys and the
+ * cryptogram are the worked examples of the M/Chip Card Application Cryptographic
+ * Algorithms: the MasterCard proprietary derivation and the common one, with the application
+ * cryptogram each produces over the same data.
+ */
+class EmvCryptoTest {
+
+ /** The issuer master key of the published ICC master key vector. */
+ private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
+
+ /** The account number of the published ICC master key vector. */
+ private static final String PAN = "4111111111111111";
+
+ /** The sequence number of the published ICC master key vector. */
+ private static final String PSN = "00";
+
+ /** The ICC master key the published vector gives. */
+ private static final String UDK = "31089464674C73EC851A6E0737029D19";
+
+ /** The AC master key of the M/Chip worked examples. */
+ private static final String MKAC = "08DF34253220A720EFF2C1343852E63D";
+
+ /** The application transaction counter of the M/Chip worked examples. */
+ private static final String ATC = "3456";
+
+ /** The terminal unpredictable number of the M/Chip worked examples. */
+ private static final String UN = "11111111";
+
+ /** The data the M/Chip worked examples compute the application cryptogram over. */
+ private static final String CDOL = """
+ 00 00 00 01 00 00 00 00 00 00 10 00 08 40 00 00
+ 00 10 80 08 40 98 07 04 00 11 11 11 11 58 00 34
+ 56 03 A4 00 20""";
+
+ /** The application cryptogram the M/Chip worked example gives. */
+ private static final String ARQC = "DBC1E0B820FFE7DB";
+
+ /** The common session key the M/Chip worked example gives. */
+ private static final String COMMON_SESSION_KEY = "182025BA4FAB32F5A63A1BA5E6845D4E";
+
+ @Test
+ void theIccMasterKeyIsTheOneTheStandardGives() {
+ assertEquals(UDK, hex(EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN)));
+ }
+
+ @Test
+ void aShortAccountNumberIsPaddedOnTheLeft() {
+ // The block is the rightmost sixteen digits of the account number and the sequence
+ // number, padded on the left with zeros when they are shorter. So an account number
+ // that is two digits short of the field derives the key that the same number with
+ // those two zeros derives.
+ String shortNumber = "411111111111";
+ String paddedNumber = "00" + shortNumber;
+
+ assertArrayEquals(EmvCrypto.deriveIccMasterKey(hex(IMK), paddedNumber, "01"),
+ EmvCrypto.deriveIccMasterKey(hex(IMK), shortNumber, "01"));
+ }
+
+ @Test
+ void theMasterCardSessionKeyAndCryptogramAreTheOnesTheDocumentGives() {
+ byte[] sessionKey = EmvCrypto.deriveSessionKeyMastercard(hex(MKAC), hex(ATC), hex(UN));
+
+ assertEquals(ARQC, hex(EmvCrypto.retailMac(sessionKey, hex(CDOL), EmvCrypto.Padding.METHOD2)));
+ }
+
+ @Test
+ void theCommonSessionKeyIsTheOneTheDocumentGives() {
+ byte[] sessionKey = EmvCrypto.deriveSessionKey(hex(MKAC), hex(ATC));
+
+ // The document does not force the parity of the derived key, and the derivation does
+ // not affect the computation, so the parity bits are masked on both sides.
+ assertEquals(withoutParity(COMMON_SESSION_KEY), withoutParity(hex(sessionKey)));
+ }
+
+ /** The bytes of a hexadecimal string, the spaces and the line breaks in it ignored. */
+ private static byte[] hex(String value) {
+ return HexFormat.of().parseHex(value.replaceAll("\\s", ""));
+ }
+
+ /** The hexadecimal of the bytes, in the case the documents print them. */
+ private static String hex(byte[] value) {
+ return HexFormat.of().withUpperCase().formatHex(value);
+ }
+
+ /** The key with the DES parity bits masked, which the derivation does not affect. */
+ private static String withoutParity(String key) {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < key.length(); i += 2) {
+ sb.append(String.format("%02X", Integer.parseInt(key.substring(i, i + 2), 16) & 0xFE));
+ }
+ return sb.toString();
+ }
+}
diff --git a/tools/aws/regen_payment_cryptography_data_shapes.py b/tools/aws/regen_payment_cryptography_data_shapes.py
index 3ac1978324..f7d8a45633 100644
--- a/tools/aws/regen_payment_cryptography_data_shapes.py
+++ b/tools/aws/regen_payment_cryptography_data_shapes.py
@@ -27,6 +27,8 @@ OPERATIONS = (
"EncryptData", "DecryptData", "ReEncryptData",
"GenerateMac", "VerifyMac",
"GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange",
+ "GenerateCardValidationData", "VerifyCardValidationData",
+ "GenerateAuthRequestCryptogram", "VerifyAuthRequestCryptogram",
)
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index 44f0fcdb70..f1c789b652 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -42,6 +42,7 @@ services:
sources:
- { path: services/paymentcryptography/PaymentCryptographyCryptoController.java, mode: rest }
- { path: services/paymentcryptography/PaymentCryptographyPinController.java, mode: rest }
+ - { path: services/paymentcryptography/PaymentCryptographyCardController.java, mode: rest }
exclude_actions:
- GenerateMacEmvPinChange
- service: applicationautoscaling
+ * data = (PAN || expiry || serviceCode), right-padded with '0' to 32 hex
+ * B1, B2 = the two 8-byte blocks
+ * r = 3DES_EDE(CVK, DES_e(B1, CVK-A) XOR B2) with CVK = CVK-A || CVK-B
+ * value = decimalize(r, 3)
+ *
+ */
+public final class CvvCrypto {
+
+ /** The hexadecimal the data plane's blobs are written in. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ private CvvCrypto() {
+ }
+
+ /** Compute the 3-digit card verification value. {@code cvkHex} is CVK-A || CVK-B. */
+ public static String computeCvv(String pan, String expiryYYMM, String serviceCode,
+ String cvkHex, int length) {
+ byte[] cvk = HEX.parseHex(cvkHex);
+ if (cvk.length != 16) {
+ throw new IllegalArgumentException("CVK must be 16 bytes (32 hex)");
+ }
+ return decimalize(PinCrypto.digits(pan) + PinCrypto.digits(expiryYYMM)
+ + PinCrypto.digits(serviceCode), cvk, length);
+ }
+
+ /**
+ * The dynamic card verification value (dCVV).
+ *
+ *
+ * altered PAN = the leftmost four digits of the PAN replaced by the counter
+ * r = 3DES_EDE(UDK, DES_e(B1, UDK-A) XOR B2) over altered PAN || expiry || service code
+ * value = decimalize(r, 3)
+ *
+ *
+ *
+ * 1. ICC master key derivation (EMV Book 2, Option A) IMK + PAN + PSN -> MK
+ * 2. Common session key derivation (EMV Book 2 A1.3.1) MK + ATC -> SK
+ * 3. ARQC = ISO 9797-1 MAC algorithm 3 over the transaction data, truncated to 8 bytes
+ * 4. ARPC method 1 = 3DES_EDE(SK, ARQC XOR (ARC || 00*6))
+ *
+ *
+ *
+ * H_i = E_KL(D_i XOR H_{i-1}) for i = 1..n
+ * MAC = E_KL(D_KR(H_n))
+ *
+ *
+ *
+ * Y = the RIGHT-MOST 16 digits of PAN || PSN, left-padded with zeros when shorter
+ * ZR = Y XOR FF..FF
+ * MK = 3DES(IMK, Y) || 3DES(IMK, ZR), odd parity adjusted
+ *
+ *
+ *
+ * H = SHA-1(PAN || PSN as packed BCD)
+ * Y = the leftmost 16 digits of {H's decimal digits || H's other nibbles mod 10}
+ * MK = 3DES(IMK, Y) || 3DES(IMK, Y XOR FF..FF)
+ *
+ *
+ *
+ * F1 = ATC(2) || F0 || 00*5 SK_L = 3DES(MK, F1)
+ * F2 = ATC(2) || 0F || 00*5 SK_R = 3DES(MK, F2)
+ *
+ *
+ *
+ *
+ */
+ private static String dcvv() {
+ String data = ATC + PAN.substring(4) + EXPIRY + SERVICE_CODE;
+ while (data.length() < 32) {
+ data = data + "0";
+ }
+ byte[] left = hex(data.substring(0, 16));
+ byte[] right = hex(data.substring(16, 32));
+ byte[] udk = EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN);
+
+ byte[] block = singleDes(left, udk, 0, false);
+ block = xor(block, right);
+ block = singleDes(block, udk, 0, false);
+ block = singleDes(block, udk, 8, true);
+ block = singleDes(block, udk, 0, false);
+
+ StringBuilder digits = new StringBuilder();
+ StringBuilder letters = new StringBuilder();
+ for (byte b : block) {
+ for (int nibble : new int[]{(b >> 4) & 0xf, b & 0xf}) {
+ if (nibble < 10) {
+ digits.append((char) ('0' + nibble));
+ } else {
+ letters.append((char) ('0' + nibble - 10));
+ }
+ }
+ }
+ return digits.append(letters).substring(0, 3);
+ }
+
+ /** One block of Single DES, with the first or the second half of the double length key. */
+ private static byte[] singleDes(byte[] block, byte[] key16, int half, boolean decrypt) {
+ byte[] key = new byte[8];
+ System.arraycopy(key16, half, key, 0, 8);
+ try {
+ Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
+ cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE,
+ new SecretKeySpec(key, "DES"));
+ return cipher.doFinal(block);
+ } catch (Exception e) {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /** The exclusive-or of two byte arrays of the same length. */
+ private static byte[] xor(byte[] a, byte[] b) {
+ byte[] out = new byte[a.length];
+ for (int i = 0; i < a.length; i++) {
+ out[i] = (byte) (a[i] ^ b[i]);
+ }
+ return out;
+ }
+
+ /** The bytes of a hexadecimal string. */
+ private static byte[] hex(String value) {
+ return HexFormat.of().parseHex(value);
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java
new file mode 100644
index 0000000000..276388beab
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/EmvCryptoTest.java
@@ -0,0 +1,106 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.HexFormat;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * The EMV derivations, against the vectors the specifications publish.
+ *
+ *