mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(paymentcryptography): the PIN operations (#7397)
This commit is contained in:
1 parent
d0b50384fc
commit
6130fe9568
27 files changed
+3427
-191
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
+209
@@ -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.
|
||||
*
|
||||
* <p>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<KeyModesOfUse.Builder> modes) {
|
||||
return TestFixtures.paymentCryptographyClient().createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(algorithm)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(usage)
|
||||
.keyModesOfUse(modes))
|
||||
.exportable(true))
|
||||
.key().keyArn();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void cleanup() {
|
||||
if (client != null) {
|
||||
client.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPinIsGeneratedAndVerifies() {
|
||||
// The service makes a random PIN, so the block and the verification value come from
|
||||
// one call: a second call would make another PIN and another value.
|
||||
GeneratePinDataResponse generated = client.generatePinData(r -> r
|
||||
.encryptionKeyIdentifier(pinEncryptionKeyArn)
|
||||
.generationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_0)
|
||||
.primaryAccountNumber(PAN)
|
||||
.generationAttributes(PinGenerationAttributes.builder()
|
||||
.visaPin(VisaPin.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.build())
|
||||
.build()));
|
||||
|
||||
String block = generated.encryptedPinBlock();
|
||||
assertThat(block).isNotBlank();
|
||||
assertThat(block).hasSize(16);
|
||||
|
||||
PinData pinData = generated.pinData();
|
||||
assertThat(pinData.verificationValue()).isNotBlank();
|
||||
// The model's PinData is a union, and the discriminator says which of its two
|
||||
// members the answer carries: this one carries the verification value.
|
||||
assertThat(pinData.type()).isEqualTo(PinData.Type.VERIFICATION_VALUE);
|
||||
|
||||
// The block verifies against the verification value that goes with it.
|
||||
client.verifyPinData(r -> r
|
||||
.encryptionKeyIdentifier(pinEncryptionKeyArn)
|
||||
.verificationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_0)
|
||||
.primaryAccountNumber(PAN)
|
||||
.encryptedPinBlock(block)
|
||||
.verificationAttributes(PinVerificationAttributes.builder()
|
||||
.visaPin(VisaPinVerification.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.verificationValue(pinData.verificationValue())
|
||||
.build())
|
||||
.build()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPinThatDoesNotVerifyIsRefused() {
|
||||
String block = client.generatePinData(r -> r
|
||||
.encryptionKeyIdentifier(pinEncryptionKeyArn)
|
||||
.generationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_0)
|
||||
.primaryAccountNumber(PAN)
|
||||
.generationAttributes(PinGenerationAttributes.builder()
|
||||
.visaPin(VisaPin.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.build())
|
||||
.build()))
|
||||
.encryptedPinBlock();
|
||||
|
||||
// The verification value is not the one over the PIN, so the verification fails.
|
||||
assertThatThrownBy(() -> client.verifyPinData(r -> r
|
||||
.encryptionKeyIdentifier(pinEncryptionKeyArn)
|
||||
.verificationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_0)
|
||||
.primaryAccountNumber(PAN)
|
||||
.encryptedPinBlock(block)
|
||||
.verificationAttributes(PinVerificationAttributes.builder()
|
||||
.visaPin(VisaPinVerification.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.verificationValue("9999")
|
||||
.build())
|
||||
.build())))
|
||||
.isInstanceOf(VerificationFailedException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPinBlockTranslatesFromTheAesFormatToTheTdesOne() {
|
||||
String aesKeyArn = createKeyArn(KeyAlgorithm.AES_128,
|
||||
KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY, m -> m.encrypt(true).decrypt(true));
|
||||
|
||||
String block4 = client.generatePinData(r -> r
|
||||
.encryptionKeyIdentifier(aesKeyArn)
|
||||
.generationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_4)
|
||||
.primaryAccountNumber(PAN)
|
||||
.generationAttributes(PinGenerationAttributes.builder()
|
||||
.visaPin(VisaPin.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.build())
|
||||
.build()))
|
||||
.encryptedPinBlock();
|
||||
|
||||
assertThat(block4).hasSize(32);
|
||||
|
||||
String block0 = client.translatePinData(r -> r
|
||||
.encryptedPinBlock(block4)
|
||||
.incomingKeyIdentifier(aesKeyArn)
|
||||
.outgoingKeyIdentifier(pinEncryptionKeyArn)
|
||||
.incomingTranslationAttributes(TranslationIsoFormats.builder()
|
||||
.isoFormat4(TranslationPinDataIsoFormat034.builder()
|
||||
.primaryAccountNumber(PAN)
|
||||
.build())
|
||||
.build())
|
||||
.outgoingTranslationAttributes(TranslationIsoFormats.builder()
|
||||
.isoFormat0(TranslationPinDataIsoFormat034.builder()
|
||||
.primaryAccountNumber(PAN)
|
||||
.build())
|
||||
.build()))
|
||||
.pinBlock();
|
||||
|
||||
assertThat(block0).isNotBlank();
|
||||
assertThat(block0).hasSize(16);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatMayNotEncryptIsRefused() {
|
||||
String readOnlyKeyArn = createKeyArn(KeyAlgorithm.TDES_2_KEY,
|
||||
KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY, m -> m.decrypt(true));
|
||||
|
||||
assertThatThrownBy(() -> client.generatePinData(r -> r
|
||||
.encryptionKeyIdentifier(readOnlyKeyArn)
|
||||
.generationKeyIdentifier(visaVerificationKeyArn)
|
||||
.pinBlockFormat(PinBlockFormatForPinData.ISO_FORMAT_0)
|
||||
.primaryAccountNumber(PAN)
|
||||
.generationAttributes(PinGenerationAttributes.builder()
|
||||
.visaPin(VisaPin.builder()
|
||||
.pinVerificationKeyIndex(VERIFICATION_KEY_INDEX)
|
||||
.build())
|
||||
.build())))
|
||||
.isInstanceOf(ValidationException.class);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
|
||||
| [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 29 |
|
||||
| [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 |
|
||||
| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 12 |
|
||||
| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 5 |
|
||||
| [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 8 |
|
||||
| [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 23 |
|
||||
| [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 32 |
|
||||
| [SWF](swf.md) | `POST /` + `X-Amz-Target: SimpleWorkflowService.*` | JSON 1.0 | 39 |
|
||||
|
||||
@@ -17,6 +17,9 @@ client that talks to the control plane does not reach it by accident.
|
||||
| `ReEncryptData` | Decrypt under one key and encrypt under another, on `POST /keys/{IncomingKeyIdentifier}/reencrypt` |
|
||||
| `GenerateMac` | A MAC of a message under a key, on `POST /mac/generate` |
|
||||
| `VerifyMac` | Verify a MAC over a message, on `POST /mac/verify` |
|
||||
| `GeneratePinData` | Generate a PIN block and the verification value that goes with it, on `POST /pindata/generate` |
|
||||
| `VerifyPinData` | Verify a PIN block against the verification value the issuer holds, on `POST /pindata/verify` |
|
||||
| `TranslatePinData` | Re-encipher a PIN block from one key to another, on `POST /pindata/translate` |
|
||||
<!-- floci:actions:end -->
|
||||
|
||||
## Emulation Behavior
|
||||
@@ -40,6 +43,38 @@ client that talks to the control plane does not reach it by accident.
|
||||
encrypt arbitrary data, and a key of a MAC usage is not used to encrypt either.
|
||||
- **The key's own algorithm is the cipher that runs.** A key of an algorithm this service does
|
||||
not cipher with is refused rather than read as bytes it is not.
|
||||
- **The PIN operations are the Visa path.** The PIN block is the one of the ISO 9564-1 format
|
||||
the request names: the formats 0 and 3 are eight-byte Triple DES blocks, and the format 4 is
|
||||
a sixteen-byte AES block that binds the PIN to the whole account number rather than to the
|
||||
twelve-digit account field. The blocks are enciphered in ECB mode, which is what the standard
|
||||
defines, and they are not padded. The verification value is the Visa PIN verification value,
|
||||
computed under a key of the `TR31_V2_VISA_PIN_VERIFICATION_KEY` usage, and it is a four-digit
|
||||
verification value. The algorithm's transformed security parameter is sixteen digits: eleven
|
||||
of account number, one of verification key index and four of PIN, so the PIN it is computed
|
||||
over is a four-digit one and a longer PIN has no verification value. A PIN that does not
|
||||
verify fails the request with `VerificationFailedException`, because the answer of a
|
||||
verification has no verdict in it.
|
||||
- **A PIN block that is not one the service can read is a different failure.** A block that
|
||||
does not decipher into a PIN field, because the key is another one, the account number is
|
||||
another one, or the block is corrupted, is refused with `ValidationException` and the
|
||||
message the reference uses. A PIN is not translated from one account number to another:
|
||||
`TranslatePinData` refuses a request whose incoming and outgoing `PrimaryAccountNumber`
|
||||
differ, for PCI compliance.
|
||||
- **A DUKPT key serial number is the one the Triple DES derivation takes.** The model lets a
|
||||
key serial number be eight, ten or twelve bytes, and the twelve byte one belongs to the AES
|
||||
derivation, which this service does not make; a key serial number of more than ten bytes is
|
||||
refused. The model's DUKPT attributes come in two shapes: the PIN operations take the key
|
||||
serial number and the derivation type, and the translation takes the key serial number, an
|
||||
optional derivation type and an optional key variant. The derivation this path makes is the
|
||||
Triple DES one, so a request that asks for another of the five the model allows is refused,
|
||||
and the PIN key it derives both encrypts and decrypts, so a key variant other than the
|
||||
bidirectional one is refused.
|
||||
- **The PIN operations are not the IBM 3624 ones, and the AS2805 translation is 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. The EMV PIN change MAC is refused as well: it needs
|
||||
the session key the EMV secure messaging rules define, which this service does not make. It
|
||||
is not one of the actions the service lists as supported. The wrapped-key form of a PIN
|
||||
encryption key is refused too, because the unwrapping is part of the key exchange.
|
||||
|
||||
The two-segment paths are moved to an internal prefix for the requests signed for this
|
||||
service, so a path-style request for a bucket of that name still reaches S3.
|
||||
|
||||
@@ -68,6 +68,7 @@ import io.floci.aws.services.oam.OamController;
|
||||
import io.floci.aws.services.opensearch.ElasticsearchController;
|
||||
import io.floci.aws.services.opensearch.OpenSearchController;
|
||||
import io.floci.aws.services.paymentcryptography.PaymentCryptographyCryptoController;
|
||||
import io.floci.aws.services.paymentcryptography.PaymentCryptographyPinController;
|
||||
import io.floci.aws.services.pipes.PipesController;
|
||||
import io.floci.aws.services.quicksight.QuickSightController;
|
||||
import io.floci.aws.services.quicksight.QuickSightEmbedController;
|
||||
@@ -322,7 +323,8 @@ public class ResolvedServiceCatalog {
|
||||
// signs for the service, which is one scope for both of its planes; the
|
||||
// scope its own plane is named by is an alias of that one.
|
||||
Set.of(), Set.of("payment-cryptography", "payment-cryptography-data"), Set.of(),
|
||||
Set.of(PaymentCryptographyCryptoController.class)),
|
||||
Set.of(PaymentCryptographyCryptoController.class,
|
||||
PaymentCryptographyPinController.class)),
|
||||
descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true,
|
||||
"secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()),
|
||||
config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON,
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* How the attributes of a data plane request are read.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<Map.Entry<String, JsonNode>> fields = attributes.fields();
|
||||
while (fields.hasNext()) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = fields.next().getKey();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
}
|
||||
+11
-158
@@ -10,11 +10,21 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Iterator;
|
||||
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.material;
|
||||
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;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyService.isAes;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyService.isTdes;
|
||||
|
||||
/**
|
||||
* The data plane's encryption and its MACs: the operations that use a key to protect data.
|
||||
*
|
||||
@@ -291,48 +301,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
return iv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key is an AES key.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String> usages, String what) {
|
||||
String usage = key.getKeyUsage();
|
||||
if (usage == null || usages.contains(usage)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
|
||||
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
|
||||
}
|
||||
|
||||
/** The modes of use a key has to have for an operation. */
|
||||
private static void requireMode(PaymentCryptographyKey key, String mode, String what) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
if (modes == null) {
|
||||
return;
|
||||
}
|
||||
// A NoRestrictions that is false is not a permission: a request that names the
|
||||
// member says nothing about what it allows, so the mode itself decides.
|
||||
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(modes.get(mode))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " does not have the mode of use " + mode
|
||||
+ ", which it needs to " + what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC a request asks for, and the key it is computed under.
|
||||
*
|
||||
@@ -625,31 +503,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
byte[] apply(byte[] key, byte[] message);
|
||||
}
|
||||
|
||||
/** The one variant of an attributes structure, or null when there is not exactly one. */
|
||||
private static String soleVariant(JsonNode attributes) {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return null;
|
||||
}
|
||||
String found = null;
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
|
||||
while (fields.hasNext()) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = fields.next().getKey();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The text of a member. */
|
||||
private static String text(JsonNode request, String member) {
|
||||
if (request == null) {
|
||||
return "";
|
||||
}
|
||||
JsonNode declared = request.get(member);
|
||||
return declared == null || declared.isNull() ? "" : declared.asText("");
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob of the request.
|
||||
*
|
||||
|
||||
+2
-2
@@ -28,8 +28,8 @@ import java.util.Map;
|
||||
* besides it, and then the two must agree, so a request cannot act on a key other than the
|
||||
* one its path names.
|
||||
*
|
||||
* <p>{@code /mac}, {@code /pindata}, {@code /cardvalidationdata} and {@code /cryptogram} are
|
||||
* two-segment paths, which S3's path-style routes would claim, so
|
||||
* <p>{@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.
|
||||
*
|
||||
|
||||
+33
-5
@@ -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.
|
||||
*
|
||||
* <p>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<String> CONTESTED_PATHS = Set.of(
|
||||
"/keys",
|
||||
"/mac",
|
||||
"/macemvpinchange",
|
||||
"/pindata",
|
||||
"/cardvalidationdata",
|
||||
"/cryptogram",
|
||||
"/keymaterial",
|
||||
"/as2805kekvalidation");
|
||||
|
||||
private final SignedServiceRoute route;
|
||||
|
||||
@Inject
|
||||
@@ -33,15 +52,24 @@ public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequest
|
||||
// is served as well, so that either scope reaches the data plane.
|
||||
this.route = new SignedServiceRoute(catalog,
|
||||
Set.of("paymentcryptography", "payment-cryptography-data"), INTERNAL_PREFIX,
|
||||
SignedServiceRoute.under("/mac")
|
||||
.or(SignedServiceRoute.under("/pindata"))
|
||||
.or(SignedServiceRoute.under("/cardvalidationdata"))
|
||||
.or(SignedServiceRoute.under("/cryptogram"))
|
||||
.or(SignedServiceRoute.under("/keys")));
|
||||
under(CONTESTED_PATHS));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
route.apply(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* The predicate that says a path is one of the service's contested routes.
|
||||
*
|
||||
* @param roots the path prefixes the routes sit under
|
||||
* @return the predicate
|
||||
*/
|
||||
private static Predicate<String> under(Set<String> roots) {
|
||||
return roots.stream()
|
||||
.map(SignedServiceRoute::under)
|
||||
.reduce(Predicate::or)
|
||||
.orElseThrow(() -> new IllegalStateException("the data plane has no routes"));
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The rules a key has to satisfy before an operation runs under it.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
if (modes == null) {
|
||||
return;
|
||||
}
|
||||
// A NoRestrictions that is false is not a permission: a request that names the
|
||||
// member says nothing about what it allows, so the mode itself decides.
|
||||
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(modes.get(mode))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " does not have the mode of use " + mode
|
||||
+ ", which it needs to " + what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The usage a key has to have for an operation.
|
||||
*
|
||||
* <p>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<String> usages, String what) {
|
||||
String usage = key.getKeyUsage();
|
||||
if (usage == null || usages.contains(usage)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
|
||||
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm has to be for an operation.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
+55
@@ -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.
|
||||
*
|
||||
* <p>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)));
|
||||
}
|
||||
|
||||
}
|
||||
+627
@@ -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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String> PIN_ENCRYPTION_USAGES = List.of(
|
||||
"TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
/** The usages a key may have for the Visa PIN verification value. */
|
||||
private static final List<String> VISA_VERIFICATION_USAGES = List.of(
|
||||
"TR31_V2_VISA_PIN_VERIFICATION_KEY");
|
||||
|
||||
/** The usages a key may have for the derivation a DUKPT PIN key is made by. */
|
||||
private static final List<String> DERIVATION_USAGES = List.of(
|
||||
"TR31_B0_BASE_DERIVATION_KEY");
|
||||
|
||||
/** The source of the random fill of the format 3 blocks and the format 4 pads. */
|
||||
private final SecureRandom random;
|
||||
|
||||
private final PaymentCryptographyService service;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyPinOperations(PaymentCryptographyService service) {
|
||||
this(service, new SecureRandom());
|
||||
}
|
||||
|
||||
PaymentCryptographyPinOperations(PaymentCryptographyService service, SecureRandom random) {
|
||||
this.service = service;
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved PIN-encryption leg: the key the answer names, and the working key.
|
||||
*/
|
||||
private static final class PinLeg {
|
||||
/** The key the answer names. */
|
||||
final PaymentCryptographyKey record;
|
||||
/** The working key: the one that protects the PIN block. */
|
||||
final byte[] keyBytes;
|
||||
/** Whether the working key is an AES key. */
|
||||
final boolean aes;
|
||||
/** How the working key's algorithm is named in an error message. */
|
||||
final String algorithmName;
|
||||
|
||||
PinLeg(PaymentCryptographyKey record, byte[] keyBytes, boolean aes, String algorithmName) {
|
||||
this.record = record;
|
||||
this.keyBytes = keyBytes;
|
||||
this.aes = aes;
|
||||
this.algorithmName = algorithmName;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- VerifyPinData -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Verifies a PIN block against the verification value the issuer holds.
|
||||
*/
|
||||
Map<String, Object> verifyPinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("VerifyPinData", request);
|
||||
String encryptionKeyIdentifier = text(request, "EncryptionKeyIdentifier");
|
||||
String verificationKeyIdentifier = text(request, "VerificationKeyIdentifier");
|
||||
refuseWrappedKey(request, "EncryptionWrappedKey");
|
||||
PinBlockFormat format = format(text(request, "PinBlockFormat"));
|
||||
String pan = requirePan(text(request, "PrimaryAccountNumber"),
|
||||
"PrimaryAccountNumber is required for Visa PVV verification");
|
||||
requireVisaPinLength(request);
|
||||
requireExactLength(text(request, "EncryptedPinBlock"), format.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + format.blockHexLength()
|
||||
+ " characters (one " + format.label() + " block)");
|
||||
|
||||
JsonNode verificationAttributes = request.get("VerificationAttributes");
|
||||
String variant = soleVariant(verificationAttributes);
|
||||
if (variant == null) {
|
||||
throw validation("VerificationAttributes must specify exactly one variant");
|
||||
}
|
||||
if (!"VisaPin".equals(variant)) {
|
||||
throw validation("VerificationAttributes." + variant
|
||||
+ " not supported by this service (only VisaPin)");
|
||||
}
|
||||
JsonNode visa = verificationAttributes.get("VisaPin");
|
||||
int pvki = pvki(visa);
|
||||
String pvv = text(visa, "VerificationValue");
|
||||
|
||||
PinLeg pek = resolvePinLeg(encryptionKeyIdentifier, request.get("DukptAttributes"), region,
|
||||
"Decrypt", "decrypting a PIN block");
|
||||
requireNoDukptForAes(format, request.get("DukptAttributes"));
|
||||
requireKeyMatchesFormat(pek, format, "EncryptionKeyIdentifier");
|
||||
|
||||
PaymentCryptographyKey pvk = requiredKey(verificationKeyIdentifier, region);
|
||||
requireMode(pvk, "Verify", "verifying a PIN");
|
||||
requireUsage(pvk, VISA_VERIFICATION_USAGES, "verifying a PIN");
|
||||
// The Visa PVV is defined over Triple DES, so the key is one.
|
||||
requireFamily(pvk, false, "verifying a PIN");
|
||||
|
||||
String pin;
|
||||
try {
|
||||
pin = PinCrypto.decipherPinBlock(format, text(request, "EncryptedPinBlock"), pan,
|
||||
pek.keyBytes);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The block did not decipher into a well-formed PIN field: the key is another one,
|
||||
// the account number is another one, or the block is corrupted. The reference
|
||||
// answers that with the error that says the block is invalid.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
// A wrong key, or a wrong KSN, deciphers to garble, and what the block carries is
|
||||
// then not a PIN. That is an invalid block rather than a PIN that does not verify.
|
||||
if (!isRecoveredPin(pin)) {
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
// The Visa verification value is a four digit number, so a block that deciphers to a
|
||||
// longer PIN has no value to be compared with.
|
||||
if (pin.length() != VISA_PIN_LENGTH) {
|
||||
throw verificationFailed();
|
||||
}
|
||||
if (!PinCrypto.computePvv(pan, pvki, pin, materialHex(pvk)).equals(pvv)) {
|
||||
throw verificationFailed();
|
||||
}
|
||||
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("EncryptionKeyArn", pek.record.getArn());
|
||||
out.put("EncryptionKeyCheckValue", pek.record.getKeyCheckValue());
|
||||
out.put("VerificationKeyArn", pvk.getArn());
|
||||
out.put("VerificationKeyCheckValue", pvk.getKeyCheckValue());
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- GeneratePinData -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Generates a PIN block and the verification value that goes with it.
|
||||
*/
|
||||
Map<String, Object> generatePinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("GeneratePinData", request);
|
||||
String encryptionKeyIdentifier = text(request, "EncryptionKeyIdentifier");
|
||||
String generationKeyIdentifier = text(request, "GenerationKeyIdentifier");
|
||||
refuseWrappedKey(request, "EncryptionWrappedKey");
|
||||
PinBlockFormat format = format(text(request, "PinBlockFormat"));
|
||||
String pan = requirePan(text(request, "PrimaryAccountNumber"),
|
||||
"PrimaryAccountNumber is required");
|
||||
|
||||
JsonNode generationAttributes = request.get("GenerationAttributes");
|
||||
String variant = soleVariant(generationAttributes);
|
||||
if (!"VisaPin".equals(variant) && !"VisaPinVerificationValue".equals(variant)) {
|
||||
throw validation("GenerationAttributes." + (variant == null ? "(missing)" : variant)
|
||||
+ " not supported (VisaPin, VisaPinVerificationValue)");
|
||||
}
|
||||
JsonNode visa = generationAttributes == null ? null : generationAttributes.get(variant);
|
||||
int pvki = pvki(visa);
|
||||
|
||||
// VisaPinVerificationValue carries the block to verify, so the verification value is
|
||||
// computed for a PIN the caller already has rather than a new one.
|
||||
String givenBlock = "VisaPinVerificationValue".equals(variant) && visa != null
|
||||
? text(visa, "EncryptedPinBlock")
|
||||
: "";
|
||||
requireVisaPinLength(request);
|
||||
|
||||
PinLeg pek = resolvePinLeg(encryptionKeyIdentifier, null, region,
|
||||
"Encrypt", "encrypting a PIN block");
|
||||
PaymentCryptographyKey pvk = requiredKey(generationKeyIdentifier, region);
|
||||
requireMode(pvk, "Generate", "generating a PIN verification value");
|
||||
requireUsage(pvk, VISA_VERIFICATION_USAGES, "generating a PIN verification value");
|
||||
// The Visa PVV is defined over Triple DES, so the key is one.
|
||||
requireFamily(pvk, false, "generating a PIN verification value");
|
||||
requireKeyMatchesFormat(pek, format, "EncryptionKeyIdentifier");
|
||||
if (!givenBlock.isEmpty()) {
|
||||
// The caller's own block is decrypted to recover the PIN, so the key has to be
|
||||
// allowed to decrypt as well as to encrypt.
|
||||
requireMode(pek.record, "Decrypt", "decrypting a PIN block");
|
||||
}
|
||||
|
||||
String pin;
|
||||
String encryptedPinBlock;
|
||||
if (!givenBlock.isEmpty()) {
|
||||
// The caller's own block: recover the PIN from it and leave the block as it is.
|
||||
requireExactLength(givenBlock, format.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + format.blockHexLength()
|
||||
+ " characters (one " + format.label() + " block)");
|
||||
try {
|
||||
pin = PinCrypto.decipherPinBlock(format, givenBlock, pan, pek.keyBytes);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The caller's block did not decipher into a well-formed PIN field under the
|
||||
// key it named: the block and the key do not go together.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
if (!isRecoveredPin(pin)) {
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
encryptedPinBlock = givenBlock;
|
||||
} else {
|
||||
pin = randomPin(VISA_PIN_LENGTH);
|
||||
encryptedPinBlock = PinCrypto.encipherPinBlock(format, pin, pan, pek.keyBytes, random);
|
||||
}
|
||||
// The Visa verification value is a four digit number, so it is computed over a four
|
||||
// digit PIN. A block that carries a longer PIN has no value to be computed, and the
|
||||
// computation refuses it, so the length is checked here where the refusal is the
|
||||
// caller's to act on.
|
||||
if (pin.length() != VISA_PIN_LENGTH) {
|
||||
throw validation("the Visa verification value is computed over a four digit PIN, and "
|
||||
+ "the PIN block carries " + pin.length() + " digits");
|
||||
}
|
||||
String pvv = PinCrypto.computePvv(pan, pvki, pin, materialHex(pvk));
|
||||
|
||||
// The model's PinData is a union of the PIN offset and the verification value, and a
|
||||
// union carries one of them: this is the verification value.
|
||||
Map<String, Object> pinData = new LinkedHashMap<>();
|
||||
pinData.put("VerificationValue", pvv);
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("EncryptedPinBlock", encryptedPinBlock);
|
||||
out.put("PinData", pinData);
|
||||
out.put("EncryptionKeyArn", pek.record.getArn());
|
||||
out.put("EncryptionKeyCheckValue", pek.record.getKeyCheckValue());
|
||||
out.put("GenerationKeyArn", pvk.getArn());
|
||||
out.put("GenerationKeyCheckValue", pvk.getKeyCheckValue());
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- GenerateMacEmvPinChange ---------------------------------------------
|
||||
|
||||
/**
|
||||
* The EMV PIN change MAC.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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<String, Object> generateMacEmvPinChange(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("GenerateMacEmvPinChange", request);
|
||||
throw validation("the EMV PIN change MAC is not supported by this service");
|
||||
}
|
||||
|
||||
// ---- TranslatePinData -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Re-enciphers a PIN block from one PEK to another.
|
||||
*/
|
||||
Map<String, Object> translatePinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("TranslatePinData", request);
|
||||
String incomingKeyIdentifier = text(request, "IncomingKeyIdentifier");
|
||||
String outgoingKeyIdentifier = text(request, "OutgoingKeyIdentifier");
|
||||
if (request.get("IncomingAs2805Attributes") != null) {
|
||||
throw validation("AS2805 translation is not supported by this service");
|
||||
}
|
||||
refuseWrappedKey(request, "IncomingWrappedKey");
|
||||
refuseWrappedKey(request, "OutgoingWrappedKey");
|
||||
|
||||
JsonNode incoming = request.get("IncomingTranslationAttributes");
|
||||
JsonNode outgoing = request.get("OutgoingTranslationAttributes");
|
||||
String inVariant = soleVariant(incoming);
|
||||
String outVariant = soleVariant(outgoing);
|
||||
if (inVariant == null) {
|
||||
throw validation("IncomingTranslationAttributes must specify exactly one format");
|
||||
}
|
||||
if (outVariant == null) {
|
||||
throw validation("OutgoingTranslationAttributes must specify exactly one format");
|
||||
}
|
||||
PinBlockFormat inFormat = PinBlockFormat.fromTranslationMember(inVariant);
|
||||
PinBlockFormat outFormat = PinBlockFormat.fromTranslationMember(outVariant);
|
||||
if (inFormat == null) {
|
||||
throw validation("IncomingTranslationAttributes." + inVariant
|
||||
+ " not supported (" + translationFormats() + ")");
|
||||
}
|
||||
if (outFormat == null) {
|
||||
throw validation("OutgoingTranslationAttributes." + outVariant
|
||||
+ " not supported (" + translationFormats() + ")");
|
||||
}
|
||||
|
||||
// The block length follows the incoming format: eight bytes for the TDES formats,
|
||||
// sixteen for the AES one.
|
||||
requireExactLength(text(request, "EncryptedPinBlock"), inFormat.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + inFormat.blockHexLength()
|
||||
+ " characters (one " + inFormat.label() + " block)");
|
||||
|
||||
JsonNode inAttrs = incoming.get(inVariant);
|
||||
JsonNode outAttrs = outgoing.get(outVariant);
|
||||
String inPan = inAttrs == null ? "" : text(inAttrs, "PrimaryAccountNumber");
|
||||
String outPan = outAttrs == null ? "" : text(outAttrs, "PrimaryAccountNumber");
|
||||
// For PCI compliance the incoming and the outgoing account number are the same one,
|
||||
// and a PIN is not translated from one account number to another. The model states
|
||||
// that the attributes carry the account number, so the two are read and compared.
|
||||
if (!inPan.equals(outPan)) {
|
||||
throw validation("the incoming and the outgoing PrimaryAccountNumber must be the "
|
||||
+ "same one, and a PIN is not translated from one account number to another");
|
||||
}
|
||||
|
||||
PinLeg in = resolvePinLeg(incomingKeyIdentifier, request.get("IncomingDukptAttributes"), region,
|
||||
"Decrypt", "decrypting a PIN block");
|
||||
PinLeg out = resolvePinLeg(outgoingKeyIdentifier, request.get("OutgoingDukptAttributes"),
|
||||
region, "Encrypt", "encrypting a PIN block");
|
||||
requireNoDukptForAes(inFormat, request.get("IncomingDukptAttributes"));
|
||||
requireNoDukptForAes(outFormat, request.get("OutgoingDukptAttributes"));
|
||||
requireKeyMatchesFormat(in, inFormat, "IncomingKeyIdentifier");
|
||||
requireKeyMatchesFormat(out, outFormat, "OutgoingKeyIdentifier");
|
||||
|
||||
String pinBlock;
|
||||
try {
|
||||
String pin = PinCrypto.decipherPinBlock(inFormat, text(request, "EncryptedPinBlock"),
|
||||
inPan, in.keyBytes);
|
||||
if (!isRecoveredPin(pin)) {
|
||||
// The block deciphered, but what it carries is not a PIN, so it is not a block
|
||||
// the service can read.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
pinBlock = PinCrypto.encipherPinBlock(outFormat, pin, outPan, out.keyBytes, random);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The incoming block did not decipher into a well-formed PIN field under the
|
||||
// incoming key: the caller's block and key do not go together.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
|
||||
Map<String, Object> out2 = new LinkedHashMap<>();
|
||||
out2.put("PinBlock", pinBlock);
|
||||
out2.put("KeyArn", out.record.getArn());
|
||||
out2.put("KeyCheckValue", out.record.getKeyCheckValue());
|
||||
return out2;
|
||||
}
|
||||
|
||||
// ---- the legs ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Resolves a PIN-encryption leg.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
}
|
||||
@@ -101,12 +101,29 @@ public final class Ciphers {
|
||||
/**
|
||||
* The Triple DES encryption of a block under a three-key key, in ECB mode.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
/**
|
||||
* The decimalization the Visa PIN Verification Value is made of.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import java.util.HexFormat;
|
||||
* <pre>
|
||||
* 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
|
||||
* </pre>
|
||||
*
|
||||
* <p>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);
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<String> names = new ArrayList<>();
|
||||
for (PinBlockFormat format : values()) {
|
||||
names.add(format.name());
|
||||
}
|
||||
return String.join(", ", names);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import java.util.HexFormat;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Issuer PIN primitives: the ISO 9564-1 PIN blocks and their decoders.
|
||||
*
|
||||
* <p>The account field is the 12 right-most PAN digits <em>excluding the check
|
||||
* digit</em>. 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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <p>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.
|
||||
*
|
||||
* <pre>
|
||||
* 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)
|
||||
* </pre>
|
||||
*
|
||||
* <p>{@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.
|
||||
*
|
||||
* <p>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();
|
||||
}
|
||||
}
|
||||
@@ -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": [
|
||||
|
||||
+78
-18
@@ -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.
|
||||
*
|
||||
* <p>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")
|
||||
|
||||
@@ -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
|
||||
|
||||
+85
@@ -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.
|
||||
*
|
||||
* <p>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<String> prefixes = prefixesOfTheRoutes();
|
||||
assertTrue(!prefixes.isEmpty(), "the data plane has no routes");
|
||||
for (String prefix : PaymentCryptographyDataPlaneRouteFilter.CONTESTED_PATHS) {
|
||||
assertTrue(prefixes.contains(prefix),
|
||||
"the route filter rewrites the prefix " + prefix + ", which no route of the "
|
||||
+ "data plane sits under");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The path prefixes the data plane's routes sit under.
|
||||
*
|
||||
* @return the prefixes, each with its leading slash
|
||||
*/
|
||||
private static Set<String> prefixesOfTheRoutes() {
|
||||
JsonNode routes = read(ROUTES).path("models").path(MODEL).path("operations");
|
||||
Set<String> prefixes = new LinkedHashSet<>();
|
||||
routes.fields().forEachRemaining(entry -> {
|
||||
String uri = entry.getValue().path("requestUri").asText();
|
||||
// The route is the model's path under the internal prefix.
|
||||
assertTrue(uri.startsWith(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX),
|
||||
"the route " + uri + " does not sit under the internal prefix");
|
||||
String rest = uri.substring(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX.length());
|
||||
assertTrue(rest.startsWith("/"), "the route " + uri + " names no path");
|
||||
rest = rest.substring(1);
|
||||
int slash = rest.indexOf('/');
|
||||
assertTrue(slash > 0, "the route " + uri + " names no path");
|
||||
prefixes.add("/" + rest.substring(0, slash));
|
||||
});
|
||||
return prefixes;
|
||||
}
|
||||
|
||||
/** The generated table, read from the classpath. */
|
||||
private static JsonNode read(String resource) {
|
||||
try (InputStream in = PaymentCryptographyDataPlaneRouteFilterTest.class
|
||||
.getClassLoader().getResourceAsStream(resource)) {
|
||||
assertNotNull(in, "the generated table " + resource + " is not on the classpath");
|
||||
return new ObjectMapper().readTree(in);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("the generated table " + resource + " could not be read", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+788
@@ -0,0 +1,788 @@
|
||||
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.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 org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The PIN operations: the PIN blocks of the ISO 9564-1 formats, the Visa PIN verification
|
||||
* value, and the rules a key has to satisfy before it protects one.
|
||||
*
|
||||
* <p>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<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", usage);
|
||||
Map<String, Boolean> declared = new LinkedHashMap<>();
|
||||
for (String mode : modes) {
|
||||
declared.put(mode, Boolean.TRUE);
|
||||
}
|
||||
return service.createKey("us-east-1", attributes, declared, true, true, Map.of());
|
||||
}
|
||||
|
||||
/** The PIN encryption key of the tests: a Triple DES one that may encrypt and decrypt. */
|
||||
private PaymentCryptographyKey pinEncryptionKey() {
|
||||
return createKey("TDES_2KEY", "TR31_P0_PIN_ENCRYPTION_KEY", "Encrypt", "Decrypt");
|
||||
}
|
||||
|
||||
/** The Visa PIN verification key of the tests. */
|
||||
private PaymentCryptographyKey visaVerificationKey() {
|
||||
return createKey("TDES_2KEY", "TR31_V2_VISA_PIN_VERIFICATION_KEY", "Generate", "Verify");
|
||||
}
|
||||
|
||||
private static JsonNode request(Map<String, Object> members) {
|
||||
ObjectNode node = new ObjectMapper().createObjectNode();
|
||||
members.forEach((name, value) -> {
|
||||
if (value instanceof JsonNode json) {
|
||||
node.set(name, json);
|
||||
} else if (value instanceof Integer number) {
|
||||
node.put(name, number);
|
||||
} else {
|
||||
node.put(name, String.valueOf(value));
|
||||
}
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
private static JsonNode nested(String member, String... pairs) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
for (int i = 0; i < pairs.length; i += 2) {
|
||||
node.put(pairs[i], pairs[i + 1]);
|
||||
}
|
||||
ObjectNode outer = mapper.createObjectNode();
|
||||
outer.set(member, node);
|
||||
return outer;
|
||||
}
|
||||
|
||||
private static JsonNode visaPin(int pvki) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode visa = mapper.createObjectNode();
|
||||
visa.put("PinVerificationKeyIndex", pvki);
|
||||
ObjectNode outer = mapper.createObjectNode();
|
||||
outer.set("VisaPin", visa);
|
||||
return outer;
|
||||
}
|
||||
|
||||
private static JsonNode visaPin(int pvki, String value) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode visa = mapper.createObjectNode();
|
||||
visa.put("PinVerificationKeyIndex", pvki);
|
||||
visa.put("VerificationValue", value);
|
||||
ObjectNode outer = mapper.createObjectNode();
|
||||
outer.set("VisaPin", visa);
|
||||
return outer;
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAccountFieldAndTheBlocksAreTheOnesTheStandardGives() {
|
||||
assertEquals("147008263956", PinCrypto.account12(PAN));
|
||||
assertEquals("0412208FF7D9C6A9", PinCrypto.iso0PinBlock(PIN, PAN));
|
||||
assertEquals("441234AAAAAAAAAA0102030405060708",
|
||||
HexFormat.of().withUpperCase().formatHex(PinCrypto.iso4PinField(PIN,
|
||||
new byte[] {1, 2, 3, 4, 5, 6, 7, 8})));
|
||||
assertEquals("45081470082639564000000000000000",
|
||||
HexFormat.of().withUpperCase().formatHex(PinCrypto.iso4PanField(PAN)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPanOfTwelveDigitsIsAPanAndNotAnAccountField() {
|
||||
// The API takes a primary account number, which carries its own check digit, so a
|
||||
// twelve-digit one leaves eleven digits and the account field is padded with a
|
||||
// zero on the left.
|
||||
assertEquals("014700826395", PinCrypto.account12("147008263956"));
|
||||
// A longer PAN gives the twelve right-most digits without its check digit.
|
||||
assertEquals("147008263956", PinCrypto.account12(PAN));
|
||||
// The verification value follows the account field, so the twelve-digit PAN does
|
||||
// not give the one its own account field would.
|
||||
assertNotEquals(PinCrypto.computePvv(PAN, 1, PIN, PVK),
|
||||
PinCrypto.computePvv("147008263956", 1, PIN, PVK));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theVerificationValueIsTheOneTheStandardGives() {
|
||||
assertEquals("0463", PinCrypto.computePvv(PAN, 1, PIN, PVK));
|
||||
}
|
||||
|
||||
private static JsonNode visaPinVerificationValue(String block) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode value = mapper.createObjectNode();
|
||||
value.put("EncryptedPinBlock", block);
|
||||
value.put("PinVerificationKeyIndex", 1);
|
||||
ObjectNode variant = mapper.createObjectNode();
|
||||
variant.set("VisaPinVerificationValue", value);
|
||||
return variant;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGeneratedBlockVerifiesAgainstTheValueThatGoesWithIt() {
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
String block = (String) generated.get("EncryptedPinBlock");
|
||||
assertEquals(16, block.length());
|
||||
assertEquals(pek.getArn(), generated.get("EncryptionKeyArn"));
|
||||
assertEquals(pvk.getArn(), generated.get("GenerationKeyArn"));
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> pinData = (Map<String, Object>) generated.get("PinData");
|
||||
String pvv = (String) pinData.get("VerificationValue");
|
||||
assertNotNull(pvv);
|
||||
// The model's PinData is a union of the PIN offset and the verification value, and a
|
||||
// union carries one of them: this is the verification value and nothing else.
|
||||
assertEquals(Map.of("VerificationValue", pvv), pinData);
|
||||
|
||||
Map<String, Object> verified = pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", block,
|
||||
"VerificationAttributes", visaPin(1, pvv))),
|
||||
"us-east-1");
|
||||
assertEquals(pek.getArn(), verified.get("EncryptionKeyArn"));
|
||||
assertEquals(pvk.getArn(), verified.get("VerificationKeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockWithTheWrongVerificationValueIsRefused() {
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"VerificationAttributes", visaPin(1, "9999"))),
|
||||
"us-east-1"));
|
||||
assertEquals("VerificationFailedException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPinLongerThanFourDigitsDoesNotVerify() {
|
||||
// The Visa verification value is computed over four PIN digits, so a block that
|
||||
// carries a longer PIN is not one the value can be compared with. A block for
|
||||
// "12345" must not verify against the value over "1234".
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
byte[] key = HexFormat.of().parseHex(pek.getKeyMaterialHex());
|
||||
String block = PinCrypto.encipherPinBlock(PinBlockFormat.ISO_FORMAT_0, "12345", PAN, key,
|
||||
new SecureRandom());
|
||||
// The verification value is over the four-digit PIN the issuer holds.
|
||||
String pvv = PinCrypto.computePvv(PAN, 1, PIN, pvk.getKeyMaterialHex());
|
||||
AwsException refused = assertThrows(AwsException.class, () -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", block,
|
||||
"VerificationAttributes", visaPin(1, pvv))),
|
||||
"us-east-1"));
|
||||
assertEquals("VerificationFailedException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeclaredPinLengthThatIsNotFourIsRefused() {
|
||||
// The Visa verification value is over four PIN digits, so a request that declares
|
||||
// another length names something this path cannot verify.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"PinDataLength", 5,
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"VerificationAttributes", visaPin(1, "1234"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGivenBlockWithALongerPinIsRefused() {
|
||||
// The Visa verification value is a four digit number, so a block that carries a
|
||||
// longer PIN has no value to be computed for it. The request is refused, rather
|
||||
// than the computation failing inside the request.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
byte[] key = HexFormat.of().parseHex(pek.getKeyMaterialHex());
|
||||
String block = PinCrypto.encipherPinBlock(PinBlockFormat.ISO_FORMAT_0, "12345", PAN, key,
|
||||
new SecureRandom());
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPinVerificationValue(block))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockTranslatesFromFormatFourToFormatZero() {
|
||||
PaymentCryptographyKey aesPek = createKey("AES_128", "TR31_P0_PIN_ENCRYPTION_KEY",
|
||||
"Encrypt", "Decrypt");
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", aesPek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_4",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
String block4 = (String) generated.get("EncryptedPinBlock");
|
||||
assertEquals(32, block4.length());
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> pinData = (Map<String, Object>) generated.get("PinData");
|
||||
String pvv = (String) pinData.get("VerificationValue");
|
||||
|
||||
Map<String, Object> translated = pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", block4,
|
||||
"IncomingKeyIdentifier", aesPek.getArn(),
|
||||
"OutgoingKeyIdentifier", tdesPek.getArn(),
|
||||
"IncomingTranslationAttributes", nested("IsoFormat4", "PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0", "PrimaryAccountNumber", PAN))),
|
||||
"us-east-1");
|
||||
String block0 = (String) translated.get("PinBlock");
|
||||
assertEquals(16, block0.length());
|
||||
// The answer names the outgoing key, which is the key the block is enciphered under.
|
||||
assertEquals(tdesPek.getArn(), translated.get("KeyArn"));
|
||||
assertEquals(tdesPek.getKeyCheckValue(), translated.get("KeyCheckValue"));
|
||||
|
||||
// The PIN survived the translation: the translated block still verifies against the
|
||||
// verification value the format 4 block carried.
|
||||
Map<String, Object> verified = pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", tdesPek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", block0,
|
||||
"VerificationAttributes", visaPin(1, pvv))),
|
||||
"us-east-1");
|
||||
assertEquals(tdesPek.getArn(), verified.get("EncryptionKeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFormatThatNeedsAnAesKeyRefusesATdesKey() {
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", tdesPek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_4",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("AES"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVerificationKeyThatIsNotTdesIsRefused() {
|
||||
// The PVV is defined over Triple DES, so an AES verification key has
|
||||
// no such computation. It is refused with the reason rather than
|
||||
// failing inside the cipher.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = createKey("AES_256", "TR31_V2_VISA_PIN_VERIFICATION_KEY",
|
||||
"Generate", "Verify");
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVerificationKeyOfAnotherUsageIsRefused() {
|
||||
// The Visa PIN verification value is computed under a Visa PIN verification key, and
|
||||
// the usage is what says which key that is.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = createKey("TDES_2KEY", "TR31_P1_PIN_GENERATION_KEY",
|
||||
"Generate", "Verify");
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("TR31_V2_VISA_PIN_VERIFICATION_KEY"),
|
||||
refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatMayNotEncryptIsRefused() {
|
||||
PaymentCryptographyKey pek = createKey("TDES_2KEY", "TR31_P0_PIN_ENCRYPTION_KEY", "Decrypt");
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVerificationKeyThatMayNotVerifyIsRefused() {
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = createKey("TDES_2KEY", "TR31_V2_VISA_PIN_VERIFICATION_KEY",
|
||||
"Generate");
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", "0000000000000000",
|
||||
"VerificationAttributes", visaPin(1, "1234"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTranslationOfAnAs2805BlockIsRefused() {
|
||||
// The byte layout of the AS2805 cryptogram is in the standard and is not published,
|
||||
// so a cryptogram the service produced would not open here.
|
||||
AwsException refusal = assertThrows(AwsException.class, () -> pin.translatePinData(request(Map.of(
|
||||
"IncomingKeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/x",
|
||||
"OutgoingKeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/y",
|
||||
"IncomingAs2805Attributes", Map.of("WrappingKeyIdentifier", "x"),
|
||||
"EncryptedPinBlock", "0011223344556677")), "us-east-1"));
|
||||
assertEquals("ValidationException", refusal.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVerificationKeyIndexThatIsOutOfRangeIsRefused() {
|
||||
// The Visa PVV names one of ten keys, and the API's index is between zero and six.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(7))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFormatThatIsNotMadeIsRefused() {
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_1",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("ISO_FORMAT_0"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theWrappedKeyFormIsRefused() {
|
||||
// A wrapped key is unwrapped with a key-encryption key, and the unwrapping is part of
|
||||
// the key exchange, which this service does not make yet.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1),
|
||||
"EncryptionWrappedKey", Map.of("KeyIdentifier", "arn:aws:payment-cryptography"
|
||||
+ ":us-east-1:000000000000:key/x"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEmvPinChangeMacIsRefused() {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.generateMacEmvPinChange(request(Map.of(
|
||||
"NewPinPekIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/x",
|
||||
"SecureMessagingIntegrityKeyIdentifier",
|
||||
"arn:aws:payment-cryptography:us-east-1:000000000000:key/y",
|
||||
"SecureMessagingConfidentialityKeyIdentifier",
|
||||
"arn:aws:payment-cryptography:us-east-1:000000000000:key/z",
|
||||
"NewEncryptedPinBlock", "0000000000000000",
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"MessageData", "0000",
|
||||
"DerivationMethodAttributes", Map.of("DerivationMethod", "V2"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotThereIsRefused() {
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", "arn:aws:payment-cryptography:us-east-1:"
|
||||
+ "000000000000:key/1234abcd1234abcd1234abcd1234abcd",
|
||||
"VerificationKeyIdentifier", "arn:aws:payment-cryptography:us-east-1:"
|
||||
+ "000000000000:key/1234abcd1234abcd1234abcd1234abcd",
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", "0000000000000000",
|
||||
"VerificationAttributes", visaPin(1, "1234"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ResourceNotFoundException", refused.getErrorCode());
|
||||
assertEquals(404, refused.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBlockThatIsNotReadAsAPinBlockIsRefused() {
|
||||
// The block is enciphered under one key and verified under another, so what it
|
||||
// deciphers to is not a PIN. The reference names that an invalid PIN block, and lists
|
||||
// the wrong key among its causes.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey otherPek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", otherPek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"VerificationAttributes", visaPin(1, "1234"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPinThatDoesNotVerifyIsRefusedWithTheVerificationError() {
|
||||
// The block is read, and the PIN it carries does not match the verification value.
|
||||
// That is a verification that failed, not an invalid block.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"VerificationAttributes", visaPin(1, "9999"))),
|
||||
"us-east-1"));
|
||||
assertEquals("VerificationFailedException", refused.getErrorCode());
|
||||
assertEquals("Pin block verification failed.", refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslationBetweenTwoAccountNumbersIsRefused() {
|
||||
// For PCI compliance the incoming and the outgoing account number are the same one,
|
||||
// and a PIN is not translated from one account number to another.
|
||||
PaymentCryptographyKey aesPek = createKey("AES_128", "TR31_P0_PIN_ENCRYPTION_KEY",
|
||||
"Encrypt", "Decrypt");
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", aesPek.getArn(),
|
||||
"GenerationKeyIdentifier", visaVerificationKey().getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_4",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"IncomingKeyIdentifier", aesPek.getArn(),
|
||||
"OutgoingKeyIdentifier", tdesPek.getArn(),
|
||||
"IncomingTranslationAttributes", nested("IsoFormat4", "PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", "5081470082639565"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslationWhoseAttributesCarryNoAccountNumberIsRefused() {
|
||||
// The model's translation attributes carry the account number, and a request that
|
||||
// leaves it out is refused rather than translated.
|
||||
PaymentCryptographyKey aesPek = createKey("AES_128", "TR31_P0_PIN_ENCRYPTION_KEY",
|
||||
"Encrypt", "Decrypt");
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
ObjectNode incoming = mapper.createObjectNode();
|
||||
incoming.putNull("IsoFormat4");
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", "00112233445566778899AABBCCDDEEFF",
|
||||
"IncomingKeyIdentifier", aesPek.getArn(),
|
||||
"OutgoingKeyIdentifier", tdesPek.getArn(),
|
||||
"IncomingTranslationAttributes", incoming,
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", PAN))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptPinKeyIsDerivedFromTheBaseDerivationKey() {
|
||||
// A DUKPT PIN key is derived from the base derivation key, so that is what the
|
||||
// identifier names, and the key has to allow the derivation.
|
||||
PaymentCryptographyKey bdk = createKey("TDES_2KEY", "TR31_B0_BASE_DERIVATION_KEY",
|
||||
"DeriveKey");
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
String ksn = "12345678901234567890";
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("KeySerialNumber", ksn);
|
||||
attributes.put("DukptDerivationType", "TDES_2KEY");
|
||||
attributes.put("DukptKeyVariant", "BIDIRECTIONAL");
|
||||
|
||||
// The block is enciphered under the derived PIN key, which is what the service
|
||||
// derives from the base derivation key and the KSN.
|
||||
byte[] pinKey = DukptCrypto.pinKey(bdk.getKeyMaterialHex(), ksn);
|
||||
String block = PinCrypto.encipherPinBlock(PinBlockFormat.ISO_FORMAT_0, PIN, PAN, pinKey,
|
||||
new SecureRandom());
|
||||
|
||||
Map<String, Object> verified = pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", bdk.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", block,
|
||||
"DukptAttributes", attributes,
|
||||
"VerificationAttributes", visaPin(1,
|
||||
PinCrypto.computePvv(PAN, 1, PIN, pvk.getKeyMaterialHex())))),
|
||||
"us-east-1");
|
||||
assertEquals(bdk.getArn(), verified.get("EncryptionKeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptTranslationDerivesItsPinKeyFromTheBaseDerivationKey() {
|
||||
// The translation's DUKPT attributes are the model's other shape: the key serial
|
||||
// number, an optional derivation type and an optional key variant.
|
||||
PaymentCryptographyKey bdk = createKey("TDES_2KEY", "TR31_B0_BASE_DERIVATION_KEY",
|
||||
"DeriveKey");
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
String ksn = "12345678901234567890";
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("KeySerialNumber", ksn);
|
||||
attributes.put("DukptKeyDerivationType", "TDES_2KEY");
|
||||
attributes.put("DukptKeyVariant", "BIDIRECTIONAL");
|
||||
|
||||
// The block is enciphered under the PIN key the DUKPT derivation makes.
|
||||
byte[] pinKey = DukptCrypto.pinKey(bdk.getKeyMaterialHex(), ksn);
|
||||
String block = PinCrypto.encipherPinBlock(PinBlockFormat.ISO_FORMAT_0, PIN, PAN, pinKey,
|
||||
new SecureRandom());
|
||||
|
||||
Map<String, Object> translated = pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", block,
|
||||
"IncomingKeyIdentifier", bdk.getArn(),
|
||||
"OutgoingKeyIdentifier", tdesPek.getArn(),
|
||||
"IncomingDukptAttributes", attributes,
|
||||
"IncomingTranslationAttributes", nested("IsoFormat0", "PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0", "PrimaryAccountNumber", PAN))),
|
||||
"us-east-1");
|
||||
// The answer names the outgoing key, which is the key the block is enciphered under.
|
||||
assertEquals(tdesPek.getArn(), translated.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptTranslationOfAnotherKeyVariantIsRefused() {
|
||||
// The PIN key this path derives both encrypts and decrypts, so it is the
|
||||
// bidirectional one.
|
||||
PaymentCryptographyKey bdk = createKey("TDES_2KEY", "TR31_B0_BASE_DERIVATION_KEY",
|
||||
"DeriveKey");
|
||||
PaymentCryptographyKey tdesPek = pinEncryptionKey();
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("KeySerialNumber", "12345678901234567890");
|
||||
attributes.put("DukptKeyDerivationType", "TDES_2KEY");
|
||||
attributes.put("DukptKeyVariant", "REQUEST");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", "0000000000000000",
|
||||
"IncomingKeyIdentifier", bdk.getArn(),
|
||||
"OutgoingKeyIdentifier", tdesPek.getArn(),
|
||||
"IncomingDukptAttributes", attributes,
|
||||
"IncomingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", PAN))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTranslationWithAWrappedKeyIsRefused() {
|
||||
// The wrapped-key form of a PIN encryption key is refused: the unwrapping is part of
|
||||
// the key exchange, which this service does not make.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", "0000000000000000",
|
||||
"IncomingKeyIdentifier", pek.getArn(),
|
||||
"OutgoingKeyIdentifier", pek.getArn(),
|
||||
"IncomingWrappedKey", Map.of("WrappedKeyMaterial",
|
||||
Map.of("Tr31KeyBlock", "0123456789ABCDEF0123456789ABCDEF")),
|
||||
"OutgoingWrappedKey", Map.of("WrappedKeyMaterial",
|
||||
Map.of("Tr31KeyBlock", "0123456789ABCDEF0123456789ABCDEF")),
|
||||
"IncomingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0",
|
||||
"PrimaryAccountNumber", PAN))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptTranslationEncryptsTheOutgoingBlockUnderTheDerivedKey() {
|
||||
// The outgoing leg may be a DUKPT key as well, and the block is enciphered under
|
||||
// the PIN key the derivation makes.
|
||||
PaymentCryptographyKey pek = pinEncryptionKey();
|
||||
PaymentCryptographyKey bdk = createKey("TDES_2KEY", "TR31_B0_BASE_DERIVATION_KEY",
|
||||
"DeriveKey");
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("KeySerialNumber", "12345678901234567890");
|
||||
attributes.put("DukptKeyDerivationType", "TDES_2KEY");
|
||||
attributes.put("DukptKeyVariant", "BIDIRECTIONAL");
|
||||
|
||||
Map<String, Object> generated = pin.generatePinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", pek.getArn(),
|
||||
"GenerationKeyIdentifier", visaVerificationKey().getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"GenerationAttributes", visaPin(1))),
|
||||
"us-east-1");
|
||||
|
||||
Map<String, Object> translated = pin.translatePinData(request(Map.of(
|
||||
"EncryptedPinBlock", generated.get("EncryptedPinBlock"),
|
||||
"IncomingKeyIdentifier", pek.getArn(),
|
||||
"OutgoingKeyIdentifier", bdk.getArn(),
|
||||
"OutgoingDukptAttributes", attributes,
|
||||
"IncomingTranslationAttributes", nested("IsoFormat0", "PrimaryAccountNumber", PAN),
|
||||
"OutgoingTranslationAttributes", nested("IsoFormat0", "PrimaryAccountNumber", PAN))),
|
||||
"us-east-1");
|
||||
// The answer names the outgoing key, and the block it carries is enciphered under
|
||||
// the key that derivation makes.
|
||||
assertEquals(bdk.getArn(), translated.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptDerivationOfAnotherTypeIsRefused() {
|
||||
PaymentCryptographyKey bdk = createKey("TDES_2KEY", "TR31_B0_BASE_DERIVATION_KEY",
|
||||
"DeriveKey");
|
||||
PaymentCryptographyKey pvk = visaVerificationKey();
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("KeySerialNumber", "12345678901234567890");
|
||||
attributes.put("DukptDerivationType", "AES_128");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> pin.verifyPinData(request(Map.of(
|
||||
"EncryptionKeyIdentifier", bdk.getArn(),
|
||||
"VerificationKeyIdentifier", pvk.getArn(),
|
||||
"PinBlockFormat", "ISO_FORMAT_0",
|
||||
"PrimaryAccountNumber", PAN,
|
||||
"EncryptedPinBlock", "0000000000000000",
|
||||
"DukptAttributes", attributes,
|
||||
"VerificationAttributes", visaPin(1, "1234"))),
|
||||
"us-east-1"));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The decimalization the Visa PIN verification value is made of.
|
||||
*
|
||||
* <p>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));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ MODEL = Path("payment-cryptography-data/2022-02-03")
|
||||
OPERATIONS = (
|
||||
"EncryptData", "DecryptData", "ReEncryptData",
|
||||
"GenerateMac", "VerifyMac",
|
||||
"GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user