diff --git a/compatibility-tests/sdk-test-awscli/README.md b/compatibility-tests/sdk-test-awscli/README.md index 45916328ad..d2a9f83cdb 100644 --- a/compatibility-tests/sdk-test-awscli/README.md +++ b/compatibility-tests/sdk-test-awscli/README.md @@ -21,6 +21,7 @@ Tests are plain bash scripts that call `aws` CLI commands with `--endpoint-url` | `cognito` | User pools, clients | | `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 | ## Requirements diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-pin.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-pin.bats new file mode 100644 index 0000000000..206e8002fa --- /dev/null +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-pin.bats @@ -0,0 +1,182 @@ +#!/usr/bin/env bats +# Payment Cryptography PIN operation tests +# +# The PIN 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' + PEK_ARN="" + PVK_ARN="" + AES_PEK_ARN="" +} + +teardown() { + for key in "$PEK_ARN" "$PVK_ARN" "$AES_PEK_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 PIN encryption usage, for the block that protects the PIN. +create_pek() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_P0_PIN_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +# A key of the Visa PIN verification usage, for the verification value. +create_pvk() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_V2_VISA_PIN_VERIFICATION_KEY,KeyModesOfUse={Generate=true,Verify=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +@test "Payment Cryptography PIN: a PIN is generated and verifies" { + PEK_ARN=$(create_pek) + [ -n "$PEK_ARN" ] + PVK_ARN=$(create_pvk) + [ -n "$PVK_ARN" ] + + run aws_cmd payment-cryptography-data generate-pin-data \ + --encryption-key-identifier "$PEK_ARN" \ + --generation-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'VisaPin={PinVerificationKeyIndex=1}' + assert_success + BLOCK=$(json_get "$output" '.EncryptedPinBlock') + [ -n "$BLOCK" ] + PVV=$(json_get "$output" '.PinData.VerificationValue') + [ -n "$PVV" ] + + run aws_cmd payment-cryptography-data verify-pin-data \ + --encryption-key-identifier "$PEK_ARN" \ + --verification-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --encrypted-pin-block "$BLOCK" \ + --verification-attributes "VisaPin={PinVerificationKeyIndex=1,VerificationValue=$PVV}" + assert_success +} + +@test "Payment Cryptography PIN: a PIN that does not verify is refused" { + PEK_ARN=$(create_pek) + [ -n "$PEK_ARN" ] + PVK_ARN=$(create_pvk) + [ -n "$PVK_ARN" ] + + run aws_cmd payment-cryptography-data generate-pin-data \ + --encryption-key-identifier "$PEK_ARN" \ + --generation-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'VisaPin={PinVerificationKeyIndex=1}' + assert_success + BLOCK=$(json_get "$output" '.EncryptedPinBlock') + + # The verification value is not the one over the PIN, so the verification fails. + run aws_cmd payment-cryptography-data verify-pin-data \ + --encryption-key-identifier "$PEK_ARN" \ + --verification-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --encrypted-pin-block "$BLOCK" \ + --verification-attributes 'VisaPin={PinVerificationKeyIndex=1,VerificationValue=9999}' + assert_failure + # A PIN that does not verify is a verification that failed, not a malformed request. + [[ "$output" == *"VerificationFailedException"* ]] +} + +@test "Payment Cryptography PIN: a PIN block translates from one format to another" { + PEK_ARN=$(create_pek) + [ -n "$PEK_ARN" ] + PVK_ARN=$(create_pvk) + [ -n "$PVK_ARN" ] + + # The format 4 block is protected by an AES key and holds the whole account number. + run aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=AES_128,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_P0_PIN_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text + assert_success + AES_PEK_ARN="$output" + [ -n "$AES_PEK_ARN" ] + + run aws_cmd payment-cryptography-data generate-pin-data \ + --encryption-key-identifier "$AES_PEK_ARN" \ + --generation-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_4 \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'VisaPin={PinVerificationKeyIndex=1}' + assert_success + BLOCK=$(json_get "$output" '.EncryptedPinBlock') + + run aws_cmd payment-cryptography-data translate-pin-data \ + --encrypted-pin-block "$BLOCK" \ + --incoming-key-identifier "$AES_PEK_ARN" \ + --outgoing-key-identifier "$PEK_ARN" \ + --incoming-translation-attributes 'IsoFormat4={PrimaryAccountNumber=5081470082639564}' \ + --outgoing-translation-attributes 'IsoFormat0={PrimaryAccountNumber=5081470082639564}' + assert_success + TRANSLATED=$(json_get "$output" '.PinBlock') + [ -n "$TRANSLATED" ] + # The answer names the key the block is enciphered under. + [ "$(json_get "$output" '.KeyArn')" = "$PEK_ARN" ] +} + +@test "Payment Cryptography PIN: a key that may not encrypt is refused" { + # A PIN encryption key that may only decrypt does not encrypt a PIN block. + run aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_P0_PIN_ENCRYPTION_KEY,KeyModesOfUse={Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text + assert_success + READ_ONLY_ARN="$output" + [ -n "$READ_ONLY_ARN" ] + + PVK_ARN=$(create_pvk) + [ -n "$PVK_ARN" ] + + run aws_cmd payment-cryptography-data generate-pin-data \ + --encryption-key-identifier "$READ_ONLY_ARN" \ + --generation-key-identifier "$PVK_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'VisaPin={PinVerificationKeyIndex=1}' + assert_failure + + aws_cmd payment-cryptography delete-key --key-identifier "$READ_ONLY_ARN" \ + --delete-key-in-days 7 >/dev/null 2>&1 || true +} + +@test "Payment Cryptography PIN: a verification key of another usage is refused" { + PEK_ARN=$(create_pek) + [ -n "$PEK_ARN" ] + + # The Visa verification value is computed under a Visa PIN 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_P1_PIN_GENERATION_KEY,KeyModesOfUse={Generate=true,Verify=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text + assert_success + WRONG_USAGE_ARN="$output" + [ -n "$WRONG_USAGE_ARN" ] + + run aws_cmd payment-cryptography-data generate-pin-data \ + --encryption-key-identifier "$PEK_ARN" \ + --generation-key-identifier "$WRONG_USAGE_ARN" \ + --pin-block-format ISO_FORMAT_0 \ + --primary-account-number "5081470082639564" \ + --generation-attributes 'VisaPin={PinVerificationKeyIndex=1}' + assert_failure + + aws_cmd payment-cryptography delete-key --key-identifier "$WRONG_USAGE_ARN" \ + --delete-key-in-days 7 >/dev/null 2>&1 || true +} diff --git a/compatibility-tests/sdk-test-java/README.md b/compatibility-tests/sdk-test-java/README.md index 69c057cf38..8de8657252 100644 --- a/compatibility-tests/sdk-test-java/README.md +++ b/compatibility-tests/sdk-test-java/README.md @@ -2,7 +2,7 @@ Compatibility tests for [Floci](https://github.com/hectorvent/floci) using the **AWS SDK for Java v2 (2.31.8)**. -Runs 352 tests across 17 test classes against a live Floci instance — no mocks. +Runs 2981 tests across 436 test classes against a live Floci instance — no mocks. ## Services Covered @@ -26,6 +26,8 @@ Runs 352 tests across 17 test classes against a live Floci instance — no mocks | `Ec2Tests` | EC2 instances, VPCs, security groups, subnets | | `AppSyncTest` | GraphQL API CRUDL, data sources, resolvers, functions, types, API keys, tags, schema validation | | `EcsTests` | ECS clusters, task definitions, services | +| `PaymentCryptographyDataPlaneTest` | Payment Cryptography data plane: encrypt, decrypt, MAC | +| `PaymentCryptographyPinTest` | Payment Cryptography PIN operations: generate, verify, translate | ## Adding a New Test diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java new file mode 100644 index 0000000000..e840b10002 --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyPinTest.java @@ -0,0 +1,209 @@ +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.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.GeneratePinDataResponse; +import software.amazon.awssdk.services.paymentcryptographydata.model.PinBlockFormatForPinData; +import software.amazon.awssdk.services.paymentcryptographydata.model.PinData; +import software.amazon.awssdk.services.paymentcryptographydata.model.PinGenerationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.PinVerificationAttributes; +import software.amazon.awssdk.services.paymentcryptographydata.model.TranslationIsoFormats; +import software.amazon.awssdk.services.paymentcryptographydata.model.TranslationPinDataIsoFormat034; +import software.amazon.awssdk.services.paymentcryptographydata.model.ValidationException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VerificationFailedException; +import software.amazon.awssdk.services.paymentcryptographydata.model.VisaPin; +import software.amazon.awssdk.services.paymentcryptographydata.model.VisaPinVerification; + +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@DisplayName("Payment Cryptography PIN operations") +class PaymentCryptographyPinTest { + + /** The account number the PIN belongs to. */ + private static final String PAN = "5081470082639564"; + + /** The index of the verification key the PVV is computed under. */ + private static final int VERIFICATION_KEY_INDEX = 1; + + private static PaymentCryptographyDataClient client; + private static String pinEncryptionKeyArn; + private static String visaVerificationKeyArn; + + @BeforeAll + static void setup() { + client = TestFixtures.paymentCryptographyDataClient(); + // A PIN block is protected by a PIN encryption key, and the verification value is + // computed under a Visa PIN verification key, which is a key of its own. + pinEncryptionKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY, m -> m.encrypt(true).decrypt(true)); + visaVerificationKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY, + KeyUsage.TR31_V2_VISA_PIN_VERIFICATION_KEY, m -> m.generate(true).verify(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 data plane's requests name what they want in an attributes member, and the
+ * attributes member holds one variant: the algorithms a MAC may use, the formats a PIN
+ * block may be in, and the key a DUKPT derivation is made from. Reading them is the same
+ * whatever the operation is, so it is read in one place.
+ */
+final class PaymentCryptographyAttributes {
+
+ private PaymentCryptographyAttributes() {
+ }
+
+ /**
+ * The text of a member, or the empty string when the member is not there.
+ *
+ * @param request the request or the attributes to read
+ * @param member the member to read
+ * @return the member's text
+ */
+ static String text(JsonNode request, String member) {
+ if (request == null) {
+ return "";
+ }
+ JsonNode declared = request.get(member);
+ return declared == null || declared.isNull() ? "" : declared.asText("");
+ }
+
+ /**
+ * The one variant an attributes member holds.
+ *
+ * An attributes member holds exactly one variant, so a member with none or with two
+ * is a request that cannot be read.
+ *
+ * @param attributes the attributes to read
+ * @return the variant's name, or null when there is not exactly one
+ */
+ static String soleVariant(JsonNode attributes) {
+ if (attributes == null || !attributes.isObject()) {
+ return null;
+ }
+ String found = null;
+ Iterator The key record knows its algorithm, so the family is read from there and not guessed
- * from the length of the material: a sixteen-byte key is a two-key Triple DES one and an
- * AES-128 one.
- */
- private static boolean isAes(PaymentCryptographyKey key) {
- return PaymentCryptographyService.isAes(key);
- }
-
- /**
- * Whether the key is a Triple DES one.
- *
- * The reference ciphers with AES and with Triple DES, and the block and the vector follow
- * the key's family: sixteen bytes and a sixteen-byte vector for AES, eight for Triple DES.
- *
- * @param key the key the cipher runs under
- * @return whether the key is a Triple DES one
- */
- private static boolean isTdes(PaymentCryptographyKey key) {
- return PaymentCryptographyService.isTdes(key);
- }
-
- /**
- * The family a key's algorithm has to be for an operation.
- *
- * The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
- * the CMAC over AES, so a key of the other family would be read as bytes it is not.
- *
- * @param key the key the operation runs under
- * @param aes whether the operation needs an AES key
- * @param what the operation, for the message
- */
- private static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
- if (isAes(key) != aes) {
- throw new AwsException("ValidationException",
- "the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
- + what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
- }
- }
-
/**
* The family a key's algorithm belongs to.
*
@@ -402,56 +370,6 @@ public class PaymentCryptographyCryptoHandler {
return key;
}
- /**
- * A key that is disabled does no work.
- *
- * The service reads a disabled key and tells the caller about it, but it does not
- * encrypt with it, decrypt with it, or make a MAC under it.
- *
- * @param key the key the request names
- */
- private static void requireEnabled(PaymentCryptographyKey key) {
- if (!key.isEnabled()) {
- throw new AwsException("ValidationException",
- "the key " + key.getArn() + " is disabled", 400);
- }
- }
-
- /**
- * The material of a key.
- *
- * The material is held by the key while the emulator runs and is not written to the
- * store, so a key read back after a restart has none. A request that needs the material
- * is then refused with an error that says so, rather than failing on the missing value.
- *
- * @param key the key the operation runs under
- * @return the key's material
- */
- private static byte[] material(PaymentCryptographyKey key) {
- return PaymentCryptographyCrypto.fromHex(materialHex(key));
- }
-
- /**
- * The material of a key, as it is held.
- *
- * The material is held by the key while the emulator runs and is not written to the
- * store, so a key read back after a restart has none. A request that needs the material
- * is then refused with an error that says so, rather than failing on the missing value.
- *
- * @param key the key the operation runs under
- * @return the key's material, as hexadecimal
- */
- private static String materialHex(PaymentCryptographyKey key) {
- String hex = key.getKeyMaterialHex();
- if (hex == null || hex.isEmpty()) {
- throw new AwsException("ValidationException",
- "the material of the key " + key.getArn() + " is not held: it is kept while the "
- + "emulator runs and is not written to the store, so a key read back after "
- + "a restart has none", 400);
- }
- return hex;
- }
-
/**
* The block the key's cipher works in: sixteen bytes for AES and eight for Triple DES, as
* the reference says.
@@ -484,46 +402,6 @@ public class PaymentCryptographyCryptoHandler {
}
}
- /**
- * The usage a key has to have for an operation.
- *
- * The usage is what binds a key to its purpose, so an operation that belongs to one
- * purpose is not served with a key of another: a PIN encryption key does not encrypt
- * arbitrary data, and a MAC key does not either. The check is on the usage itself, not
- * on the mode, because a key may carry the mode and still be of another purpose.
- *
- * @param key the key the operation runs under
- * @param usages the usages the operation serves
- * @param what the operation, for the message
- */
- private static void requireUsage(PaymentCryptographyKey key, List {@code /mac}, {@code /pindata}, {@code /cardvalidationdata} and {@code /cryptogram} are
- * two-segment paths, which S3's path-style routes would claim, so
+ * {@code /mac}, {@code /macemvpinchange}, {@code /pindata}, {@code /cardvalidationdata} and
+ * {@code /cryptogram} are two-segment paths, which S3's path-style routes would claim, so
* {@link PaymentCryptographyDataPlaneRouteFilter} moves them for the requests signed for this
* service.
*
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilter.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilter.java
index 73c506f725..d57f2deb8d 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilter.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilter.java
@@ -9,6 +9,7 @@ import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;
import java.util.Set;
+import java.util.function.Predicate;
/**
* Rewrites the data plane's two-segment paths to an internal prefix before JAX-RS route
@@ -23,6 +24,24 @@ public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequest
static final String INTERNAL_PREFIX = "/_paymentcryptography";
+ /**
+ * The path prefixes the data plane's routes sit under.
+ *
+ * The routes are the ones the model names, and every one of them starts with one of
+ * these. A route whose prefix is not here is not rewritten, so it never reaches its
+ * controller, and the request is answered by whichever controller claims it instead.
+ * The test reads the generated routes and holds this list to them.
+ */
+ static final Set The data plane has more than one kind of operation, and they all ask the same questions
+ * of the key they run under: is it enabled, does it allow the mode of use the operation
+ * needs, is it of the usage the operation is for, is it of the cipher family the algorithm
+ * is defined over, and does it hold its material. The answers are the same whatever the
+ * operation is, so they are asked in one place.
+ *
+ * A key that does not satisfy a rule is refused with the error that names it, so a caller
+ * is told which of the key's attributes is wrong rather than that the request failed. The
+ * refusal is a {@code ValidationException}, which is the error the data plane's model
+ * states for a request that is well made but that the service will not serve.
+ */
+final class PaymentCryptographyKeyRules {
+
+ private PaymentCryptographyKeyRules() {
+ }
+
+ /**
+ * A key that is disabled does no work.
+ *
+ * The service reads a disabled key and tells the caller about it, but it does not
+ * encrypt with it, decrypt with it, or make a MAC under it.
+ *
+ * @param key the key the request names
+ */
+ static void requireEnabled(PaymentCryptographyKey key) {
+ if (!key.isEnabled()) {
+ throw new AwsException("ValidationException",
+ "the key " + key.getArn() + " is disabled", 400);
+ }
+ }
+
+ /**
+ * The mode of use a key has to have for an operation.
+ *
+ * The mode is what the key allows: a key that may only decrypt may not encrypt, and a
+ * key with no restrictions may do both.
+ *
+ * @param key the key the operation runs under
+ * @param mode the mode of use the operation needs
+ * @param what the operation, for the message
+ */
+ static void requireMode(PaymentCryptographyKey key, String mode, String what) {
+ Map The usage is what binds a key to its purpose, so an operation that belongs to one
+ * purpose is not served with a key of another: a PIN encryption key does not encrypt
+ * arbitrary data, and a MAC key does not either. The check is on the usage itself, not
+ * on the mode, because a key may carry the mode and still be of another purpose.
+ *
+ * @param key the key the operation runs under
+ * @param usages the usages the operation serves
+ * @param what the operation, for the message
+ */
+ static void requireUsage(PaymentCryptographyKey key, List The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
+ * the CMAC over AES, so a key of the other family would be read as bytes it is not.
+ *
+ * @param key the key the operation runs under
+ * @param aes whether the operation needs an AES key
+ * @param what the operation, for the message
+ */
+ static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
+ if (PaymentCryptographyService.isAes(key) != aes) {
+ throw new AwsException("ValidationException",
+ "the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
+ + what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
+ }
+ }
+
+ /**
+ * The material of a key.
+ *
+ * The material is held by the key while the emulator runs and is not written to the
+ * store, so a key read back after a restart has none. A request that needs the material
+ * is then refused with an error that says so, rather than failing on the missing value.
+ *
+ * @param key the key the operation runs under
+ * @return the key's material
+ */
+ static byte[] material(PaymentCryptographyKey key) {
+ return PaymentCryptographyCrypto.fromHex(materialHex(key));
+ }
+
+ /**
+ * The material of a key, as it is held.
+ *
+ * The material is held by the key while the emulator runs and is not written to the
+ * store, so a key read back after a restart has none. A request that needs the material
+ * is then refused with an error that says so, rather than failing on the missing value.
+ *
+ * @param key the key the operation runs under
+ * @return the key's material, as hexadecimal
+ */
+ static String materialHex(PaymentCryptographyKey key) {
+ String hex = key.getKeyMaterialHex();
+ if (hex == null || hex.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "the material of the key " + key.getArn() + " is not held: it is kept while the "
+ + "emulator runs and is not written to the store, so a key read back after "
+ + "a restart has none", 400);
+ }
+ return hex;
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinController.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinController.java
new file mode 100644
index 0000000000..4c11196ef1
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinController.java
@@ -0,0 +1,55 @@
+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 PIN operations.
+ *
+ * The routes are the ones the AWS SDK builds: the PIN data is made, verified and
+ * translated under the paths the model names.
+ */
+@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
+public class PaymentCryptographyPinController extends PaymentCryptographyDataPlaneController {
+
+ private final PaymentCryptographyPinOperations operations;
+
+ @Inject
+ public PaymentCryptographyPinController(PaymentCryptographyPinOperations operations,
+ ObjectMapper objectMapper,
+ RegionResolver regionResolver) {
+ super(objectMapper, regionResolver);
+ this.operations = operations;
+ }
+
+ @POST
+ @Path("/pindata/generate")
+ public Response generatePinData(String body, @Context HttpHeaders headers) {
+ return respond(operations.generatePinData(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/pindata/verify")
+ public Response verifyPinData(String body, @Context HttpHeaders headers) {
+ return respond(operations.verifyPinData(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/pindata/translate")
+ public Response translatePinData(String body, @Context HttpHeaders headers) {
+ return respond(operations.translatePinData(parse(body), region(headers)));
+ }
+
+ @POST
+ @Path("/macemvpinchange/generate")
+ public Response generateMacEmvPinChange(String body, @Context HttpHeaders headers) {
+ return respond(operations.generateMacEmvPinChange(parse(body), region(headers)));
+ }
+
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java
new file mode 100644
index 0000000000..a2dfa26796
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyPinOperations.java
@@ -0,0 +1,627 @@
+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.DukptCrypto;
+import io.floci.aws.services.paymentcryptography.crypto.PinBlockFormat;
+import io.floci.aws.services.paymentcryptography.crypto.PinCrypto;
+import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.security.SecureRandom;
+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;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.materialHex;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireEnabled;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireFamily;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireMode;
+import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireUsage;
+
+/**
+ * The PIN operations, over the Visa PVV path.
+ *
+ * VerifyPinData deciphers the inbound PIN block under the PEK, recovers the PIN, recomputes
+ * the PVV under the PVK and compares. GeneratePinData is the same arithmetic with a fresh
+ * random PIN. TranslatePinData re-enciphers a block from one PEK to another, which is the
+ * core acquiring operation and the mechanism behind a PEK rotation.
+ *
+ * PEK encryption: the eight-byte ISO 0 block is enciphered as a single TDES block, no IV
+ * and no padding. ISO format 4 is the exception: it is a sixteen-byte block protected by AES,
+ * and it binds the PIN to the whole PAN rather than to the twelve-digit account field. The
+ * format decides the cipher, so a format and a key from different families are refused
+ * together rather than producing a garbled PIN.
+ *
+ * The IBM 3624 variants, the AS2805 translation and the EMV PIN change MAC are not made.
+ * A request that asks for one of them is refused with the error that says so, rather than
+ * answered with something of another kind.
+ */
+@ApplicationScoped
+public class PaymentCryptographyPinOperations {
+
+ /** The PIN length the Visa path works over: the verification value is over four. */
+ private static final int VISA_PIN_LENGTH = 4;
+
+ /** The usages a key may have for the encryption of a PIN block. */
+ private static final List The MAC of an EMV PIN change is taken over the command message with a session key
+ * that the EMV secure messaging rules define, and this service does not make that
+ * session key. The request is refused with the error that says so, rather than answered
+ * with a MAC of another kind.
+ *
+ * The route answers, so a client that calls the operation learns why it is refused,
+ * but the action is not one the service lists as supported.
+ */
+ Map Without DUKPT attributes the identifier names a fixed PEK; with them it names a base
+ * derivation key and the working key is the X9.24 DUKPT PIN key for the KSN.
+ */
+ private PinLeg resolvePinLeg(String identifier, JsonNode dukptAttributes, String region,
+ String mode, String what) {
+ PaymentCryptographyKey key = service.findKey(region, identifier);
+ if (key == null) {
+ throw notFound(identifier);
+ }
+ requireEnabled(key);
+ if (dukptAttributes == null) {
+ requireMode(key, mode, what);
+ requireUsage(key, PIN_ENCRYPTION_USAGES, what);
+ PaymentCryptographyKeyAlgorithm algorithm = algorithmOf(key);
+ return new PinLeg(key, PaymentCryptographyCrypto.fromHex(materialHex(key)), algorithm.aes,
+ algorithm.name());
+ }
+ // A DUKPT PIN key is derived from the base derivation key, so that is what the key has
+ // to allow, and the derivation is over Triple DES, so the key is one.
+ requireMode(key, "DeriveKey", "deriving a PIN key");
+ requireUsage(key, DERIVATION_USAGES, "deriving a PIN key");
+ requireFamily(key, false, "deriving a PIN key");
+
+ // The model's DUKPT attributes come in two shapes. The PIN operations take
+ // DukptAttributes, whose derivation type is DukptDerivationType, and the translation
+ // takes DukptDerivationAttributes, whose derivation type is DukptKeyDerivationType and
+ // whose variant is DukptKeyVariant. The derivation this path makes is the Triple DES
+ // one, and the PIN key it derives is the one that both encrypts and decrypts.
+ String ksn = text(dukptAttributes, "KeySerialNumber");
+ String derivationType = text(dukptAttributes, "DukptDerivationType");
+ if (derivationType.isEmpty()) {
+ derivationType = text(dukptAttributes, "DukptKeyDerivationType");
+ }
+ if (!derivationType.isEmpty() && !"TDES_2KEY".equals(derivationType)) {
+ throw validation("the DUKPT derivation type '" + derivationType
+ + "' is not supported by this service (TDES_2KEY)");
+ }
+ String keyVariant = text(dukptAttributes, "DukptKeyVariant");
+ if (!keyVariant.isEmpty() && !"BIDIRECTIONAL".equals(keyVariant)) {
+ throw validation("the DUKPT key variant '" + keyVariant
+ + "' is not supported by this service (BIDIRECTIONAL)");
+ }
+ try {
+ // A DUKPT PIN key is a TDES key, whatever the base derivation key is.
+ return new PinLeg(key, DukptCrypto.pinKey(materialHex(key), ksn), false, "TDES");
+ } catch (IllegalArgumentException e) {
+ // The derivation refuses what the request names, so the refusal is the caller's to
+ // act on.
+ throw validation("DUKPT derivation failed: " + e.getMessage());
+ }
+ }
+
+ /**
+ * Refuses DUKPT for a format that needs an AES key.
+ *
+ * DUKPT derives a TDES PIN key, so it can only ever produce a format 0 or 3 block.
+ */
+ private static void requireNoDukptForAes(PinBlockFormat format, JsonNode dukptAttributes) {
+ if (format.isAes() && dukptAttributes != null) {
+ throw validation("DukptAttributes derive a TDES PIN key, but " + format.name()
+ + " PIN blocks require an AES PEK");
+ }
+ }
+
+ /**
+ * Checks that the PIN encryption key suits the PIN block format.
+ *
+ * Formats 0 and 3 are eight-byte TDES blocks and format 4 is a sixteen-byte AES block. A
+ * key from the wrong family cannot produce a block of that shape, so the mismatch is a
+ * validation error rather than a garbled PIN.
+ */
+ private static void requireKeyMatchesFormat(PinLeg leg, PinBlockFormat format, String label) {
+ if (leg.aes != format.isAes()) {
+ throw validation(label + " must resolve to an "
+ + (format.isAes() ? "AES" : "TDES") + " key for " + format.name()
+ + " PIN blocks (it resolves to " + leg.algorithmName + ")");
+ }
+ }
+
+ // ---- the helpers ---------------------------------------------------------
+
+ private PaymentCryptographyKey requiredKey(String identifier, String region) {
+ PaymentCryptographyKey key = service.findKey(region, identifier);
+ if (key == null) {
+ throw notFound(identifier);
+ }
+ requireEnabled(key);
+ return key;
+ }
+
+ private static PaymentCryptographyKeyAlgorithm algorithmOf(PaymentCryptographyKey key) {
+ PaymentCryptographyKeyAlgorithm algorithm =
+ PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
+ if (algorithm == null) {
+ throw validation("the key " + key.getArn() + " has the algorithm "
+ + key.getKeyAlgorithm() + ", which this service does not make");
+ }
+ return algorithm;
+ }
+
+ /**
+ * The PIN length the request declares, which the Visa path fixes at four digits.
+ *
+ * The Visa verification value is a four digit number, and the algorithm's transformed
+ * security parameter is sixteen digits: eleven of account number, one of verification key
+ * index and four of PIN. A longer PIN has no place in it, so there is no verification
+ * value for one, and a request that declares another length names something this path
+ * cannot answer.
+ *
+ * The model lets the length be between four and twelve, which is the range of the PIN
+ * a block holds and the range the IBM 3624 variants need; the Visa verification value is
+ * the four digit one.
+ *
+ * @param request the request, whose PinDataLength member may be absent
+ */
+ private static void requireVisaPinLength(JsonNode request) {
+ JsonNode declared = request.get("PinDataLength");
+ if (declared == null || declared.isNull()) {
+ return;
+ }
+ if (!declared.isIntegralNumber() || declared.asInt() != VISA_PIN_LENGTH) {
+ throw validation("Visa PVV requires a 4-digit PIN (PinDataLength 4)");
+ }
+ }
+
+ /**
+ * Refuses the wrapped-key form of a PIN encryption 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.
+ */
+ private static void refuseWrappedKey(JsonNode request, String member) {
+ if (request.get(member) != null) {
+ throw validation(member + " is not supported by this service");
+ }
+ }
+
+ private static PinBlockFormat format(String wireName) {
+ PinBlockFormat format = PinBlockFormat.from(wireName);
+ if (format == null) {
+ throw validation("PinBlockFormat '" + wireName + "' not supported by this service ("
+ + PinBlockFormat.supported() + ")");
+ }
+ return format;
+ }
+
+ /**
+ * The verification key index the attributes name.
+ *
+ * The model states that the attributes carry the index and the range it holds, and the
+ * request has been checked against it, so it is read and not checked again.
+ *
+ * @param visa the VisaPin attributes of the request
+ * @return the index of the verification key
+ */
+ private static int pvki(JsonNode visa) {
+ return visa.path("PinVerificationKeyIndex").asInt();
+ }
+
+ /**
+ * The account number the request names.
+ *
+ * The member is optional in the model, so a request that leaves it out is refused
+ * here. Its length and its digits are the model's to settle.
+ *
+ * @param pan the account number of the request
+ * @param message what to say when the request leaves it out
+ * @return the account number
+ */
+ private static String requirePan(String pan, String message) {
+ if (pan.isEmpty()) {
+ throw validation(message);
+ }
+ return pan;
+ }
+
+ private static void requireExactLength(String value, int length, String message) {
+ if (value == null || value.length() != length) {
+ throw validation(message);
+ }
+ }
+
+ /**
+ * Whether a recovered PIN is one the service can work with.
+ *
+ * A block that was enciphered under another key deciphers to something that is not a
+ * PIN, and what it carries is then not a PIN block the service can read.
+ */
+ private static boolean isRecoveredPin(String pin) {
+ if (pin == null || pin.length() < 4 || pin.length() > 12) {
+ return false;
+ }
+ for (int i = 0; i < pin.length(); i++) {
+ if (!Character.isDigit(pin.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private String randomPin(int length) {
+ StringBuilder pin = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ pin.append(random.nextInt(10));
+ }
+ return pin.toString();
+ }
+
+ /** The translation attributes this service accepts, for a message. */
+ private static String translationFormats() {
+ StringBuilder names = new StringBuilder();
+ for (PinBlockFormat format : PinBlockFormat.values()) {
+ if (names.length() > 0) {
+ names.append(", ");
+ }
+ names.append(format.translationMember());
+ }
+ return names.toString();
+ }
+
+ private static AwsException validation(String message) {
+ return new AwsException("ValidationException", message, 400);
+ }
+
+ private static AwsException notFound(String identifier) {
+ return new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
+ }
+
+ /**
+ * The PIN did not verify.
+ *
+ * A PIN that does not verify is not a bad request: the request was well made and the
+ * answer is that the PIN is not the one the issuer holds.
+ */
+ private static AwsException verificationFailed() {
+ return new AwsException("VerificationFailedException", "Pin block verification failed.", 400,
+ Map.of("Reason", "INVALID_PIN"));
+ }
+
+ /**
+ * The PIN block the request carries is not one the service can read.
+ *
+ * The reference answers a block that is not a valid PIN block with this error, and
+ * names the three causes: the wrong key, a wrong account number, and a corrupted block.
+ *
+ * @return the error that says the block is invalid
+ */
+ private static AwsException invalidPinBlock() {
+ return new AwsException("ValidationException",
+ "Pin block provided is invalid. Please check your input to ensure all field "
+ + "values are correct.", 400);
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
index a878cddf11..9c7ae7c76c 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
@@ -101,12 +101,29 @@ public final class Ciphers {
/**
* The Triple DES encryption of a block under a three-key key, in ECB mode.
*
+ * The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
+ * is what the two-key form means. A three-key key is taken as it is.
+ *
* @param block8 the eight-byte block to encrypt
- * @param key24 the twenty-four-byte key
+ * @param key the sixteen- or twenty-four-byte key
* @return the encrypted block
*/
- public static byte[] tdes3Encrypt(byte[] block8, byte[] key24) {
- return block(new DESedeEngine(), true, block8, key24);
+ public static byte[] tdes3Encrypt(byte[] block8, byte[] key) {
+ return block(new DESedeEngine(), true, block8, key);
+ }
+
+ /**
+ * The Triple DES decryption of a block under a key, in ECB mode.
+ *
+ * The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
+ * is what the two-key form means. A three-key key is taken as it is.
+ *
+ * @param block8 the eight-byte block to decrypt
+ * @param key the sixteen- or twenty-four-byte key
+ * @return the decrypted block
+ */
+ public static byte[] tdesEcbDecrypt(byte[] block8, byte[] key) {
+ return block(new DESedeEngine(), false, block8, key);
}
/**
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Decimalize.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Decimalize.java
new file mode 100644
index 0000000000..b566205fa6
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Decimalize.java
@@ -0,0 +1,44 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+/**
+ * The decimalization the Visa PIN Verification Value is made of.
+ *
+ * The digits of the enciphered block are taken first, from left to right, and the letters
+ * are turned into numbers only if there are not enough digits: a letter stands for its own
+ * value less ten, so A is zero, B is one, and F is five.
+ */
+public final class Decimalize {
+
+ private Decimalize() {
+ }
+
+ /**
+ * The first n digits of a hexadecimal string, decimalized.
+ *
+ * The digits are taken first, from left to right. When there are not enough of them,
+ * the letters fill the gap, from left to right, each one standing for its own value less
+ * ten.
+ *
+ * @param hex the hexadecimal string
+ * @param n the number of digits wanted
+ * @return the digits, which may be shorter than n when the string holds too few
+ */
+ public static String of(String hex, int n) {
+ StringBuilder out = new StringBuilder(n);
+ for (int i = 0; i < hex.length() && out.length() < n; i++) {
+ char c = hex.charAt(i);
+ if (c >= '0' && c <= '9') {
+ out.append(c);
+ }
+ }
+ if (out.length() < n) {
+ for (int i = 0; i < hex.length() && out.length() < n; i++) {
+ int v = Character.digit(hex.charAt(i), 16);
+ if (v >= 10) {
+ out.append(v - 10);
+ }
+ }
+ }
+ return out.toString();
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/DukptCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/DukptCrypto.java
index 8bf06d345d..25ed483007 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/DukptCrypto.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/DukptCrypto.java
@@ -9,7 +9,7 @@ import java.util.HexFormat;
* Validated against the vectors ANSI X9.24-1 publishes, which the test holds: the
@@ -23,6 +23,7 @@ import java.util.HexFormat;
public final class DukptCrypto {
private static final byte[] KEY_VARIANT = HexFormat.of().parseHex("C0C0C0C000000000C0C0C0C000000000");
+ private static final byte[] PIN_MASK = HexFormat.of().parseHex("00000000000000FF00000000000000FF");
private static final byte[] MAC_REQUEST_MASK = HexFormat.of().parseHex("000000000000FF00000000000000FF00");
private DukptCrypto() {
@@ -110,6 +111,11 @@ public final class DukptCrypto {
return key;
}
+ /** The PIN encryption working key. */
+ public static byte[] pinKey(String bdkHex, String ksnHex) {
+ return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), PIN_MASK);
+ }
+
/** The MAC-request working key. */
public static byte[] macKey(String bdkHex, String ksnHex) {
return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), MAC_REQUEST_MASK);
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/PinBlockFormat.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/PinBlockFormat.java
new file mode 100644
index 0000000000..81ebc5e048
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/PinBlockFormat.java
@@ -0,0 +1,110 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * The ISO 9564-1 PIN block formats the service makes.
+ *
+ * Three of the four formats the API names are made: the format 0 and the format 3 are
+ * eight-byte Triple DES blocks, and the format 4 is a sixteen-byte AES block. The format 1
+ * the API also names is a format ISO 9564-1 defines, a block that carries no PAN, but this
+ * service does not make it, so a request that asks for one is refused rather than answered
+ * with a block of some other format.
+ */
+public enum PinBlockFormat {
+
+ /** The eight-byte Triple DES block that fills with F. */
+ ISO_FORMAT_0(8, false),
+
+ /** The eight-byte Triple DES block that fills with random nibbles. */
+ ISO_FORMAT_3(8, false),
+
+ /** The sixteen-byte AES block that binds the PIN to the whole account number. */
+ ISO_FORMAT_4(16, true);
+
+ /** The block the format is, in bytes. */
+ private final int blockBytes;
+
+ /** Whether the format is protected by an AES key rather than a Triple DES one. */
+ private final boolean aes;
+
+ PinBlockFormat(int blockBytes, boolean aes) {
+ this.blockBytes = blockBytes;
+ this.aes = aes;
+ }
+
+ /** The block the format is, in bytes. */
+ public int blockBytes() {
+ return blockBytes;
+ }
+
+ /** The block the format is, in hexadecimal characters. */
+ public int blockHexLength() {
+ return blockBytes * 2;
+ }
+
+ /** Whether the format is protected by an AES key rather than a Triple DES one. */
+ public boolean isAes() {
+ return aes;
+ }
+
+ /** How the format is named in a message. */
+ public String label() {
+ return "ISO-" + suffix();
+ }
+
+ /** How the format is named in the translation attributes. */
+ public String translationMember() {
+ return "IsoFormat" + suffix();
+ }
+
+ private String suffix() {
+ return name().substring("ISO_FORMAT_".length());
+ }
+
+ /**
+ * The format a name in {@code PinBlockFormat} names.
+ *
+ * @param wireName the name the request carries
+ * @return the format, or null when the name is one this service does not make
+ */
+ public static PinBlockFormat from(String wireName) {
+ if (wireName == null) {
+ return null;
+ }
+ for (PinBlockFormat format : values()) {
+ if (format.name().equals(wireName)) {
+ return format;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * The format a name in the translation attributes names.
+ *
+ * @param member the name the request carries
+ * @return the format, or null when the name is one this service does not make
+ */
+ public static PinBlockFormat fromTranslationMember(String member) {
+ if (member == null) {
+ return null;
+ }
+ for (PinBlockFormat format : values()) {
+ if (format.translationMember().equals(member)) {
+ return format;
+ }
+ }
+ return null;
+ }
+
+ /** The formats this service makes, for a message. */
+ public static String supported() {
+ List The account field is the 12 right-most PAN digits excluding the check
+ * digit. The API takes a primary account number, which carries its own
+ * check digit, so the digit is dropped and the twelve right-most of what is
+ * left are the field. A PAN of twelve digits leaves eleven, and the field is
+ * padded with a zero on the left.
+ *
+ * Format 4 is the odd one out. It does not use the account field at all:
+ * it carries the whole PAN, and it is the only format an AES key can protect.
+ *
+ * The blocks are enciphered in ECB mode, which is what ISO 9564-1 defines: one block
+ * goes in and one block comes out. The ciphers are BouncyCastle's, so the block that goes
+ * in and the block that comes out are the ones the standard is written over.
+ */
+public final class PinCrypto {
+
+ /** The hexadecimal form the blocks are written in: upper case, no separators. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ private PinCrypto() {
+ }
+
+ /**
+ * The 12-digit ISO-0 account field.
+ *
+ * The field is the twelve right-most digits of the PAN without its check
+ * digit, so the digit is dropped and the twelve right-most of what is left
+ * are the field. A PAN of twelve digits leaves eleven, and the field is
+ * padded with a zero on the left.
+ *
+ * @throws IllegalArgumentException if the PAN has fewer than twelve digits,
+ * which is fewer than the field holds
+ */
+ public static String account12(String pan) {
+ String d = digits(pan);
+ if (d.length() < 12) {
+ throw new IllegalArgumentException("the account field is twelve digits, and the PAN "
+ + "has fewer");
+ }
+ String withoutCheckDigit = d.substring(0, d.length() - 1);
+ if (withoutCheckDigit.length() >= 12) {
+ return withoutCheckDigit.substring(withoutCheckDigit.length() - 12);
+ }
+ return "0" + withoutCheckDigit;
+ }
+
+ /**
+ * The ISO 9564-1 Format-0 clear PIN block, as 16 upper-case hex characters.
+ *
+ * Layout: a filler nibble, the PIN length as one hex digit, the PIN
+ * digits, then {@code F} padding to 16 characters. XOR that against
+ * {@code 0000} followed by the account field.
+ */
+ public static String iso0PinBlock(String pin, String pan) {
+ String p = digits(pin);
+ if (p.length() < 4 || p.length() > 12) {
+ throw new IllegalArgumentException("PIN length must be 4..12");
+ }
+ StringBuilder pinField = new StringBuilder();
+ pinField.append('0');
+ pinField.append(Integer.toHexString(p.length()).toUpperCase());
+ pinField.append(p);
+ while (pinField.length() < 16) {
+ pinField.append('F');
+ }
+ String panField = "0000" + account12(pan);
+ return HEX.formatHex(Ciphers.xor(
+ HEX.parseHex(pinField.toString()), HEX.parseHex(panField)));
+ }
+
+ /**
+ * Recover the clear PIN digits from a Format-0 or Format-3 block.
+ *
+ * The block is checked before the PIN is read out of it. The format nibble says which
+ * format the block is, the length nibble says how long the PIN is, the digits have to be
+ * digits, and the fill has to be what the format says it is. A block that is not checked
+ * would give a PIN out of a block of another format, and a block that was made up would
+ * pass as one that was not.
+ *
+ * @param blockHex the clear block, as hexadecimal
+ * @param pan the account number the block is bound to
+ * @param format the format the block is in
+ * @return the PIN the block carries
+ */
+ public static String decodeIso0PinBlock(String blockHex, String pan, PinBlockFormat format) {
+ String panField = "0000" + account12(pan);
+ String pinField = HEX.formatHex(Ciphers.xor(HEX.parseHex(blockHex), HEX.parseHex(panField)));
+ if (pinField.length() != 16) {
+ throw new IllegalArgumentException("the PIN block is " + pinField.length()
+ + " characters; it is 16");
+ }
+ char formatNibble = pinField.charAt(0);
+ char wanted = format == PinBlockFormat.ISO_FORMAT_3 ? '3' : '0';
+ if (formatNibble != wanted) {
+ throw new IllegalArgumentException("the PIN block is a format " + formatNibble
+ + " block, and a " + format.label() + " block was expected");
+ }
+ int len = Character.digit(pinField.charAt(1), 16);
+ if (len < 4 || len > 12) {
+ throw new IllegalArgumentException("the PIN block says the PIN is " + len
+ + " digits; it is 4 to 12");
+ }
+ String pin = pinField.substring(2, 2 + len);
+ for (int i = 0; i < pin.length(); i++) {
+ if (!Character.isDigit(pin.charAt(i))) {
+ throw new IllegalArgumentException("the PIN block does not carry digits");
+ }
+ }
+ for (int i = 2 + len; i < pinField.length(); i++) {
+ char fill = pinField.charAt(i);
+ // Format 0 fills with F, and format 3 with a value in the range A to F.
+ boolean good = format == PinBlockFormat.ISO_FORMAT_3
+ ? fill >= 'A' && fill <= 'F'
+ : fill == 'F';
+ if (!good) {
+ throw new IllegalArgumentException("the PIN block does not carry the fill of a "
+ + format.label() + " block");
+ }
+ }
+ return pin;
+ }
+
+ // ---- ISO 9564-1 Format 3 ------------------------------------------------
+
+ /**
+ * The ISO 9564-1 Format-3 clear PIN block, as 16 upper-case hex characters.
+ *
+ * Format 3 is format 0 with two differences: the control nibble is
+ * {@code 3}, and the fill nibbles are random values in the range A to F
+ * rather than a constant F. The random fill is the point of the format -
+ * it stops the same PIN from producing the same ciphertext twice.
+ *
+ * @param random the source of the fill nibbles
+ */
+ public static String iso3PinBlock(String pin, String pan, Random random) {
+ String p = digits(pin);
+ if (p.length() < 4 || p.length() > 12) {
+ throw new IllegalArgumentException("PIN length must be 4..12");
+ }
+ StringBuilder pinField = new StringBuilder();
+ pinField.append('3');
+ pinField.append(Integer.toHexString(p.length()).toUpperCase());
+ pinField.append(p);
+ while (pinField.length() < 16) {
+ // 10 to 15, which is A to F.
+ pinField.append(Integer.toHexString(10 + random.nextInt(6)).toUpperCase());
+ }
+ String panField = "0000" + account12(pan);
+ return HEX.formatHex(Ciphers.xor(
+ HEX.parseHex(pinField.toString()), HEX.parseHex(panField)));
+ }
+
+ // ---- ISO 9564-1 Format 4 ------------------------------------------------
+
+ /**
+ * The ISO 9564-1 Format-4 plain-text PIN field: 16 bytes.
+ *
+ * Layout: the control nibble {@code 4}, the PIN length, the PIN digits,
+ * {@code A} fill up to 16 nibbles, then 8 random bytes. The random half is
+ * what makes every block unique, so the same PIN never enciphers to the
+ * same ciphertext twice.
+ *
+ * @param randomPad 8 random bytes
+ */
+ public static byte[] iso4PinField(String pin, byte[] randomPad) {
+ String p = digits(pin);
+ if (p.length() < 4 || p.length() > 12) {
+ throw new IllegalArgumentException("PIN length must be 4..12");
+ }
+ if (randomPad == null || randomPad.length != 8) {
+ throw new IllegalArgumentException("the random pad must be 8 bytes");
+ }
+ StringBuilder pinField = new StringBuilder();
+ pinField.append('4');
+ pinField.append(Integer.toHexString(p.length()).toUpperCase());
+ pinField.append(p);
+ while (pinField.length() < 16) {
+ pinField.append('A');
+ }
+ pinField.append(HEX.formatHex(randomPad));
+ return HEX.parseHex(pinField.toString());
+ }
+
+ /**
+ * The ISO 9564-1 Format-4 plain-text PAN field: 16 bytes.
+ *
+ * Layout: the M nibble, which records the PAN length as 12 plus its own
+ * value, then the PAN digits, then zero padding to 32 nibbles. A PAN
+ * shorter than 12 digits is right justified and padded to the left with
+ * zeros, and M is then zero.
+ *
+ * The field carries the whole PAN, the check digit included, which is
+ * what the standard says: the format 4 PAN field is the complete PAN,
+ * where the account field of the formats 0 and 3 is the twelve right-most
+ * digits without the check digit.
+ *
+ * The M nibble is four bits, so the PAN it records may be up to twenty
+ * seven digits, which is what the field holds beside the nibble.
+ */
+ public static byte[] iso4PanField(String pan) {
+ String d = digits(pan);
+ if (d.isEmpty() || d.length() > 27) {
+ throw new IllegalArgumentException("the PAN field holds up to twenty seven digits");
+ }
+ StringBuilder panField = new StringBuilder();
+ panField.append(Integer.toHexString(Math.max(0, d.length() - 12)));
+ String panDigits = d;
+ while (panDigits.length() < 12) {
+ panDigits = "0" + panDigits;
+ }
+ panField.append(panDigits);
+ while (panField.length() < 32) {
+ panField.append('0');
+ }
+ return HEX.parseHex(panField.toString());
+ }
+
+ /**
+ * The encrypted ISO 9564-1 Format-4 PIN block, as 32 upper-case hex
+ * characters.
+ *
+ * The PIN field is enciphered, XORed with the PAN field, and the result
+ * enciphered again. Two passes, because one pass over the PIN field alone
+ * would not bind the PIN to the account.
+ *
+ * @param key the AES PIN encryption key
+ * @param randomPad 8 random bytes for the random half of the PIN field
+ */
+ public static String iso4PinBlock(String pin, String pan, byte[] key, byte[] randomPad) {
+ byte[] intermediateA = Ciphers.aesEcbEncrypt(iso4PinField(pin, randomPad), key);
+ byte[] intermediateB = Ciphers.xor(intermediateA, iso4PanField(pan));
+ return HEX.formatHex(Ciphers.aesEcbEncrypt(intermediateB, key));
+ }
+
+ /**
+ * The encrypted ISO 9564-1 Format-4 PIN block, with the random half drawn
+ * from {@code random}.
+ */
+ public static String iso4PinBlock(String pin, String pan, byte[] key, Random random) {
+ byte[] randomPad = new byte[8];
+ random.nextBytes(randomPad);
+ return iso4PinBlock(pin, pan, key, randomPad);
+ }
+
+ /**
+ * Recover the clear PIN digits from an encrypted Format-4 block.
+ *
+ * @return the PIN digits, or null when the block does not carry a
+ * well-formed Format-4 PIN field. A wrong key or a wrong PAN
+ * produces exactly that, so the caller reports a failed
+ * verification rather than a bad request.
+ */
+ public static String decodeIso4PinBlock(String blockHex, String pan, byte[] key) {
+ byte[] intermediateB = Ciphers.aesEcbDecrypt(HEX.parseHex(blockHex), key);
+ byte[] intermediateA = Ciphers.xor(intermediateB, iso4PanField(pan));
+ String pinField = HEX.formatHex(Ciphers.aesEcbDecrypt(intermediateA, key));
+
+ if (pinField.charAt(0) != '4') {
+ return null;
+ }
+ int len = Character.digit(pinField.charAt(1), 16);
+ if (len < 4 || len > 12) {
+ return null;
+ }
+ String pin = pinField.substring(2, 2 + len);
+ if (!pin.matches("[0-9]{4,12}")) {
+ return null;
+ }
+ // The fill between the PIN and the random half is fixed at A.
+ StringBuilder fill = new StringBuilder();
+ for (int i = 0; i < 14 - len; i++) {
+ fill.append('A');
+ }
+ if (!pinField.substring(2 + len, 16).equals(fill.toString())) {
+ return null;
+ }
+ return pin;
+ }
+
+ // ---- format dispatch ----------------------------------------------------
+
+ /**
+ * Encipher a PIN into a PIN block of the given format.
+ *
+ * @param format the ISO 9564-1 format
+ * @param pin the clear PIN
+ * @param pan the PAN in the form the format takes: a whole PAN for format 4,
+ * and anything the account field can be derived from for
+ * formats 0 and 3
+ * @param key the PIN encryption key: TDES for formats 0 and 3, AES for
+ * format 4
+ * @param random the source of the random fill
+ */
+ public static String encipherPinBlock(PinBlockFormat format, String pin, String pan,
+ byte[] key, Random random) {
+ switch (format) {
+ case ISO_FORMAT_0:
+ return HEX.formatHex(Ciphers.tdes3Encrypt(
+ HEX.parseHex(iso0PinBlock(pin, pan)), key));
+ case ISO_FORMAT_3:
+ return HEX.formatHex(Ciphers.tdes3Encrypt(
+ HEX.parseHex(iso3PinBlock(pin, pan, random)), key));
+ case ISO_FORMAT_4:
+ return iso4PinBlock(pin, pan, key, random);
+ default:
+ throw new IllegalArgumentException("unsupported PIN block format: " + format);
+ }
+ }
+
+ /**
+ * Decipher a PIN block of the given format and recover the PIN.
+ *
+ * @param pan the PAN in the form the format takes
+ * @param key the PIN encryption key
+ * @return the PIN digits, or null when the block does not carry a
+ * well-formed PIN field
+ */
+ public static String decipherPinBlock(PinBlockFormat format, String blockHex, String pan,
+ byte[] key) {
+ switch (format) {
+ case ISO_FORMAT_0:
+ case ISO_FORMAT_3:
+ return decodeIso0PinBlock(
+ HEX.formatHex(Ciphers.tdesEcbDecrypt(HEX.parseHex(blockHex), key)), pan,
+ format);
+ case ISO_FORMAT_4:
+ return decodeIso4PinBlock(blockHex, pan, key);
+ default:
+ throw new IllegalArgumentException("unsupported PIN block format: " + format);
+ }
+ }
+
+ /**
+ * The Visa PVV, the standard algorithm.
+ *
+ * {@code pvkHex} is a double-length (16-byte) key.
+ */
+ public static String computePvv(String pan, int pvki, String pin, String pvkHex) {
+ String d = digits(pan);
+ String pan11 = tspDigits(d);
+ String p4 = digits(pin);
+ if (p4.length() != 4) {
+ throw new IllegalArgumentException("Visa PVV uses a 4-digit PIN");
+ }
+ String tsp = pan11 + pvki + p4;
+ if (tsp.length() != 16) {
+ throw new IllegalArgumentException("TSP must be 16 digits, got " + tsp.length());
+ }
+ return Decimalize.of(
+ HEX.formatHex(Ciphers.tdes2Encrypt(HEX.parseHex(tsp), HEX.parseHex(pvkHex))), 4);
+ }
+
+ /**
+ * The 11 digits of the TSP: the 11 right-most digits of the account
+ * number, excluding the check digit.
+ *
+ * The API takes a primary account number, which carries its own check
+ * digit, so the digit is dropped and the eleven right-most of what is left
+ * are the TSP's.
+ */
+ private static String tspDigits(String pan) {
+ return pan.substring(0, pan.length() - 1)
+ .substring(pan.length() - 1 - 11);
+ }
+
+ /** Strip everything that is not a decimal digit. */
+ public static String digits(String s) {
+ if (s == null) {
+ return "";
+ }
+ StringBuilder sb = new StringBuilder(s.length());
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c >= '0' && c <= '9') {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+}
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 4d9c044e45..da514ff260 100644
--- a/src/main/resources/aws/payment-cryptography-data-request-shapes.json
+++ b/src/main/resources/aws/payment-cryptography-data-request-shapes.json
@@ -8,15 +8,48 @@
"DecryptData": "DecryptDataInput",
"ReEncryptData": "ReEncryptDataInput",
"GenerateMac": "GenerateMacInput",
- "VerifyMac": "VerifyMacInput"
+ "VerifyMac": "VerifyMacInput",
+ "GeneratePinData": "GeneratePinDataInput",
+ "VerifyPinData": "VerifyPinDataInput",
+ "TranslatePinData": "TranslatePinDataInput",
+ "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput"
},
"shapes": {
+ "AmexAttributes": {
+ "type": "structure",
+ "required": [
+ "MajorKeyDerivationMode",
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter",
+ "AuthorizationRequestKeyIdentifier"
+ ],
+ "members": {
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4",
+ "AuthorizationRequestKeyIdentifier": "KeyArnOrKeyAliasType",
+ "CurrentPinAttributes": "CurrentPinAttributes"
+ }
+ },
"ApplicationCryptogramType": {
"type": "string",
"min": 16,
"max": 16,
"pattern": "[0-9a-fA-F]+"
},
+ "As2805PekDerivationAttributes": {
+ "type": "structure",
+ "required": [
+ "SystemTraceAuditNumber",
+ "TransactionAmount"
+ ],
+ "members": {
+ "SystemTraceAuditNumber": "SystemTraceAuditNumberType",
+ "TransactionAmount": "TransactionAmountType"
+ }
+ },
"AsymmetricEncryptionAttributes": {
"type": "structure",
"members": {
@@ -35,6 +68,29 @@
"max": 4224,
"pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
},
+ "CommandMessageDataType": {
+ "type": "string",
+ "min": 16,
+ "max": 1024,
+ "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
+ },
+ "CurrentPinAttributes": {
+ "type": "structure",
+ "required": [
+ "CurrentPinPekIdentifier",
+ "CurrentEncryptedPinBlock"
+ ],
+ "members": {
+ "CurrentPinPekIdentifier": "KeyArnOrKeyAliasType",
+ "CurrentEncryptedPinBlock": "PinBlockLengthEquals16"
+ }
+ },
+ "DecimalizationTableType": {
+ "type": "string",
+ "min": 16,
+ "max": 16,
+ "pattern": "[0-9]+"
+ },
"DecryptDataInput": {
"type": "structure",
"required": [
@@ -49,6 +105,38 @@
"WrappedKey": "WrappedKey"
}
},
+ "DerivationMethodAttributes": {
+ "type": "structure",
+ "members": {
+ "EmvCommon": "EmvCommonAttributes",
+ "Amex": "AmexAttributes",
+ "Visa": "VisaAttributes",
+ "Emv2000": "Emv2000Attributes",
+ "Mastercard": "MasterCardAttributes"
+ }
+ },
+ "DukptAttributes": {
+ "type": "structure",
+ "required": [
+ "KeySerialNumber",
+ "DukptDerivationType"
+ ],
+ "members": {
+ "KeySerialNumber": "HexLength16Or20Or24",
+ "DukptDerivationType": "DukptDerivationType"
+ }
+ },
+ "DukptDerivationAttributes": {
+ "type": "structure",
+ "required": [
+ "KeySerialNumber"
+ ],
+ "members": {
+ "KeySerialNumber": "HexLength16Or20Or24",
+ "DukptKeyDerivationType": "DukptDerivationType",
+ "DukptKeyVariant": "DukptKeyVariant"
+ }
+ },
"DukptDerivationType": {
"type": "string",
"enum": [
@@ -106,6 +194,42 @@
"SharedInformation": "SharedInformation"
}
},
+ "Emv2000Attributes": {
+ "type": "structure",
+ "required": [
+ "MajorKeyDerivationMode",
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter"
+ ],
+ "members": {
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4"
+ }
+ },
+ "EmvCommonAttributes": {
+ "type": "structure",
+ "required": [
+ "MajorKeyDerivationMode",
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationCryptogram",
+ "Mode",
+ "PinBlockPaddingType",
+ "PinBlockLengthPosition"
+ ],
+ "members": {
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationCryptogram": "ApplicationCryptogramType",
+ "Mode": "EmvEncryptionMode",
+ "PinBlockPaddingType": "PinBlockPaddingType",
+ "PinBlockLengthPosition": "PinBlockLengthPosition"
+ }
+ },
"EmvEncryptionAttributes": {
"type": "structure",
"required": [
@@ -151,6 +275,12 @@
"WrappedKey": "WrappedKey"
}
},
+ "EncryptedPinBlockType": {
+ "type": "string",
+ "min": 16,
+ "max": 32,
+ "pattern": "[0-9a-fA-F]+"
+ },
"EncryptionDecryptionAttributes": {
"type": "structure",
"members": {
@@ -173,6 +303,27 @@
"OFB"
]
},
+ "GenerateMacEmvPinChangeInput": {
+ "type": "structure",
+ "required": [
+ "NewPinPekIdentifier",
+ "NewEncryptedPinBlock",
+ "PinBlockFormat",
+ "SecureMessagingIntegrityKeyIdentifier",
+ "SecureMessagingConfidentialityKeyIdentifier",
+ "MessageData",
+ "DerivationMethodAttributes"
+ ],
+ "members": {
+ "NewPinPekIdentifier": "KeyArnOrKeyAliasType",
+ "NewEncryptedPinBlock": "PinBlockLengthEquals16",
+ "PinBlockFormat": "PinBlockFormatForEmvPinChange",
+ "SecureMessagingIntegrityKeyIdentifier": "KeyArnOrKeyAliasType",
+ "SecureMessagingConfidentialityKeyIdentifier": "KeyArnOrKeyAliasType",
+ "MessageData": "CommandMessageDataType",
+ "DerivationMethodAttributes": "DerivationMethodAttributes"
+ }
+ },
"GenerateMacInput": {
"type": "structure",
"required": [
@@ -187,24 +338,135 @@
"MacLength": "IntegerRangeBetween4And32"
}
},
+ "GeneratePinDataInput": {
+ "type": "structure",
+ "required": [
+ "GenerationKeyIdentifier",
+ "EncryptionKeyIdentifier",
+ "GenerationAttributes",
+ "PinBlockFormat"
+ ],
+ "members": {
+ "GenerationKeyIdentifier": "KeyArnOrKeyAliasType",
+ "EncryptionKeyIdentifier": "KeyArnOrKeyAliasType",
+ "GenerationAttributes": "PinGenerationAttributes",
+ "PinDataLength": "IntegerRangeBetween4And12",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PinBlockFormat": "PinBlockFormatForPinData",
+ "EncryptionWrappedKey": "WrappedKey"
+ }
+ },
+ "HexEvenLengthBetween16And32": {
+ "type": "string",
+ "min": 16,
+ "max": 32,
+ "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
+ },
"HexLength16Or20Or24": {
"type": "string",
"min": 16,
"max": 24,
"pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{20}|[0-9a-fA-F]{24})"
},
+ "HexLengthEquals1": {
+ "type": "string",
+ "min": 1,
+ "max": 1,
+ "pattern": "[0-9A-F]+"
+ },
"HexLengthEquals4": {
"type": "string",
"min": 4,
"max": 4,
"pattern": "[0-9a-fA-F]+"
},
+ "Ibm3624NaturalPin": {
+ "type": "structure",
+ "required": [
+ "DecimalizationTable",
+ "PinValidationDataPadCharacter",
+ "PinValidationData"
+ ],
+ "members": {
+ "DecimalizationTable": "DecimalizationTableType",
+ "PinValidationDataPadCharacter": "HexLengthEquals1",
+ "PinValidationData": "PinValidationDataType"
+ }
+ },
+ "Ibm3624PinFromOffset": {
+ "type": "structure",
+ "required": [
+ "DecimalizationTable",
+ "PinValidationDataPadCharacter",
+ "PinValidationData",
+ "PinOffset"
+ ],
+ "members": {
+ "DecimalizationTable": "DecimalizationTableType",
+ "PinValidationDataPadCharacter": "HexLengthEquals1",
+ "PinValidationData": "PinValidationDataType",
+ "PinOffset": "PinOffsetType"
+ }
+ },
+ "Ibm3624PinOffset": {
+ "type": "structure",
+ "required": [
+ "EncryptedPinBlock",
+ "DecimalizationTable",
+ "PinValidationDataPadCharacter",
+ "PinValidationData"
+ ],
+ "members": {
+ "EncryptedPinBlock": "EncryptedPinBlockType",
+ "DecimalizationTable": "DecimalizationTableType",
+ "PinValidationDataPadCharacter": "HexLengthEquals1",
+ "PinValidationData": "PinValidationDataType"
+ }
+ },
+ "Ibm3624PinVerification": {
+ "type": "structure",
+ "required": [
+ "DecimalizationTable",
+ "PinValidationDataPadCharacter",
+ "PinValidationData",
+ "PinOffset"
+ ],
+ "members": {
+ "DecimalizationTable": "DecimalizationTableType",
+ "PinValidationDataPadCharacter": "HexLengthEquals1",
+ "PinValidationData": "PinValidationDataType",
+ "PinOffset": "PinOffsetType"
+ }
+ },
+ "Ibm3624RandomPin": {
+ "type": "structure",
+ "required": [
+ "DecimalizationTable",
+ "PinValidationDataPadCharacter",
+ "PinValidationData"
+ ],
+ "members": {
+ "DecimalizationTable": "DecimalizationTableType",
+ "PinValidationDataPadCharacter": "HexLengthEquals1",
+ "PinValidationData": "PinValidationDataType"
+ }
+ },
"InitializationVectorType": {
"type": "string",
"min": 16,
"max": 32,
"pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{32})"
},
+ "IntegerRangeBetween0And6": {
+ "type": "integer",
+ "min": 0,
+ "max": 6
+ },
+ "IntegerRangeBetween4And12": {
+ "type": "integer",
+ "min": 4,
+ "max": 12
+ },
"IntegerRangeBetween4And32": {
"type": "integer",
"min": 4,
@@ -306,6 +568,21 @@
"EMV_OPTION_B"
]
},
+ "MasterCardAttributes": {
+ "type": "structure",
+ "required": [
+ "MajorKeyDerivationMode",
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationCryptogram"
+ ],
+ "members": {
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationCryptogram": "ApplicationCryptogramType"
+ }
+ },
"MessageDataType": {
"type": "string",
"min": 2,
@@ -327,6 +604,73 @@
"OAEP_SHA512"
]
},
+ "PinBlockFormatForEmvPinChange": {
+ "type": "string",
+ "enum": [
+ "ISO_FORMAT_0",
+ "ISO_FORMAT_1",
+ "ISO_FORMAT_3"
+ ]
+ },
+ "PinBlockFormatForPinData": {
+ "type": "string",
+ "enum": [
+ "ISO_FORMAT_0",
+ "ISO_FORMAT_1",
+ "ISO_FORMAT_3",
+ "ISO_FORMAT_4"
+ ]
+ },
+ "PinBlockLengthEquals16": {
+ "type": "string",
+ "min": 16,
+ "max": 16,
+ "pattern": "[0-9a-fA-F]+"
+ },
+ "PinBlockLengthPosition": {
+ "type": "string",
+ "enum": [
+ "NONE",
+ "FRONT_OF_PIN_BLOCK"
+ ]
+ },
+ "PinBlockPaddingType": {
+ "type": "string",
+ "enum": [
+ "NO_PADDING",
+ "ISO_IEC_7816_4"
+ ]
+ },
+ "PinGenerationAttributes": {
+ "type": "structure",
+ "members": {
+ "VisaPin": "VisaPin",
+ "VisaPinVerificationValue": "VisaPinVerificationValue",
+ "Ibm3624PinOffset": "Ibm3624PinOffset",
+ "Ibm3624NaturalPin": "Ibm3624NaturalPin",
+ "Ibm3624RandomPin": "Ibm3624RandomPin",
+ "Ibm3624PinFromOffset": "Ibm3624PinFromOffset"
+ }
+ },
+ "PinOffsetType": {
+ "type": "string",
+ "min": 4,
+ "max": 12,
+ "pattern": "[0-9]+"
+ },
+ "PinValidationDataType": {
+ "type": "string",
+ "min": 4,
+ "max": 16,
+ "pattern": "[0-9]+"
+ },
+ "PinVerificationAttributes": {
+ "type": "structure",
+ "members": {
+ "VisaPin": "VisaPinVerification",
+ "Ibm3624Pin": "Ibm3624PinVerification"
+ }
+ },
"PlainTextType": {
"type": "string",
"min": 2,
@@ -421,12 +765,84 @@
"HMAC_SHA224"
]
},
+ "SystemTraceAuditNumberType": {
+ "type": "string",
+ "min": 6,
+ "max": 6,
+ "pattern": "[0-9]+"
+ },
"Tr31WrappedKeyBlock": {
"type": "string",
"min": 56,
"max": 9984,
"pattern": "[0-9a-zA-Z]+"
},
+ "TransactionAmountType": {
+ "type": "string",
+ "min": 12,
+ "max": 12,
+ "pattern": "[0-9]+"
+ },
+ "TranslatePinDataInput": {
+ "type": "structure",
+ "required": [
+ "IncomingKeyIdentifier",
+ "OutgoingKeyIdentifier",
+ "IncomingTranslationAttributes",
+ "OutgoingTranslationAttributes",
+ "EncryptedPinBlock"
+ ],
+ "members": {
+ "IncomingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "OutgoingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "IncomingTranslationAttributes": "TranslationIsoFormats",
+ "OutgoingTranslationAttributes": "TranslationIsoFormats",
+ "EncryptedPinBlock": "HexEvenLengthBetween16And32",
+ "IncomingDukptAttributes": "DukptDerivationAttributes",
+ "OutgoingDukptAttributes": "DukptDerivationAttributes",
+ "IncomingWrappedKey": "WrappedKey",
+ "OutgoingWrappedKey": "WrappedKey",
+ "IncomingAs2805Attributes": "As2805PekDerivationAttributes"
+ }
+ },
+ "TranslationIsoFormats": {
+ "type": "structure",
+ "members": {
+ "IsoFormat0": "TranslationPinDataIsoFormat034",
+ "IsoFormat1": "TranslationPinDataIsoFormat1",
+ "IsoFormat3": "TranslationPinDataIsoFormat034",
+ "IsoFormat4": "TranslationPinDataIsoFormat034",
+ "As2805Format0": "TranslationPinDataAs2805Format0"
+ }
+ },
+ "TranslationPinDataAs2805Format0": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType"
+ }
+ },
+ "TranslationPinDataIsoFormat034": {
+ "type": "structure",
+ "required": [
+ "PrimaryAccountNumber"
+ ],
+ "members": {
+ "PrimaryAccountNumber": "PrimaryAccountNumberType"
+ }
+ },
+ "TranslationPinDataIsoFormat1": {
+ "type": "structure",
+ "members": {}
+ },
+ "VerificationValueType": {
+ "type": "string",
+ "min": 4,
+ "max": 12,
+ "pattern": "[0-9]+"
+ },
"VerifyMacInput": {
"type": "structure",
"required": [
@@ -443,6 +859,76 @@
"MacLength": "IntegerRangeBetween4And32"
}
},
+ "VerifyPinDataInput": {
+ "type": "structure",
+ "required": [
+ "VerificationKeyIdentifier",
+ "EncryptionKeyIdentifier",
+ "VerificationAttributes",
+ "EncryptedPinBlock",
+ "PinBlockFormat"
+ ],
+ "members": {
+ "VerificationKeyIdentifier": "KeyArnOrKeyAliasType",
+ "EncryptionKeyIdentifier": "KeyArnOrKeyAliasType",
+ "VerificationAttributes": "PinVerificationAttributes",
+ "EncryptedPinBlock": "EncryptedPinBlockType",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PinBlockFormat": "PinBlockFormatForPinData",
+ "PinDataLength": "IntegerRangeBetween4And12",
+ "DukptAttributes": "DukptAttributes",
+ "EncryptionWrappedKey": "WrappedKey"
+ }
+ },
+ "VisaAttributes": {
+ "type": "structure",
+ "required": [
+ "MajorKeyDerivationMode",
+ "PrimaryAccountNumber",
+ "PanSequenceNumber",
+ "ApplicationTransactionCounter",
+ "AuthorizationRequestKeyIdentifier"
+ ],
+ "members": {
+ "MajorKeyDerivationMode": "MajorKeyDerivationMode",
+ "PrimaryAccountNumber": "PrimaryAccountNumberType",
+ "PanSequenceNumber": "NumberLengthEquals2",
+ "ApplicationTransactionCounter": "HexLengthEquals4",
+ "AuthorizationRequestKeyIdentifier": "KeyArnOrKeyAliasType",
+ "CurrentPinAttributes": "CurrentPinAttributes"
+ }
+ },
+ "VisaPin": {
+ "type": "structure",
+ "required": [
+ "PinVerificationKeyIndex"
+ ],
+ "members": {
+ "PinVerificationKeyIndex": "IntegerRangeBetween0And6"
+ }
+ },
+ "VisaPinVerification": {
+ "type": "structure",
+ "required": [
+ "PinVerificationKeyIndex",
+ "VerificationValue"
+ ],
+ "members": {
+ "PinVerificationKeyIndex": "IntegerRangeBetween0And6",
+ "VerificationValue": "VerificationValueType"
+ }
+ },
+ "VisaPinVerificationValue": {
+ "type": "structure",
+ "required": [
+ "EncryptedPinBlock",
+ "PinVerificationKeyIndex"
+ ],
+ "members": {
+ "EncryptedPinBlock": "EncryptedPinBlockType",
+ "PinVerificationKeyIndex": "IntegerRangeBetween0And6"
+ }
+ },
"WrappedKey": {
"type": "structure",
"required": [
diff --git a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamEnforcementTest.java b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamEnforcementTest.java
index 5c58412d68..a9501d23d4 100644
--- a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamEnforcementTest.java
+++ b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamEnforcementTest.java
@@ -54,33 +54,52 @@ class PaymentCryptographyDataPlaneIamEnforcementTest {
/** The key the MAC operations use, which is a MAC key and not a data-encryption one. */
private String macKeyArn;
+ /** The key the PIN operations use to protect the block. */
+ private String pinEncryptionKeyArn;
+
+ /** The key the PIN operations compute the verification value under. */
+ private String visaVerificationKeyArn;
+
@TestHTTPResource("/")
static URI baseUri;
private final PartitionCleanup cleanup = new PartitionCleanup();
+ /**
+ * The ARN of a key the control plane makes from the given CreateKey body.
+ *
+ * Every key this test needs is made the same way, so the request is written once
+ * and each key only differs in the body it carries.
+ *
+ * @param body the CreateKey request body
+ * @return the ARN of the key that was made
+ */
+ private static String createKeyArn(String body) {
+ return given().contentType("application/x-amz-json-1.0")
+ .header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
+ .header("Authorization", auth(ADMIN, "payment-cryptography"))
+ .body(body)
+ .when().post("/")
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ }
+
@BeforeEach
void createTheKeyAndTheCaller() {
RestAssuredJsonUtils.configureAwsContentTypes();
- keyArn = given().contentType("application/x-amz-json-1.0")
- .header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
- .header("Authorization", auth(ADMIN, "payment-cryptography"))
- .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");
+ keyArn = createKeyArn("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
+ + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},\"Exportable\":true}");
keyId = keyArn.substring(keyArn.lastIndexOf('/') + 1);
- macKeyArn = given().contentType("application/x-amz-json-1.0")
- .header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
- .header("Authorization", auth(ADMIN, "payment-cryptography"))
- .body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
- + "\"KeyUsage\":\"TR31_M6_ISO_9797_5_CMAC_KEY\","
- + "\"KeyModesOfUse\":{\"Generate\":true,\"Verify\":true}},\"Exportable\":true}")
- .when().post("/")
- .then().statusCode(200)
- .extract().path("Key.KeyArn");
+ macKeyArn = createKeyArn("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
+ + "\"KeyUsage\":\"TR31_M6_ISO_9797_5_CMAC_KEY\","
+ + "\"KeyModesOfUse\":{\"Generate\":true,\"Verify\":true}},\"Exportable\":true}");
+ pinEncryptionKeyArn = createKeyArn("{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_P0_PIN_ENCRYPTION_KEY\","
+ + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},\"Exportable\":true}");
+ visaVerificationKeyArn = createKeyArn("{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_V2_VISA_PIN_VERIFICATION_KEY\","
+ + "\"KeyModesOfUse\":{\"Generate\":true,\"Verify\":true}},\"Exportable\":true}");
callerName = "payment-cryptography-data-" + Long.toString(System.nanoTime(), 36);
caller = EnforcementFixtures.createUser(cleanup, port(), auth(ADMIN, "iam"), callerName);
}
@@ -236,6 +255,47 @@ class PaymentCryptographyDataPlaneIamEnforcementTest {
.then();
}
+ @Test
+ void aDenialOnOneKeyIsEnforcedWhenThePinNamesIt() {
+ // The PIN data names its keys in the body, and the action is checked on them, so a
+ // denial limited to the PIN encryption key holds.
+ EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
+ + "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:GeneratePinData\","
+ + "\"Resource\":\"" + pinEncryptionKeyArn + "\"}]}");
+
+ assertEquals(403, generatePinData().extract().statusCode());
+ }
+
+ @Test
+ void anAllowOnTheKeysThePinNamesIsEnough() {
+ // The PIN data names two keys, and the action is checked on both, so the policy has to
+ // allow the two of them and nothing else.
+ EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
+ "{\"Version\":\"2012-10-17\",\"Statement\":["
+ + "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:*\","
+ + "\"Resource\":[" + "\"" + pinEncryptionKeyArn + "\","
+ + "\"" + visaVerificationKeyArn + "\"]}]}");
+
+ ValidatableResponse response = generatePinData();
+ assertEquals(200, response.extract().statusCode());
+ response.body("EncryptedPinBlock", notNullValue());
+ }
+
+ /** The request is made as the caller, whose policy is what is under test. */
+ private ValidatableResponse generatePinData() {
+ return given().contentType("application/json")
+ .header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
+ .body("{\"EncryptionKeyIdentifier\":\"" + pinEncryptionKeyArn + "\","
+ + "\"GenerationKeyIdentifier\":\"" + visaVerificationKeyArn + "\","
+ + "\"PinBlockFormat\":\"ISO_FORMAT_0\","
+ + "\"PrimaryAccountNumber\":\"5081470082639564\","
+ + "\"GenerationAttributes\":{\"VisaPin\":{\"PinVerificationKeyIndex\":1}}}")
+ .when().post("/pindata/generate")
+ .then();
+ }
+
/** The request is made as the caller, whose policy is what is under test. */
private ValidatableResponse reEncrypt(String path, String outgoingKeyArn) {
return given().contentType("application/json")
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 bb31ee5ec0..f4c8507814 100644
--- a/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java
+++ b/src/test/java/io/floci/aws/services/iam/PaymentCryptographyDataPlaneIamRouteTest.java
@@ -72,6 +72,18 @@ class PaymentCryptographyDataPlaneIamRouteTest {
assertEquals("payment-cryptography:VerifyMac", resolve("/_paymentcryptography/mac/verify"));
}
+ @Test
+ void thePinOperationsResolveToTheirActions() {
+ assertEquals("payment-cryptography:GeneratePinData",
+ resolve("/_paymentcryptography/pindata/generate"));
+ assertEquals("payment-cryptography:VerifyPinData",
+ resolve("/_paymentcryptography/pindata/verify"));
+ assertEquals("payment-cryptography:TranslatePinData",
+ resolve("/_paymentcryptography/pindata/translate"));
+ assertEquals("payment-cryptography:GenerateMacEmvPinChange",
+ resolve("/_paymentcryptography/macemvpinchange/generate"));
+ }
+
@Test
void theRoutesAreReadUnderTheServicesScope() {
// A client of the data plane signs for the service, which is one scope for both of
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java
new file mode 100644
index 0000000000..4e1b2dac3b
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyDataPlaneRouteFilterTest.java
@@ -0,0 +1,85 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import java.io.InputStream;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Every route of the data plane is rewritten onto the internal prefix.
+ *
+ * The data plane's routes are the ones the model names, and they sit under paths that S3's
+ * path-style routes would claim. A request for one of them is rewritten before the routes
+ * match, and a request for one whose prefix the filter does not name is not rewritten: it
+ * never reaches its controller, and the request is answered by whichever controller claims it
+ * instead. The prefixes are therefore held to the generated routes, so a route that is added
+ * without its prefix is caught here rather than by a client.
+ */
+class PaymentCryptographyDataPlaneRouteFilterTest {
+
+ /** The routes the generated table holds. */
+ private static final String ROUTES = "aws/rest-routes.json";
+
+ /** The model the data plane's routes come from. */
+ private static final String MODEL = "payment-cryptography-data";
+
+ @Test
+ void everyRouteOfTheDataPlaneSitsUnderAPrefixTheFilterNames() {
+ for (String prefix : prefixesOfTheRoutes()) {
+ assertTrue(PaymentCryptographyDataPlaneRouteFilter.CONTESTED_PATHS.contains(prefix),
+ "the route prefix " + prefix + " is not one the route filter rewrites, so a "
+ + "request for it would never reach its controller");
+ }
+ }
+
+ @Test
+ void everyPrefixTheFilterNamesIsARouteOfTheDataPlane() {
+ Set The block and the verification value are checked against the values the standards
+ * give, and the rules are checked by refusing: a key of another usage, a key of another
+ * family, a key that may not do what the operation needs, and a verification value that is
+ * not the one the issuer holds.
+ */
+class PaymentCryptographyPinOperationsTest {
+
+ /** The account number the PIN belongs to. */
+ private static final String PAN = "5081470082639564";
+
+ /** The PIN the account holds. */
+ private static final String PIN = "1234";
+
+ /** The Visa PIN verification key the PVV is computed under. */
+ private static final String PVK = "0123456789ABCDEFFEDCBA9876543210";
+
+ private PaymentCryptographyService service;
+
+ private PaymentCryptographyPinOperations pin;
+
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ @BeforeEach
+ void setUp() {
+ service = new PaymentCryptographyService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"));
+ pin = new PaymentCryptographyPinOperations(service);
+ }
+
+ /** A key with the algorithm, the usage and the modes the test needs. */
+ private PaymentCryptographyKey createKey(String algorithm, String usage, String... modes) {
+ Map The digits of the enciphered block come first, and the letters fill the gap when there
+ * are not enough of them: a letter stands for its own value less ten, so A is zero and F is
+ * five.
+ */
+class DecimalizeTest {
+
+ @Test
+ void theDigitsComeFirst() {
+ assertEquals("1234", Decimalize.of("1234ABCDEF", 4));
+ }
+
+ @Test
+ void theLettersFillTheGap() {
+ // The example the reference gives: the block holds three digits, so the first letter
+ // completes the value, and F is five.
+ assertEquals("0975", Decimalize.of("0FAB9CDEFFE7DCBA", 4));
+ }
+
+ @Test
+ void aLetterStandsForItsOwnValueLessTen() {
+ assertEquals("0123", Decimalize.of("ABCDEF", 4));
+ assertEquals("012345", Decimalize.of("ABCDEF", 6));
+ }
+}
diff --git a/tools/aws/regen_payment_cryptography_data_shapes.py b/tools/aws/regen_payment_cryptography_data_shapes.py
index 86e065a7ca..3ac1978324 100644
--- a/tools/aws/regen_payment_cryptography_data_shapes.py
+++ b/tools/aws/regen_payment_cryptography_data_shapes.py
@@ -26,6 +26,7 @@ MODEL = Path("payment-cryptography-data/2022-02-03")
OPERATIONS = (
"EncryptData", "DecryptData", "ReEncryptData",
"GenerateMac", "VerifyMac",
+ "GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange",
)
diff --git a/tools/docs/services.yaml b/tools/docs/services.yaml
index d8e0c7f63b..32013a7a75 100644
--- a/tools/docs/services.yaml
+++ b/tools/docs/services.yaml
@@ -37,6 +37,9 @@ services:
doc: docs/services/payment-cryptography-data.md
sources:
- { path: services/paymentcryptography/PaymentCryptographyCryptoController.java, mode: rest }
+ - { path: services/paymentcryptography/PaymentCryptographyPinController.java, mode: rest }
+ exclude_actions:
+ - GenerateMacEmvPinChange
- service: applicationautoscaling
doc: docs/services/applicationautoscaling.md
sources:
* 1. IPEK derivation BDK + initial KSN -> IPEK
* 2. Transaction key IPEK + KSN counter bits -> derived key (one-way)
- * 3. Working-key variant derived key XOR mask -> MAC-request key
+ * 3. Working-key variants derived key XOR mask -> PIN / MAC-request key
*
*
*
+ * TSP (16 digits) = 11 rightmost PAN digits excluding the check digit
+ * + 1 PVKI digit + 4 PIN digits
+ * PVV = decimalize(3DES_EDE(PVK, TSP as an 8-byte block), 4)
+ *
+ *
+ *