feat(paymentcryptography): the card values and the authorization cryptograms (#7400)

* feat(paymentcryptography): the single DES decryption

The retail MAC closes its tag with a decryption under the right half of the
key, so the cipher package needs the Single DES decryption as well as the
encryption. It is the same cipher the encryption is, the other way round, and
it is BouncyCastle's like every other cipher here.

* feat(paymentcryptography): the card values and the authorization cryptograms

The card validation value is the three digit value of the X9 algorithm: the
account number, the expiry and the service code, enciphered under the card
verification key, and decimalized. The dynamic variants compute the value
from the transaction rather than from the card's own fields, and they take a
key of their own usage that may derive.

The authorization cryptogram is the ARQC of the transaction: the ISO 9797-1
algorithm 3 retail MAC over the transaction data, cut to eight bytes, under a
session key the request's derivation produces. The EMV common session key, the
EMV 2000 one, the Mastercard one and the Visa one are served. The American
Express derivation is refused rather than approximated: the AEIPS session key
derivation is proprietary and there is nothing to verify it against, and a
plausible wrong cryptogram is worse than an error.

The operations are written on the data plane as it is now: the hexadecimal is
java.util.HexFormat, the digests are the shared Digests, and the ciphers are
the BouncyCastle ones the package already uses. The routes of the card
operations are in the vendored rest-routes.json already, so they are
authorized by the generated rules and need no hand-written ones.

* test(paymentcryptography): the card operations over the SDK and the CLI

The unit tests call the operations directly, so they do not reach the routes
the requests travel, the JSON the body carries, or the rules that decide which
action a request is. The suite does, through a client that signs the request
the way a client of the data plane signs it.

The Java suite drives the card verification value and the authorization
cryptogram with the AWS SDK for Java v2, and the CLI suite drives them with
the AWS CLI. Both refuse the American Express derivation, the key of another
usage, and the value or the cryptogram that does not verify.

* fix(paymentcryptography): the card requests are checked against the model

The card operations' constraints were not vendored, so their requests were
checked by hand and only partly: the account number was read as the digits it
carried, the expiry and the service code were not checked at all for the
first card verification value, and the key an operation acted on was not
checked to be a key.

The constraints are in the model, so they are vendored now, the four
operations are checked against them before they look at the request, and the
checks that repeat them are gone.

The model states that the PAN sequence number is two digits and that the
application transaction counter is two bytes. The derivation reads the last
eight bytes of the packed PAN || PSN and the first two bytes of the counter,
so the longer values the hand-rolled checks allowed were read as something
other than the counter they stood for. The vectors are the ones the EMV
derivation gives for the model's inputs.

* docs(paymentcryptography): the card requests are checked against the model

The account number is digits, the expiry is four of them, the service code is
three and the PAN sequence number is two, the EMV ones as the model states
them. A formatted account number and a longer sequence number are refused
rather than read as the digits they carry.

* docs(paymentcryptography): the data plane's operation count

The Service Matrix counts the operations a service documents, and the data
plane documents four more now: the card verification value and the
authorization cryptogram.

* fix(paymentcryptography): the card operations raise the errors the model names

Three findings from the review, all in the card operations.

A key that may not be used for the operation was refused with
InvalidKeyUsageException, which the data plane's model does not name, so a
client cannot catch it as its own type. The data plane names three errors,
and a refusal that is not one of them is a ValidationException.

The ARPC method 2 read an ArpcInputFormat member that no model, and no SDK,
carries, so the branch it guarded could never be taken. The member is gone
and the response value is always made the way the reference makes it.

And a hexadecimal member of an odd length is a request the model allows and
the cipher cannot read, so it was answered with an internal failure the
caller cannot catch. It is refused with the error the model names, and the
refusal names the member.

* test(paymentcryptography): the card operations' members are covered

Seven members the card operations read were read by no test, so nothing
proved they work: the response attributes and the response code, the card
status update and the proprietary data, the track data, the unpredictable
number and the validation data length. Each is sent now, and the shape the
service receives with them is exercised.

The response value is made by both ARPC methods, and a request that asks for
none is answered without one.

* test(paymentcryptography): the padding type is refused

The padding type belongs to RSA, and the symmetric cipher does not pad, so a
request that names one is refused rather than answered with a cipher that
ignored it. Nothing sent one, so the refusal was never exercised.

* fix(paymentcryptography): the wrapped key is refused on every operation that carries one

The encrypt, decrypt and re-encrypt requests hold a wrapped key for the key
exchange, and the unwrapping is part of that exchange rather than part of the
cipher. A request that carries one is refused, as the PIN operations already
refused it, rather than answered as if the key were a fixed one.

The rule now lives in one place, so the two paths cannot disagree on it.

* fix(paymentcryptography): the master key is derived over the rightmost sixteen digits

The block the ICC master key is derived over is the rightmost sixteen digits of
the account number and the PAN sequence number, padded on the left with zeros
when they are shorter. That is the rule EMV 4.4 Book 2 Annex A1.4.1 gives for
Option A, and the Visa Integrated Circuit Card Specification states it the same
way.

An account number of twelve digits is therefore read and derived from, where
the derivation used to refuse it, and the refusal in the request layer goes
with it.

A derivation the request cannot be read for is refused with the error the
model names, rather than answered with a failure the caller cannot catch.

* test(paymentcryptography): the derivations are the ones the specifications give

The vectors are the ones the specifications publish: the ICC master key from
the EMV Option A derivation, the MasterCard proprietary session key and the
application cryptogram it produces over the same data from the M/Chip worked
example, and the common session key from the same document.

The common session key is compared with the parity bits masked, because the
document does not force the parity of the derived key and the derivation does
not affect the computation.

* fix(paymentcryptography): the dynamic value is the one Visa describes

The Visa Contactless Payment Specification gives the dynamic card
verification value in full: the leftmost four digits of the account number are
replaced by the transaction counter, and the result, the expiry and the service
code are enciphered under the card's unique derived key, which the issuer
derives from the master key with the account number and the PAN sequence
number. The three leftmost decimal digits of the result are the value.

The derivation used a session key and covered the account number as it stands,
so it was the emulator's own construction and not the value Visa describes.
The key it needs is the one the unique derived key derivation already makes,
and the request carries the PAN sequence number that derivation takes.

The counter is a binary coded decimal counter, so a counter that is not one
is refused rather than read.

* docs(paymentcryptography): the dynamic code is the emulator's one

* fix(paymentcryptography): the card value carries the length asked for

The model states the length of a card validation value as three to five, and
the service refused every length but three. The value now carries the number
of digits the request asks for, and the verification compares as many.

The dynamic value's counter is a binary coded decimal counter, so the digits
that replace the leftmost ones of the account number are zero padded on the
left to the four the field holds.

* fix(paymentcryptography): the card values and cryptograms as specified

The review of the branch found that the card values and the authorization
cryptograms did not follow the rules they are made by.

The Option B master key derivation turned the hexadecimal digits of the
hash into digits as it scanned them. The specification takes the decimal
digits of the hash first and only then the nibbles that are not decimal
digits, each reduced modulo ten, so the derivation now follows it.

The transaction data reaches the service already padded, because the
caller pads it the way the card padded it before the card enciphered it.
The service was padding it a second time, which enciphered a block the
card never enciphered. The data is enciphered as it was sent now, and a
length that is not a whole number of eight-byte blocks is refused,
because the ISO 9797-1 MAC runs over whole blocks.

The key table names the application cryptogram usage, the TDES_2KEY
algorithm and the DeriveKey mode of use for the ARQC key, so a key of
another usage, another algorithm or without the mode of use is refused.
The rules are asked in one place now, so the card operations and the
cryptogram operations cannot drift apart on what they accept.

The response value of the second issuer authentication method is made of
the card status update and the proprietary data, as the specification has
it. The response code belongs to the first method.

The EMV 4.1 tree derivation and the dynamic card verification code are
refused rather than approximated: the first is proprietary, and the
second was the emulator's own construction.

A verification that fails carries the reason the model names, and a key
that is not there is answered with a 404.

* refactor(paymentcryptography): the model settles the card value's length

The card operations refused a validation data length that was not three to
five digits, and a validation data that was not, while the model states
both. The model is checked before the operation runs, so the two checks
never reached the point where they could answer, and the model answers
the same request with the same error. The checks are gone, and the
model's own constraints have a test each, so the refusal is proved.

The class comment of EmvCrypto said the ARQC is made over the CDOL, and
it is made over the transaction data as the caller sent it, so the
comment says that now.

* refactor(paymentcryptography): the card side reads the shared helpers

The review found the card side holding copies of what the service already
holds, and the comments around them out of date.

The card operations read the request members through
PaymentCryptographyAttributes now, the same as the cryptogram operations,
instead of carrying their own text and soleVariant.

They read the key's material through PaymentCryptographyKeyRules.materialHex
as well. A key read back after a restart holds no material, and the shared
rule says so, where the raw accessor gave a null that the derivation failed
on.

The refused dynamic card verification code left its branch in the
computation and the track data and unpredictable number fields behind, and
the two-argument retailMac had no callers. They are gone.

The comments are in step with the code now: the class comment of the
cryptogram operations no longer calls the EMV 2000 derivation the common
one, the comment on the second issuer authentication method no longer
carries the response code in its input, and the class comment of EmvCrypto
no longer names OpenSSL or the original engine.
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-09 11:18:07 -04:00
1 parent 2ceb668009
commit ab312d68e6
27 files changed
+3261 -6

No files matched your search

@@ -96,6 +96,18 @@ class PaymentCryptographyDataPlaneIamRouteTest {
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
}
@Test
void theCardOperationsResolveToTheirActions() {
assertEquals("payment-cryptography:GenerateCardValidationData",
resolve("/_paymentcryptography/cardvalidationdata/generate"));
assertEquals("payment-cryptography:VerifyCardValidationData",
resolve("/_paymentcryptography/cardvalidationdata/verify"));
assertEquals("payment-cryptography:GenerateAuthRequestCryptogram",
resolve("/_paymentcryptography/cryptogram/generate"));
assertEquals("payment-cryptography:VerifyAuthRequestCryptogram",
resolve("/_paymentcryptography/cryptogram/verify"));
}
/** The action the registry resolves for a POST to the path, for the service's scope. */
private String resolve(String path) {
return resolve("payment-cryptography", path);
@@ -0,0 +1,485 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.services.paymentcryptography.crypto.EmvCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HexFormat;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The authorization request cryptograms.
*
* <p>The derivations in the first test are the emulator's, and the emulator checks them
* against an independent implementation: the ICC master key, the session key that
* comes from it, and the ARQC of a
* transaction.
*/
class PaymentCryptographyAuthCryptogramOperationsTest {
/** The hexadecimal the data plane's blobs are written in. */
private static final HexFormat HEX = HexFormat.of().withUpperCase();
private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
private static final String PAN = "4111111111111111";
/** The PAN sequence number, which the model states is two digits. */
private static final String PSN = "01";
/** The application transaction counter, which the model states is two bytes. */
private static final String ATC = "0001";
/**
* The transaction data the cryptogram is computed over.
*
* <p>The user guide tells the caller to pad the transaction data before sending
* it, because the card padded it the same way before it enciphered it. The
* data here is padded that way: a whole number of eight-byte blocks, with the
* {@code 80} and the zeros that method 2 appends.
*/
/**
* Another transaction's data, of the same shape as the one above.
*
* <p>The amount differs, so the cryptogram over it differs, and the data is still
* a whole number of eight-byte blocks.
*/
private static final String ANOTHER_TRANSACTION_DATA =
"00000000180000000000000008400080008000084016051700000000093800000B1F2201"
+ "030000000000000000000000000000000000000000000000000000008000000000000000";
private static final String TRANSACTION_DATA =
"00000000170000000000000008400080008000084016051700000000093800000B1F2201"
+ "030000000000000000000000000000000000000000000000000000008000000000000000";
private PaymentCryptographyService service;
private PaymentCryptographyAuthCryptogramOperations cryptogram;
private final ObjectMapper mapper = new ObjectMapper();
@BeforeEach
void setUp() {
service = new PaymentCryptographyService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"));
cryptogram = new PaymentCryptographyAuthCryptogramOperations(service);
}
/** The session key derivation attributes of the EMV common variant. */
/** The attributes of the EMV 4.1 tree derivation, which this service refuses. */
private static JsonNode emv2000() {
ObjectMapper mapper = new ObjectMapper();
ObjectNode value = mapper.createObjectNode();
value.put("PrimaryAccountNumber", PAN);
value.put("PanSequenceNumber", PSN);
value.put("ApplicationTransactionCounter", ATC);
ObjectNode outer = mapper.createObjectNode();
outer.set("Emv2000", value);
return outer;
}
private static JsonNode emvCommon() {
return emvCommon(PAN);
}
/** The session key derivation attributes of the EMV common variant, for an account number. */
private static JsonNode emvCommon(String pan) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode value = mapper.createObjectNode();
value.put("PrimaryAccountNumber", pan);
value.put("PanSequenceNumber", PSN);
value.put("ApplicationTransactionCounter", ATC);
ObjectNode outer = mapper.createObjectNode();
outer.set("EmvCommon", value);
return outer;
}
@Test
void anAccountNumberShorterThanTheFieldIsRead() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
// The model lets the account number be twelve digits, and the derivation reads the
// rightmost sixteen digits of it and the sequence number, so it is read rather than
// refused.
Map<String, Object> generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon("411111111111"))), "us-east-1");
assertEquals(16, ((String) generated.get("AuthRequestCryptogram")).length());
}
@Test
void theDerivationsAreTheOnesTheStandardGives() {
// The values are the ones the EMV derivation gives for these inputs: the master key
// from the packed PAN || PSN, and the session key from the counter and that key. The
// derivation itself is pinned to the vectors the specifications publish in
// EmvCryptoTest.
byte[] masterKey = EmvCrypto.deriveIccMasterKey(HEX.parseHex(IMK), PAN, PSN);
assertEquals("A768CE9E1551FDE3A45B4C7C3DE9DC52", HEX.formatHex(masterKey));
// A PAN of sixteen digits or fewer is derived the Option A way, so the two agree.
assertEquals(HEX.formatHex(masterKey),
HEX.formatHex(EmvCrypto.deriveIccMasterKeyOptionB(HEX.parseHex(IMK), PAN, PSN)));
assertEquals("892FA4A7F8C8ABC7464FBF5DD63ECBD5",
HEX.formatHex(EmvCrypto.deriveSessionKey(masterKey, HEX.parseHex(ATC))));
}
@Test
void theLongerAccountNumberIsDerivedTheOptionBWay() {
// The hash is only there for the longer numbers, and the letters of the hash
// stand for the digits zero to five.
byte[] optionB = EmvCrypto.deriveIccMasterKeyOptionB(HEX.parseHex(IMK),
"4111111111111111111", PSN);
assertEquals(16, optionB.length);
assertNotEquals(HEX.formatHex(EmvCrypto.deriveIccMasterKey(HEX.parseHex(IMK),
"4111111111111111111", PSN)), HEX.formatHex(optionB));
}
@Test
void theEmv41DerivationIsRefusedRatherThanApproximated() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
// Emv2000 is the EMV 4.1 tree derivation, not the common one, and the tree needs
// the card's public key certificate.
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emv2000())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("Emv2000"), refused.getMessage());
}
@Test
void aVerificationThatFailsSaysWhy() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"AuthRequestCryptogram", "0000000000000000",
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("VerificationFailedException", refused.getErrorCode());
assertEquals("INVALID_AUTH_REQUEST_CRYPTOGRAM", refused.getExtendedData().get("Reason"));
}
@Test
void aKeyThatIsNotThereIsNotFound() {
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:111122223333:key/0123456789abcdef",
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ResourceNotFoundException", refused.getErrorCode());
assertEquals(404, refused.getHttpStatus());
}
@Test
void aGeneratedCryptogramVerifies() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
Map<String, Object> generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1");
String arqc = (String) generated.get("AuthRequestCryptogram");
assertEquals(16, arqc.length());
assertEquals(key.getArn(), generated.get("KeyArn"));
Map<String, Object> verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"AuthRequestCryptogram", arqc,
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1");
assertEquals(key.getArn(), verified.get("KeyArn"));
}
@Test
void aCryptogramOfAnotherTransactionIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
Map<String, Object> generated = cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1");
AwsException refused = assertThrows(AwsException.class, () -> cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"AuthRequestCryptogram", generated.get("AuthRequestCryptogram"),
"TransactionData", ANOTHER_TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("VerificationFailedException", refused.getErrorCode());
}
@Test
void theAmexDerivationIsRefusedRatherThanApproximated() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
ObjectMapper mapper = new ObjectMapper();
ObjectNode amex = mapper.createObjectNode();
amex.put("PrimaryAccountNumber", PAN);
amex.put("PanSequenceNumber", PSN);
ObjectNode attributes = mapper.createObjectNode();
attributes.set("Amex", amex);
AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("not approximated"), refused.getMessage());
}
@Test
void aKeyThatMayNotDeriveIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "Sign");
AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void theSequenceNumberTheModelStatesIsTheOneTheDerivationTakes() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
ObjectMapper mapper = new ObjectMapper();
ObjectNode common = mapper.createObjectNode();
common.put("PrimaryAccountNumber", PAN);
// The model states that the PAN sequence number is two digits, and the derivation
// reads the last eight bytes of the packed PAN || PSN, so a longer one moves the
// window the master key is taken from.
common.put("PanSequenceNumber", "0001");
common.put("ApplicationTransactionCounter", ATC);
ObjectNode attributes = mapper.createObjectNode();
attributes.set("EmvCommon", common);
AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("PanSequenceNumber"), refused.getMessage());
}
@Test
void transactionDataThatIsNotHexadecimalIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
AwsException refused = assertThrows(AwsException.class, () -> cryptogram.generate(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", "not hexadecimal",
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("TransactionData"), refused.getMessage());
}
@Test
void theResponseValueIsTheOneTheFirstMethodMakes() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1")
.get("AuthRequestCryptogram");
// The response attributes are what the response value is made from, and the first
// method takes the response code.
Map<String, Object> verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"AuthRequestCryptogram", arqc,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon(),
"AuthResponseAttributes", responseCode("1234"))), "us-east-1");
String value = (String) verified.get("AuthResponseValue");
assertNotNull(value);
assertEquals(16, value.length());
}
@Test
void theResponseValueIsTheOneTheSecondMethodMakes() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1")
.get("AuthRequestCryptogram");
// The second method takes the card status update and the proprietary data.
Map<String, Object> verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"AuthRequestCryptogram", arqc,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon(),
"AuthResponseAttributes", cardStatusUpdate("12345678", "ABCD"))), "us-east-1");
String value = (String) verified.get("AuthResponseValue");
assertNotNull(value);
assertEquals(8, value.length());
}
@Test
void aTransactionDataThatIsNotWholeBlocksIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
// The ISO 9797-1 MAC runs over eight-byte blocks, and the user guide tells the
// caller to pad the transaction data before sending it, so a length that is not
// a whole number of blocks is a request the cipher cannot read.
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", "0000000001000000000000000000800000",
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("TransactionData"), refused.getMessage());
assertTrue(refused.getMessage().contains("blocks"), refused.getMessage());
}
@Test
void aKeyOfAnotherAlgorithmIsRefused() {
// The key table names TDES_2KEY for the ARQC key, and the derivation reads
// sixteen bytes of material, so a three-key Triple DES key is refused.
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_3KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("TDES_2KEY"), refused.getMessage());
}
@Test
void aDisabledKeyIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createDisabledKey(service,
"TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aKeyOfTheWrongUsageIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY",
"TR31_C0_CARD_VERIFICATION_KEY", "DeriveKey");
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aKeyThatIsNotTripleDesIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "AES_128",
"TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
AwsException refused = assertThrows(AwsException.class,
() -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aResponseValueThatIsNotAskedForIsNotAnswered() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
String arqc = (String) cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1")
.get("AuthRequestCryptogram");
Map<String, Object> verified = cryptogram.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"TransactionData", TRANSACTION_DATA,
"AuthRequestCryptogram", arqc,
"MajorKeyDerivationMode", "EMV_OPTION_A",
"SessionKeyDerivationAttributes", emvCommon())), "us-east-1");
assertEquals(key.getArn(), verified.get("KeyArn"));
assertNull(verified.get("AuthResponseValue"));
}
/** The response attributes of the first ARPC method, which takes the response code. */
private static JsonNode responseCode(String code) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode method = mapper.createObjectNode();
method.put("AuthResponseCode", code);
ObjectNode outer = mapper.createObjectNode();
outer.set("ArpcMethod1", method);
return outer;
}
/** The response attributes of the second ARPC method. */
private static JsonNode cardStatusUpdate(String status, String proprietary) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode method = mapper.createObjectNode();
method.put("CardStatusUpdate", status);
method.put("ProprietaryAuthenticationData", proprietary);
ObjectNode outer = mapper.createObjectNode();
outer.set("ArpcMethod2", method);
return outer;
}
}
@@ -0,0 +1,283 @@
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.CvvCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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 card validation operations.
*
* <p>The values in the first test are the emulator's, and the emulator checks them against
* an independent implementation: the card verification value of an account number,
* an expiry and a service code.
*/
class PaymentCryptographyCardValidationOperationsTest {
private static final String PAN = "5081470082639564";
private static final String EXPIRY = "3003";
private static final String CVK = "0123456789ABCDEFFEDCBA9876543210";
private PaymentCryptographyService service;
private PaymentCryptographyCardValidationOperations cardValidation;
private final ObjectMapper mapper = new ObjectMapper();
@BeforeEach
void setUp() {
service = new PaymentCryptographyService(
new InMemoryStorage<>(),
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"));
cardValidation = new PaymentCryptographyCardValidationOperations(service);
}
/** The attributes of a card verification value: the expiry and the service code. */
private static JsonNode cardVerificationValue1(String expiry, String serviceCode) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode value = mapper.createObjectNode();
value.put("CardExpiryDate", expiry);
value.put("ServiceCode", serviceCode);
ObjectNode outer = mapper.createObjectNode();
outer.set("CardVerificationValue1", value);
return outer;
}
@Test
void theCardVerificationValueIsTheOneTheStandardGives() {
assertEquals("131", CvvCrypto.computeCvv(PAN, EXPIRY, "201", CVK, 3));
assertEquals("886", CvvCrypto.computeCvv(PAN, EXPIRY, "000", CVK, 3));
assertEquals("660", CvvCrypto.computeCvv(PAN, EXPIRY, "999", CVK, 3));
}
@Test
void aGeneratedValueVerifies() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
Map<String, Object> generated = cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1");
String value = (String) generated.get("ValidationData");
assertEquals(3, value.length());
assertEquals(cvk.getArn(), generated.get("KeyArn"));
Map<String, Object> verified = cardValidation.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationData", value,
"VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1");
assertEquals(cvk.getArn(), verified.get("KeyArn"));
}
@Test
void aWrongValueIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
AwsException refused = assertThrows(AwsException.class, () -> cardValidation.verify(
PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationData", "999",
"VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))),
"us-east-1"));
assertEquals("VerificationFailedException", refused.getErrorCode());
}
@Test
void aKeyOfTheWrongUsageIsRefused() {
PaymentCryptographyKey wrong = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
"Generate", "Verify");
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", wrong.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("TR31_C0_CARD_VERIFICATION_KEY"),
refused.getMessage());
}
@Test
void aKeyThatMayNotGenerateIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Verify");
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void anExpiryThatIsNotFourDigitsIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
// The model states that the expiry is four digits, and the card verification value
// is computed over the expiry the request carries.
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1("30", "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("CardExpiryDate"), refused.getMessage());
}
@Test
void anAccountNumberThatIsNotDigitsIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
// The model states that the account number is digits, so a formatted one is refused
// rather than read as the digits it carries.
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", "5081-4700-8263-9564",
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("PrimaryAccountNumber"), refused.getMessage());
}
@Test
void theDynamicCardVerificationCodeIsRefusedRatherThanApproximated() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS",
"Generate", "Verify", "DeriveKey");
// The dynamic code is a Mastercard proprietary construction, and there is nothing
// published to check a derivation against.
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", dynamicCardVerificationCode())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("not implemented"), refused.getMessage());
}
@Test
void theValidationDataLengthIsTheOneTheModelStates() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
// The model lets the length be three to five, and the value carries that many
// digits of the decimalised block.
cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationDataLength", 3,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1");
Map<String, Object> longer = cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationDataLength", 5,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1");
assertEquals(5, ((String) longer.get("ValidationData")).length());
}
@Test
void aLengthTheModelDoesNotStateIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
// The model states the length as three to five, so the request is refused against the
// model's own constraint rather than by a check of our own.
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationDataLength", 2,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("ValidationDataLength"), refused.getMessage());
}
@Test
void aValueTheModelDoesNotStateIsRefused() {
PaymentCryptographyKey cvk = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY",
"Generate", "Verify");
// The model states the value as three to five digits, so a shorter one is refused
// against the model's own constraint.
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.verify(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", cvk.getArn(),
"PrimaryAccountNumber", PAN,
"ValidationData", "99",
"VerificationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("ValidationData"), refused.getMessage());
}
@Test
void aDisabledKeyIsRefused() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createDisabledKey(service,
"TDES_2KEY", "TR31_C0_CARD_VERIFICATION_KEY", "Generate", "Verify");
AwsException refused = assertThrows(AwsException.class,
() -> cardValidation.generate(PaymentCryptographyTestFixtures.request(Map.of(
"KeyIdentifier", key.getArn(),
"PrimaryAccountNumber", PAN,
"GenerationAttributes", cardVerificationValue1(EXPIRY, "201"))), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
}
/** The attributes of the dynamic card verification code, which is computed over the track. */
private static JsonNode dynamicCardVerificationCode() {
return dynamicCardVerificationCode("01", "5081470082639564300303D25061010000000000");
}
/** The attributes of the dynamic card verification code, over the given track data. */
private static JsonNode dynamicCardVerificationCode(String trackData) {
return dynamicCardVerificationCode("01", trackData);
}
/**
* The attributes of the dynamic card verification code of a card with the given
* sequence number, over the given track data.
*/
private static JsonNode dynamicCardVerificationCode(String psn, String trackData) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode value = mapper.createObjectNode();
value.put("UnpredictableNumber", "12345678");
value.put("PanSequenceNumber", psn);
value.put("ApplicationTransactionCounter", "0001");
value.put("TrackData", trackData);
ObjectNode outer = mapper.createObjectNode();
outer.set("DynamicCardVerificationCode", value);
return outer;
}
}
@@ -323,6 +323,65 @@ class PaymentCryptographyCryptoHandlerTest {
assertTrue(refused.getMessage().contains("16 bytes"), refused.getMessage());
}
@Test
void aPaddingTypeIsRefused() {
// The padding type belongs to RSA, and the symmetric cipher does not pad, so a
// request that names one is refused rather than answered with a cipher that
// ignored it.
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
ObjectNode symmetric = mapper.createObjectNode();
symmetric.put("Mode", "CBC");
symmetric.put("PaddingType", "OAEP_SHA1");
ObjectNode attributes = mapper.createObjectNode();
attributes.set("Symmetric", symmetric);
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
"KeyIdentifier", key.getArn(), "PlainText", hex("hello, world!!!!".getBytes()),
"EncryptionAttributes", attributes)), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("PaddingType"), refused.getMessage());
}
@Test
void aWrappedKeyIsRefused() {
// The wrapped-key form is the key exchange, and the unwrapping is part of it, so a
// request that carries one is refused rather than answered as if the key were a
// fixed one.
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
"KeyIdentifier", key.getArn(), "PlainText", hex("hello, world!!!!".getBytes()),
"EncryptionAttributes", cbc(),
"WrappedKey", wrappedKey())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("WrappedKey"), refused.getMessage());
}
@Test
void aWrappedKeyIsRefusedOnDecryptionToo() {
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
AwsException refused = assertThrows(AwsException.class, () -> handler.decryptData(request(Map.of(
"KeyIdentifier", key.getArn(), "CipherText", "00".repeat(16),
"DecryptionAttributes", cbc(),
"WrappedKey", wrappedKey())), "us-east-1"));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("WrappedKey"), refused.getMessage());
}
/** The wrapped key the model carries, which the service refuses. */
private JsonNode wrappedKey() {
ObjectNode material = mapper.createObjectNode();
material.put("Tr31KeyBlock", "A".repeat(56));
ObjectNode wrapped = mapper.createObjectNode();
wrapped.set("WrappedKeyMaterial", material);
return wrapped;
}
@Test
void aCipherTextIsAsLongAsThePlainTextItHolds() {
// The cipher pads no data, so a ciphertext is as long as its plaintext.
@@ -11,6 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* The members that name a key, checked against the vendored constraints in every published region.
@@ -59,4 +60,24 @@ class PaymentCryptographyDataRequestShapesTest {
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void theCardOperationsAreCheckedAgainstTheModelToo() {
// The card operations' constraints are vendored, so a request that names a key by
// its identifier on its own is refused the way the other operations' is.
ObjectNode attributes = MAPPER.createObjectNode();
ObjectNode value = attributes.putObject("CardVerificationValue1");
value.put("CardExpiryDate", "3003");
value.put("ServiceCode", "201");
ObjectNode card = MAPPER.createObjectNode();
card.put("KeyIdentifier", KEY_ID);
card.put("PrimaryAccountNumber", "4111111111111111");
card.set("GenerationAttributes", attributes);
AwsException refused = assertThrows(AwsException.class,
() -> PaymentCryptographyDataRequestShapes.check("GenerateCardValidationData", card));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("KeyIdentifier"), refused.getMessage());
}
}
@@ -0,0 +1,84 @@
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.services.paymentcryptography.model.PaymentCryptographyKey;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* The builders the payment cryptography tests share.
*
* <p>A key and a request are built the same way whichever operation is under test, so
* they are built here once. A change to how they are built is then a change in one
* place.
*/
final class PaymentCryptographyTestFixtures {
private PaymentCryptographyTestFixtures() {
}
/**
* A key of the algorithm and the usage, with the modes of use the test names.
*
* @param service the service the key is made in
* @param algorithm the key's algorithm
* @param usage the key's usage
* @param modes the modes of use the key allows
* @return the key that was made
*/
static PaymentCryptographyKey createKey(PaymentCryptographyService service, String algorithm,
String usage, String... modes) {
return key(service, algorithm, usage, true, modes);
}
/**
* A key that was made disabled, and may therefore not be used.
*
* @param service the service the key is made in
* @param algorithm the key's algorithm
* @param usage the key's usage
* @param modes the modes of use the key allows
* @return the key that was made
*/
static PaymentCryptographyKey createDisabledKey(PaymentCryptographyService service, String algorithm,
String usage, String... modes) {
return key(service, algorithm, usage, false, modes);
}
private static PaymentCryptographyKey key(PaymentCryptographyService service, String algorithm,
String usage, boolean enabled, String... modes) {
Map<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, enabled, Map.of());
}
/**
* A request body of the members the test names.
*
* @param members the members of the request
* @return the body
*/
static JsonNode request(Map<String, Object> members) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
members.forEach((name, value) -> {
if (value instanceof JsonNode json) {
node.set(name, json);
} else if (value instanceof Number number) {
node.put(name, number.intValue());
} else {
node.put(name, String.valueOf(value));
}
});
return node;
}
}
@@ -0,0 +1,124 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.junit.jupiter.api.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.HexFormat;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The card verification values, against the constructions the specifications give.
*
* <p>The dynamic value is the one the Visa Contactless Payment Specification describes: the
* leftmost four digits of the account number are replaced by the transaction counter, and
* the result, the expiry and the service code are enciphered under the card's unique
* derived key. The expected value is computed here from the specification's own steps,
* with the cipher written out, so that a change to the service is a change against the
* specification rather than against itself.
*/
class CvvCryptoTest {
/** The issuer master key the unique derived key is derived from. */
private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
/** The account number of the card. */
private static final String PAN = "5081470082639564";
/** The expiry of the card, in the YYMM form the request carries. */
private static final String EXPIRY = "3003";
/** The service code of the value. */
private static final String SERVICE_CODE = "201";
/** The transaction counter, in the binary coded decimal the track data carries. */
private static final String ATC = "0001";
/** The PAN sequence number, which the unique derived key is derived with. */
private static final String PSN = "01";
@Test
void theDynamicValueIsTheOneTheSpecificationGives() {
assertEquals(dcvv(), CvvCrypto.computeDynamicValue(
PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3));
}
@Test
void theDynamicValueIsNotTheStaticValue() {
// The counter is inserted into the account number, so the value is bound to the
// transaction and is not the value of the card's fields.
assertEquals(false, CvvCrypto.computeDynamicValue(
PAN, EXPIRY, SERVICE_CODE, ATC, IMK, PSN, 3)
.equals(CvvCrypto.computeCvv(PAN, EXPIRY, SERVICE_CODE, IMK, 3)));
}
/**
* The dynamic value, written from the specification's steps.
*
* <ol>
* <li>The leftmost four digits of the account number are replaced by the counter.</li>
* <li>The result, the expiry and the service code are enciphered under the unique
* derived key: the left block is enciphered with the first half of the key, the
* result is exclusive-ored with the right block, and the block is enciphered,
* deciphered and enciphered with the two halves of the key.</li>
* <li>The three leftmost decimal digits of the result are the value.</li>
* </ol>
*/
private static String dcvv() {
String data = ATC + PAN.substring(4) + EXPIRY + SERVICE_CODE;
while (data.length() < 32) {
data = data + "0";
}
byte[] left = hex(data.substring(0, 16));
byte[] right = hex(data.substring(16, 32));
byte[] udk = EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN);
byte[] block = singleDes(left, udk, 0, false);
block = xor(block, right);
block = singleDes(block, udk, 0, false);
block = singleDes(block, udk, 8, true);
block = singleDes(block, udk, 0, false);
StringBuilder digits = new StringBuilder();
StringBuilder letters = new StringBuilder();
for (byte b : block) {
for (int nibble : new int[]{(b >> 4) & 0xf, b & 0xf}) {
if (nibble < 10) {
digits.append((char) ('0' + nibble));
} else {
letters.append((char) ('0' + nibble - 10));
}
}
}
return digits.append(letters).substring(0, 3);
}
/** One block of Single DES, with the first or the second half of the double length key. */
private static byte[] singleDes(byte[] block, byte[] key16, int half, boolean decrypt) {
byte[] key = new byte[8];
System.arraycopy(key16, half, key, 0, 8);
try {
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE,
new SecretKeySpec(key, "DES"));
return cipher.doFinal(block);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
/** The exclusive-or of two byte arrays of the same length. */
private static byte[] xor(byte[] a, byte[] b) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ b[i]);
}
return out;
}
/** The bytes of a hexadecimal string. */
private static byte[] hex(String value) {
return HexFormat.of().parseHex(value);
}
}
@@ -0,0 +1,106 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.junit.jupiter.api.Test;
import java.util.HexFormat;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The EMV derivations, against the vectors the specifications publish.
*
* <p>The ICC master key is the one EMV 4.4 Book 2 Annex A1.4.1 Option A gives, and the
* Visa Integrated Circuit Card Specification states the same rule. The session keys and the
* cryptogram are the worked examples of the M/Chip Card Application Cryptographic
* Algorithms: the MasterCard proprietary derivation and the common one, with the application
* cryptogram each produces over the same data.
*/
class EmvCryptoTest {
/** The issuer master key of the published ICC master key vector. */
private static final String IMK = "0123456789ABCDEFFEDCBA9876543210";
/** The account number of the published ICC master key vector. */
private static final String PAN = "4111111111111111";
/** The sequence number of the published ICC master key vector. */
private static final String PSN = "00";
/** The ICC master key the published vector gives. */
private static final String UDK = "31089464674C73EC851A6E0737029D19";
/** The AC master key of the M/Chip worked examples. */
private static final String MKAC = "08DF34253220A720EFF2C1343852E63D";
/** The application transaction counter of the M/Chip worked examples. */
private static final String ATC = "3456";
/** The terminal unpredictable number of the M/Chip worked examples. */
private static final String UN = "11111111";
/** The data the M/Chip worked examples compute the application cryptogram over. */
private static final String CDOL = """
00 00 00 01 00 00 00 00 00 00 10 00 08 40 00 00
00 10 80 08 40 98 07 04 00 11 11 11 11 58 00 34
56 03 A4 00 20""";
/** The application cryptogram the M/Chip worked example gives. */
private static final String ARQC = "DBC1E0B820FFE7DB";
/** The common session key the M/Chip worked example gives. */
private static final String COMMON_SESSION_KEY = "182025BA4FAB32F5A63A1BA5E6845D4E";
@Test
void theIccMasterKeyIsTheOneTheStandardGives() {
assertEquals(UDK, hex(EmvCrypto.deriveIccMasterKey(hex(IMK), PAN, PSN)));
}
@Test
void aShortAccountNumberIsPaddedOnTheLeft() {
// The block is the rightmost sixteen digits of the account number and the sequence
// number, padded on the left with zeros when they are shorter. So an account number
// that is two digits short of the field derives the key that the same number with
// those two zeros derives.
String shortNumber = "411111111111";
String paddedNumber = "00" + shortNumber;
assertArrayEquals(EmvCrypto.deriveIccMasterKey(hex(IMK), paddedNumber, "01"),
EmvCrypto.deriveIccMasterKey(hex(IMK), shortNumber, "01"));
}
@Test
void theMasterCardSessionKeyAndCryptogramAreTheOnesTheDocumentGives() {
byte[] sessionKey = EmvCrypto.deriveSessionKeyMastercard(hex(MKAC), hex(ATC), hex(UN));
assertEquals(ARQC, hex(EmvCrypto.retailMac(sessionKey, hex(CDOL), EmvCrypto.Padding.METHOD2)));
}
@Test
void theCommonSessionKeyIsTheOneTheDocumentGives() {
byte[] sessionKey = EmvCrypto.deriveSessionKey(hex(MKAC), hex(ATC));
// The document does not force the parity of the derived key, and the derivation does
// not affect the computation, so the parity bits are masked on both sides.
assertEquals(withoutParity(COMMON_SESSION_KEY), withoutParity(hex(sessionKey)));
}
/** The bytes of a hexadecimal string, the spaces and the line breaks in it ignored. */
private static byte[] hex(String value) {
return HexFormat.of().parseHex(value.replaceAll("\\s", ""));
}
/** The hexadecimal of the bytes, in the case the documents print them. */
private static String hex(byte[] value) {
return HexFormat.of().withUpperCase().formatHex(value);
}
/** The key with the DES parity bits masked, which the derivation does not affect. */
private static String withoutParity(String key) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < key.length(); i += 2) {
sb.append(String.format("%02X", Integer.parseInt(key.substring(i, i + 2), 16) & 0xFE));
}
return sb.toString();
}
}