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

@@ -67,6 +67,7 @@ import io.floci.aws.services.mwaa.MwaaController;
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.PaymentCryptographyCardController;
import io.floci.aws.services.paymentcryptography.PaymentCryptographyCryptoController;
import io.floci.aws.services.paymentcryptography.PaymentCryptographyPinController;
import io.floci.aws.services.pipes.PipesController;
@@ -325,7 +326,8 @@ public class ResolvedServiceCatalog {
// 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,
PaymentCryptographyPinController.class)),
PaymentCryptographyPinController.class,
PaymentCryptographyCardController.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,
@@ -1,6 +1,7 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import java.util.Iterator;
import java.util.Map;
@@ -33,6 +34,64 @@ final class PaymentCryptographyAttributes {
return declared == null || declared.isNull() ? "" : declared.asText("");
}
/**
* A hexadecimal member, checked to be one the cipher can read.
*
* <p>The model states the length of a hexadecimal member and does not always state an
* even one, so a member of an odd length is a request the model allows and the cipher
* cannot read. It is refused with the error the model names, rather than answered with
* a failure the caller cannot catch.
*
* @param member the member's path, for the refusal
* @param value the member's text
* @return the member's text, unchanged
*/
static String hex(String member, String value) {
if (value.length() % 2 != 0) {
throw new AwsException("ValidationException",
member + " must be an even number of hexadecimal characters", 400);
}
return value;
}
/**
* A hexadecimal member that the cipher reads as whole blocks.
*
* <p>The ISO 9797-1 MAC runs over eight-byte blocks, so the data it reads has to
* be a whole number of them. The user guide tells the caller to pad the
* transaction data before sending it, and a length that is not a whole number of
* blocks is a request the cipher cannot read, so it is refused rather than read
* as the blocks that fit.
*
* @param member the member's path, for the refusal
* @param value the member's text
* @return the member's text, unchanged
*/
static String blocks(String member, String value) {
if (value.length() % 16 != 0) {
throw new AwsException("ValidationException",
member + " must be a whole number of eight-byte blocks", 400);
}
return value;
}
/**
* Refuses the wrapped-key form of a key.
*
* <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.
*
* @param request the request to read
* @param member the member the wrapped key would come in
*/
static void refuseWrappedKey(JsonNode request, String member) {
if (request.get(member) != null) {
throw new AwsException("ValidationException",
member + " is not supported by this service", 400);
}
}
/**
* The one variant an attributes member holds.
*
@@ -0,0 +1,328 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.paymentcryptography.crypto.EmvCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
/**
* The authorization request cryptograms.
*
* <p>The ARQC is the cryptogram of an authorization request, computed under a session key that
* the transaction's key derivation produces. The session key is derived from the ICC AC master
* key, which is itself derived from the account number and the sequence number, so the whole
* chain is one derivation and the cryptogram is the ISO 9797-1 algorithm 3 retail MAC over the
* transaction data, cut to eight bytes.
*
* <p>Three derivations are served. The EMV common session key is the one the EMV common
* specification gives. The Mastercard derivation is the proprietary one, which also
* diversifies with the unpredictable number. The Visa derivation derives no session key at
* all: the transaction data is enciphered under the ICC master key, which is the Visa Smart
* Debit and Credit method.
*
* <p>Two derivations are refused rather than approximated. The American Express one is
* proprietary and there is nothing to verify it against, and a plausible wrong cryptogram is
* worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which needs the
* card's public key certificate.
*/
@ApplicationScoped
public class PaymentCryptographyAuthCryptogramOperations {
/** The hexadecimal the data plane's blobs are written in. */
private static final HexFormat HEX = HexFormat.of().withUpperCase();
/** The session key derivations. */
private enum Scheme {
/** The EMV common session key, derived from the application transaction counter. */
EMV_COMMON,
/** The Mastercard proprietary derivation, which also diversifies with the number. */
MASTERCARD,
/** No session key: the transaction data is enciphered under the ICC master key. */
VSDC
}
/** The variants that use the EMV common session key. */
private static final Set<String> COMMON_SK =
new LinkedHashSet<>(Arrays.asList("EmvCommon"));
/** The variants that derive nothing and encipher under the ICC master key. */
private static final Set<String> DIRECT_SK = new LinkedHashSet<>(Arrays.asList("Visa"));
private final PaymentCryptographyService service;
@Inject
public PaymentCryptographyAuthCryptogramOperations(PaymentCryptographyService service) {
this.service = service;
}
/** The resolved session-key derivation for a request. */
private static final class SessionKey {
final String pan;
final String psn;
final String atc;
final Scheme scheme;
final String unpredictableNumber;
final boolean optionB;
SessionKey(String pan, String psn, String atc, Scheme scheme,
String unpredictableNumber, boolean optionB) {
this.pan = pan;
this.psn = psn;
this.atc = atc;
this.scheme = scheme;
this.unpredictableNumber = unpredictableNumber;
this.optionB = optionB;
}
}
// ---- GenerateAuthRequestCryptogram ---------------------------------------
/**
* The cryptogram of an authorization request.
*/
Map<String, Object> generate(JsonNode request, String region) {
PaymentCryptographyDataRequestShapes.check("GenerateAuthRequestCryptogram", request);
String keyIdentifier = text(request, "KeyIdentifier");
String transactionData = PaymentCryptographyAttributes.blocks("TransactionData",
PaymentCryptographyAttributes.hex("TransactionData",
text(request, "TransactionData")));
SessionKey sk = resolveDerivation(request);
PaymentCryptographyKey key = requiredKey(keyIdentifier, region);
PaymentCryptographyKeyRules.requireUsage(key,
List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram");
PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram");
PaymentCryptographyKeyRules.requireDerive(key, "deriving a session key");
byte[] material = HEX.parseHex(PaymentCryptographyKeyRules.materialHex(key));
EmvCrypto.Arqc computed = computeArqc(sk, material, transactionData);
Map<String, Object> out = new LinkedHashMap<>();
out.put("KeyArn", key.getArn());
out.put("KeyCheckValue", key.getKeyCheckValue());
out.put("AuthRequestCryptogram", HEX.formatHex(computed.arqc));
return out;
}
// ---- VerifyAuthRequestCryptogram -----------------------------------------
/**
* The cryptogram of an authorization request, verified, and the response value that goes
* with it.
*/
Map<String, Object> verify(JsonNode request, String region) {
PaymentCryptographyDataRequestShapes.check("VerifyAuthRequestCryptogram", request);
String keyIdentifier = text(request, "KeyIdentifier");
String arqc = text(request, "AuthRequestCryptogram");
String transactionData = PaymentCryptographyAttributes.blocks("TransactionData",
PaymentCryptographyAttributes.hex("TransactionData",
text(request, "TransactionData")));
SessionKey sk = resolveDerivation(request);
// The response attributes are optional, and the answer carries the response value only
// when the caller asked for one.
String arpcMethod = null;
String arc = "0000";
String csu = null;
String pad = "";
JsonNode responseAttributes = request.get("AuthResponseAttributes");
if (responseAttributes != null) {
String variant = soleVariant(responseAttributes);
if (variant == null) {
throw validation("AuthResponseAttributes must specify exactly one variant");
}
if ("ArpcMethod1".equals(variant)) {
arpcMethod = "1";
JsonNode method = responseAttributes.get(variant);
arc = text(method, "AuthResponseCode");
} else if ("ArpcMethod2".equals(variant)) {
arpcMethod = "2";
JsonNode method = responseAttributes.get(variant);
csu = text(method, "CardStatusUpdate");
pad = PaymentCryptographyAttributes.hex(
"AuthResponseAttributes.ArpcMethod2.ProprietaryAuthenticationData",
text(method, "ProprietaryAuthenticationData"));
if (sk.scheme == Scheme.MASTERCARD) {
throw validation("ARPC method 2 is not used in practice with the Mastercard "
+ "session key derivation (method 1 only)");
}
if (sk.scheme == Scheme.VSDC) {
throw validation("ARPC method 2 is not used in practice with the Visa session "
+ "key derivation (method 1 only)");
}
} else {
throw validation("AuthResponseAttributes." + variant
+ " not supported by this service (ArpcMethod1, ArpcMethod2)");
}
}
PaymentCryptographyKey key = requiredKey(keyIdentifier, region);
PaymentCryptographyKeyRules.requireUsage(key,
List.of("TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"), "computing a cryptogram");
PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY", "computing a cryptogram");
PaymentCryptographyKeyRules.requireDerive(key, "deriving a session key");
byte[] material = HEX.parseHex(PaymentCryptographyKeyRules.materialHex(key));
EmvCrypto.Arqc computed = computeArqc(sk, material, transactionData);
String expected = HEX.formatHex(computed.arqc);
if (!expected.equalsIgnoreCase(arqc)) {
throw verificationFailed("the authorization request cryptogram did not verify",
"INVALID_AUTH_REQUEST_CRYPTOGRAM");
}
Map<String, Object> out = new LinkedHashMap<>();
out.put("KeyArn", key.getArn());
out.put("KeyCheckValue", key.getKeyCheckValue());
// The response key is not the session key. M/Chip 4 v1.1 section 7-4 defines
// SKARPC := MKAC for the proprietary method, and only the EMV common session key method
// sets SKARPC := SKAC. Using the session key here would encipher under a key no M/Chip
// terminal would use.
byte[] arpcKey = sk.scheme == Scheme.EMV_COMMON
? computed.sessionKey
: masterKeyOf(sk, HEX.parseHex(key.getKeyMaterialHex()));
if ("1".equals(arpcMethod)) {
out.put("AuthResponseValue", HEX.formatHex(EmvCrypto.computeArpcMethod1(
arpcKey, HEX.parseHex(arqc), arc)));
} else if ("2".equals(arpcMethod)) {
// The second method is made from the card status update and the proprietary
// data; the response code belongs to the first method.
out.put("AuthResponseValue", HEX.formatHex(EmvCrypto.computeArpcMethod2(
arpcKey, HEX.parseHex(arqc), csu, pad)));
}
return out;
}
// ---- the parts -----------------------------------------------------------
/**
* The ARQC for a resolved scheme, and the session key it was computed under.
*
* <p>The session key is derived per scheme, so this is the one place the choice is made; the
* cryptogram itself is always the ISO 9797-1 algorithm 3 retail MAC, cut to eight bytes.
*/
private static EmvCrypto.Arqc computeArqc(SessionKey sk, byte[] imk, String transactionData) {
byte[] mk = masterKeyOf(sk, imk);
byte[] atc = HEX.parseHex(sk.atc);
byte[] sessionKey;
switch (sk.scheme) {
case MASTERCARD:
sessionKey = EmvCrypto.deriveSessionKeyMastercard(
mk, atc, HEX.parseHex(sk.unpredictableNumber));
break;
case EMV_COMMON:
sessionKey = EmvCrypto.deriveSessionKey(mk, atc);
break;
case VSDC:
default:
// No session key: the transaction data is enciphered under the ICC master key,
// which is the Visa Smart Debit method.
sessionKey = mk;
break;
}
byte[] mac = EmvCrypto.retailMac(sessionKey, HEX.parseHex(transactionData),
EmvCrypto.Padding.NONE);
return new EmvCrypto.Arqc(Arrays.copyOf(mac, 8), sessionKey);
}
/**
* The ICC AC master key for the resolved derivation, which is also the M/Chip ARPC key.
*
* <p>A derivation the request cannot be read for is refused with the error the model
* names, rather than answered with a failure the caller cannot catch.
*/
private static byte[] masterKeyOf(SessionKey sk, byte[] imk) {
try {
return sk.optionB
? EmvCrypto.deriveIccMasterKeyOptionB(imk, sk.pan, sk.psn)
: EmvCrypto.deriveIccMasterKey(imk, sk.pan, sk.psn);
} catch (IllegalArgumentException e) {
throw validation(e.getMessage());
}
}
/**
* Resolves the master-key derivation mode and the session-key derivation attributes, which
* both cryptogram operations share.
*/
private static SessionKey resolveDerivation(JsonNode request) {
boolean optionB = "EMV_OPTION_B".equals(text(request, "MajorKeyDerivationMode"));
JsonNode skd = request.get("SessionKeyDerivationAttributes");
if (skd == null) {
throw validation("SessionKeyDerivationAttributes is required");
}
String variant = soleVariant(skd);
if (variant == null) {
throw validation("SessionKeyDerivationAttributes must specify exactly one variant");
}
// Amex is refused rather than approximated: the AEIPS session key derivation is
// proprietary and there is nothing to verify a derivation against, and a plausible wrong
// cryptogram is the one outcome worse than an error.
if ("Amex".equals(variant)) {
throw validation("SessionKeyDerivationAttributes.Amex requires the AEIPS session key "
+ "derivation, which this service does not implement. It is not approximated.");
}
if ("Emv2000".equals(variant)) {
throw validation("SessionKeyDerivationAttributes.Emv2000 requires the EMV 4.1 tree "
+ "derivation, which this service does not implement. It is not approximated.");
}
boolean common = COMMON_SK.contains(variant);
boolean mastercard = "Mastercard".equals(variant);
if (!common && !mastercard && !DIRECT_SK.contains(variant)) {
throw validation("SessionKeyDerivationAttributes." + variant
+ " is not a recognized variant");
}
JsonNode attrs = skd.get(variant);
String pan = text(attrs, "PrimaryAccountNumber");
String psn = text(attrs, "PanSequenceNumber");
String atc = text(attrs, "ApplicationTransactionCounter");
if (mastercard && optionB) {
// The reference implementation's own constraint: master key derivation option B is
// not used in practice with this scheme.
throw validation("MasterKeyDerivationMode EMV_OPTION_B is not used in practice with "
+ "the Mastercard session key derivation (EMV_OPTION_A only)");
}
String unpredictableNumber = null;
if (mastercard) {
// Taken from the request, never inferred: the transaction data is an opaque
// concatenated block whose layout the caller chooses, so a fixed offset would be
// right for one CDOL and silently wrong for every other.
unpredictableNumber = text(attrs, "UnpredictableNumber");
}
Scheme scheme = mastercard ? Scheme.MASTERCARD
: (common ? Scheme.EMV_COMMON : Scheme.VSDC);
return new SessionKey(pan, psn, atc, scheme, unpredictableNumber, optionB);
}
// ---- the helpers ---------------------------------------------------------
private PaymentCryptographyKey requiredKey(String identifier, String region) {
PaymentCryptographyKey key = service.findKey(region, identifier);
if (key == null) {
throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
}
PaymentCryptographyKeyRules.requireEnabled(key);
return key;
}
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
private static AwsException verificationFailed(String message, String reason) {
return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason));
}
}
@@ -0,0 +1,58 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.RegionResolver;
import jakarta.inject.Inject;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
/**
* The data plane's card validation values and the authorization cryptograms.
*
* <p>The routes are the ones the AWS SDK builds: the card validation value of a card account,
* and the cryptogram an authorization request carries.
*/
@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
public class PaymentCryptographyCardController extends PaymentCryptographyDataPlaneController {
private final PaymentCryptographyCardValidationOperations cardValidation;
private final PaymentCryptographyAuthCryptogramOperations authCryptogram;
@Inject
public PaymentCryptographyCardController(PaymentCryptographyCardValidationOperations cardValidation,
PaymentCryptographyAuthCryptogramOperations authCryptogram,
ObjectMapper objectMapper,
RegionResolver regionResolver) {
super(objectMapper, regionResolver);
this.cardValidation = cardValidation;
this.authCryptogram = authCryptogram;
}
@POST
@Path("/cardvalidationdata/generate")
public Response generateCardValidationData(String body, @Context HttpHeaders headers) {
return respond(cardValidation.generate(parse(body), region(headers)));
}
@POST
@Path("/cardvalidationdata/verify")
public Response verifyCardValidationData(String body, @Context HttpHeaders headers) {
return respond(cardValidation.verify(parse(body), region(headers)));
}
@POST
@Path("/cryptogram/generate")
public Response generateAuthRequestCryptogram(String body, @Context HttpHeaders headers) {
return respond(authCryptogram.generate(parse(body), region(headers)));
}
@POST
@Path("/cryptogram/verify")
public Response verifyAuthRequestCryptogram(String body, @Context HttpHeaders headers) {
return respond(authCryptogram.verify(parse(body), region(headers)));
}
}
@@ -0,0 +1,246 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.paymentcryptography.crypto.CvvCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
/**
* The card validation operations.
*
* <p>The card verification value is the value the issuer holds and the acquirer asks for: the
* three digits of the CVV, computed under the card verification key from the account number,
* the expiry and the service code.
*
* <p>The dynamic variants compute the value from the transaction instead: the dynamic card
* verification value from the account number and the transaction counters, and the dynamic card
* verification code from the track data. They need a key of their own usage, and one that may
* derive.
*/
@ApplicationScoped
public class PaymentCryptographyCardValidationOperations {
/** The length of the value when the request does not name one. */
private static final int DEFAULT_VALIDATION_DATA_LENGTH = 3;
/** The service code of the second card verification value, which the service fixes. */
private static final String CVV2_SERVICE_CODE = "000";
private final PaymentCryptographyService service;
@Inject
public PaymentCryptographyCardValidationOperations(PaymentCryptographyService service) {
this.service = service;
}
/**
* The card validation attributes of a request.
*/
private static final class CardAttrs {
/** The static variants: the expiry and the service code. */
String expiry;
String serviceCode;
/** The dynamic variants. */
String panSequenceNumber;
String applicationTransactionCounter;
/** Which variant this is, for the key rules and the cipher. */
String variant;
}
// ---- GenerateCardValidationData ------------------------------------------
/**
* The card validation value of a card account.
*/
Map<String, Object> generate(JsonNode request, String region) {
PaymentCryptographyDataRequestShapes.check("GenerateCardValidationData", request);
String keyIdentifier = text(request, "KeyIdentifier");
String pan = text(request, "PrimaryAccountNumber");
Integer validationDataLength = request.hasNonNull("ValidationDataLength")
? request.path("ValidationDataLength").asInt()
: null;
int length = validationDataLength == null ? DEFAULT_VALIDATION_DATA_LENGTH
: validationDataLength;
CardAttrs attrs = resolveCardAttrs(request.get("GenerationAttributes"));
PaymentCryptographyKey key = requiredKey(keyIdentifier, region);
requireKeyForVariant(key, attrs.variant, "Generate");
Map<String, Object> out = new LinkedHashMap<>();
out.put("ValidationData", computeValue(pan, attrs, key, length));
out.put("KeyArn", key.getArn());
out.put("KeyCheckValue", key.getKeyCheckValue());
return out;
}
// ---- VerifyCardValidationData --------------------------------------------
/**
* The card validation value of a card account, verified.
*/
Map<String, Object> verify(JsonNode request, String region) {
PaymentCryptographyDataRequestShapes.check("VerifyCardValidationData", request);
String keyIdentifier = text(request, "KeyIdentifier");
String pan = text(request, "PrimaryAccountNumber");
String validationData = text(request, "ValidationData");
int length = validationData.length();
CardAttrs attrs = resolveCardAttrs(request.get("VerificationAttributes"));
PaymentCryptographyKey key = requiredKey(keyIdentifier, region);
requireKeyForVariant(key, attrs.variant, "Verify");
String computed = computeValue(pan, attrs, key, length);
if (!computed.equals(validationData)) {
throw verificationFailed("the validation data did not verify",
"INVALID_VALIDATION_DATA");
}
Map<String, Object> out = new LinkedHashMap<>();
out.put("KeyArn", key.getArn());
out.put("KeyCheckValue", key.getKeyCheckValue());
return out;
}
// ---- the parts -----------------------------------------------------------
/**
* The value for the variant, under the given key.
*
* <p>A request the derivation cannot read is refused with the error the model names,
* rather than answered with a failure the caller cannot catch.
*/
private static String computeValue(String pan, CardAttrs attrs, PaymentCryptographyKey key,
int length) {
try {
return compute(pan, attrs, key, length);
} catch (RuntimeException e) {
throw validation("Unable to compute the card validation value: " + e.getMessage());
}
}
/** The value for the variant, under the given key. */
private static String compute(String pan, CardAttrs attrs, PaymentCryptographyKey key,
int length) {
if ("DynamicCardVerificationValue".equals(attrs.variant)) {
return CvvCrypto.computeDynamicValue(pan, attrs.expiry, attrs.serviceCode,
attrs.applicationTransactionCounter,
PaymentCryptographyKeyRules.materialHex(key),
attrs.panSequenceNumber, length);
}
return CvvCrypto.computeCvv(pan, attrs.expiry, attrs.serviceCode,
PaymentCryptographyKeyRules.materialHex(key), length);
}
/**
* The key the variant needs, checked against the service's rules.
*
* <p>Getting this wrong is the usual reason a call against the real service is rejected, so
* it is checked here rather than left to the cipher.
*/
private static void requireKeyForVariant(PaymentCryptographyKey key, String variant, String mode) {
if ("DynamicCardVerificationValue".equals(variant)) {
PaymentCryptographyKeyRules.requireUsage(key,
List.of("TR31_E6_EMV_MKEY_OTHER"), "deriving a dynamic card verification value");
PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY",
"deriving a dynamic card verification value");
PaymentCryptographyKeyRules.requireDerive(key, "deriving a dynamic card verification value");
return;
}
// The static values use the card verification key.
PaymentCryptographyKeyRules.requireUsage(key,
List.of("TR31_C0_CARD_VERIFICATION_KEY"), "computing a card verification value");
PaymentCryptographyKeyRules.requireAlgorithm(key, "TDES_2KEY",
"computing a card verification value");
PaymentCryptographyKeyRules.requireMode(key, mode, "Generate".equals(mode)
? "generating a card verification value"
: "verifying a card verification value");
}
/**
* The card validation attributes of a request.
*
* <p>The attributes are a union, and exactly one variant of it may be given.
*/
private static CardAttrs resolveCardAttrs(JsonNode attributes) {
String variant = soleVariant(attributes);
if (variant == null) {
throw validation("attributes must specify exactly one variant");
}
switch (variant) {
case "CardVerificationValue1": {
JsonNode value = attributes.get(variant);
String expiry = text(value, "CardExpiryDate");
String serviceCode = text(value, "ServiceCode");
CardAttrs out = new CardAttrs();
out.variant = variant;
out.expiry = expiry;
out.serviceCode = serviceCode;
return out;
}
case "CardVerificationValue2": {
JsonNode value = attributes.get(variant);
String expiry = text(value, "CardExpiryDate");
CardAttrs out = new CardAttrs();
out.variant = variant;
out.expiry = expiry;
out.serviceCode = CVV2_SERVICE_CODE;
return out;
}
case "DynamicCardVerificationValue": {
JsonNode value = attributes.get(variant);
String expiry = text(value, "CardExpiryDate");
String serviceCode = text(value, "ServiceCode");
String psn = text(value, "PanSequenceNumber");
String atc = PaymentCryptographyAttributes.hex(
variant + ".ApplicationTransactionCounter",
text(value, "ApplicationTransactionCounter"));
CardAttrs out = new CardAttrs();
out.variant = variant;
out.expiry = expiry;
out.serviceCode = serviceCode;
out.panSequenceNumber = psn;
out.applicationTransactionCounter = atc;
return out;
}
case "DynamicCardVerificationCode": {
// Refused rather than approximated: the dynamic code is a Mastercard
// proprietary construction, and there is nothing published to check a
// derivation against.
throw validation("the dynamic card verification code is not implemented: it is a "
+ "Mastercard proprietary construction and it is not approximated");
}
default:
throw validation(variant + " not supported by this service "
+ "(only CardVerificationValue1/CardVerificationValue2"
+ "/DynamicCardVerificationValue/DynamicCardVerificationCode)");
}
}
private PaymentCryptographyKey requiredKey(String identifier, String region) {
PaymentCryptographyKey key = service.findKey(region, identifier);
if (key == null) {
throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
}
PaymentCryptographyKeyRules.requireEnabled(key);
return key;
}
/**
* Checks that the key has the mode of use the operation needs.
*/
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
}
private static AwsException verificationFailed(String message, String reason) {
return new AwsException("VerificationFailedException", message, 400, Map.of("Reason", reason));
}
}
@@ -86,6 +86,7 @@ public class PaymentCryptographyCryptoHandler {
public Map<String, Object> encryptData(JsonNode request, String region) {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("EncryptData", request);
PaymentCryptographyAttributes.refuseWrappedKey(request, "WrappedKey");
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
requireMode(key, "Encrypt", "encrypt");
Encryption encryption = encryptionAttributes(request.get("EncryptionAttributes"));
@@ -104,6 +105,7 @@ public class PaymentCryptographyCryptoHandler {
public Map<String, Object> decryptData(JsonNode request, String region) {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("DecryptData", request);
PaymentCryptographyAttributes.refuseWrappedKey(request, "WrappedKey");
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
requireMode(key, "Decrypt", "decrypt");
Encryption encryption = encryptionAttributes(request.get("DecryptionAttributes"));
@@ -122,6 +124,8 @@ public class PaymentCryptographyCryptoHandler {
public Map<String, Object> reEncryptData(JsonNode request, String region) {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("ReEncryptData", request);
PaymentCryptographyAttributes.refuseWrappedKey(request, "IncomingWrappedKey");
PaymentCryptographyAttributes.refuseWrappedKey(request, "OutgoingWrappedKey");
PaymentCryptographyKey incoming = requiredKey(request, region, "IncomingKeyIdentifier");
requireMode(incoming, "Decrypt", "decrypt");
PaymentCryptographyKey outgoing = requiredKey(request, region, "OutgoingKeyIdentifier");
@@ -107,6 +107,46 @@ final class PaymentCryptographyKeyRules {
}
}
/**
* The algorithm a key has to have for an operation.
*
* <p>The algorithm is what the cipher runs, so the operation names the one it is
* defined over: a Triple DES key and an AES key are different ciphers, and so are
* the two Triple DES forms.
*
* @param key the key the operation runs under
* @param algorithm the algorithm the operation needs
* @param what the operation, for the message
*/
static void requireAlgorithm(PaymentCryptographyKey key, String algorithm, String what) {
if (!algorithm.equals(key.getKeyAlgorithm())) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
+ what + " needs a " + algorithm + " one", 400);
}
}
/**
* The mode of use a key has to have to derive from it.
*
* <p>A derivation reads the key, so the key has to allow it. A key with no modes
* of use allows nothing, and is refused here rather than read.
*
* @param key the key the operation runs under
* @param what the operation, for the message
*/
static void requireDerive(PaymentCryptographyKey key, String what) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
boolean derives = modes != null
&& (Boolean.TRUE.equals(modes.get("DeriveKey"))
|| Boolean.TRUE.equals(modes.get("NoRestrictions")));
if (!derives) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " does not have the mode of use DeriveKey, "
+ "which it needs to " + what, 400);
}
}
/**
* The material of a key.
*
@@ -504,9 +504,7 @@ public class PaymentCryptographyPinOperations {
* 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");
}
PaymentCryptographyAttributes.refuseWrappedKey(request, member);
}
private static PinBlockFormat format(String wireName) {
@@ -137,6 +137,17 @@ public final class Ciphers {
return block(new DESEngine(), true, block8, key8);
}
/**
* The Single DES decryption of a block under a key, in ECB mode.
*
* @param block8 the eight-byte block to decrypt
* @param key8 the eight-byte key
* @return the decrypted block
*/
public static byte[] tdesSingleDesDecrypt(byte[] block8, byte[] key8) {
return block(new DESEngine(), false, block8, key8);
}
/**
* The Triple DES encryption of data under a two-key key, in CBC mode.
*
@@ -0,0 +1,119 @@
package io.floci.aws.services.paymentcryptography.crypto;
import java.util.HexFormat;
/**
* Visa CVV / Mastercard CVC - the standard X9 card-verification algorithm.
*
* <p>One routine serves CVV1, CVV2 (service code 000) and iCVV (service code
* 999); only the inputs differ.
*
* <pre>
* data = (PAN || expiry || serviceCode), right-padded with '0' to 32 hex
* B1, B2 = the two 8-byte blocks
* r = 3DES_EDE(CVK, DES_e(B1, CVK-A) XOR B2) with CVK = CVK-A || CVK-B
* value = decimalize(r, 3)
* </pre>
*/
public final class CvvCrypto {
/** The hexadecimal the data plane's blobs are written in. */
private static final HexFormat HEX = HexFormat.of().withUpperCase();
private CvvCrypto() {
}
/** Compute the 3-digit card verification value. {@code cvkHex} is CVK-A || CVK-B. */
public static String computeCvv(String pan, String expiryYYMM, String serviceCode,
String cvkHex, int length) {
byte[] cvk = HEX.parseHex(cvkHex);
if (cvk.length != 16) {
throw new IllegalArgumentException("CVK must be 16 bytes (32 hex)");
}
return decimalize(PinCrypto.digits(pan) + PinCrypto.digits(expiryYYMM)
+ PinCrypto.digits(serviceCode), cvk, length);
}
/**
* The dynamic card verification value (dCVV).
*
* <p>Visa's construction: the leftmost four digits of the account number are replaced by
* the transaction counter, and the result, the expiry and the service code are
* enciphered under the card's unique derived key. The three leftmost decimal digits of
* the result are the value.
*
* <pre>
* altered PAN = the leftmost four digits of the PAN replaced by the counter
* r = 3DES_EDE(UDK, DES_e(B1, UDK-A) XOR B2) over altered PAN || expiry || service code
* value = decimalize(r, 3)
* </pre>
*
* <p>The key is the unique derived key the card is personalised with, which the issuer
* derives from the master key with the account number and the PAN sequence number. The
* counter diversifies the value by the data it is inserted into, not by the key.
*/
public static String computeDynamicValue(String pan, String expiryYYMM, String serviceCode,
String atcHex, String emkHex, String psn,
int length) {
byte[] udk = EmvCrypto.deriveIccMasterKey(HEX.parseHex(emkHex), pan, psn);
return decimalize(alteredPan(pan, atcHex) + PinCrypto.digits(expiryYYMM)
+ PinCrypto.digits(serviceCode), udk, length);
}
/**
* The account number with its leftmost four digits replaced by the transaction counter.
*
* <p>The counter is a binary coded decimal counter, so its digits are the four decimal
* digits of its bytes, and only the rightmost four of them are inserted.
*/
private static String alteredPan(String pan, String atcHex) {
String digits = PinCrypto.digits(pan);
String counter = atcHex;
if (counter.length() > 4) {
counter = counter.substring(counter.length() - 4);
}
StringBuilder altered = new StringBuilder(counter.length() + digits.length());
for (int i = 0; i < counter.length(); i++) {
char c = counter.charAt(i);
if (c < '0' || c > '9') {
throw new IllegalArgumentException(
"the transaction counter must be a binary coded decimal counter");
}
altered.append(c);
}
while (altered.length() < 4) {
altered.insert(0, '0');
}
return altered.append(digits.substring(4)).toString();
}
/**
* The card verification cipher: two blocks, the left one enciphered with
* the key's left half, exclusive-or the right one, then enciphered again
* with the whole key.
*
* @param input hexadecimal input, at most 32 characters, zero-padded
*/
private static String decimalize(String input, byte[] key, int length) {
if (input.length() > 32) {
throw new IllegalArgumentException("the input exceeds two blocks");
}
StringBuilder padded = new StringBuilder();
padded.append(input);
while (padded.length() < 32) {
padded.append('0');
}
String p = padded.substring(0, 32);
byte[] b1 = HEX.parseHex(p.substring(0, 16));
byte[] b2 = HEX.parseHex(p.substring(16, 32));
byte[] r = Ciphers.tdes2Encrypt(Ciphers.xor(Ciphers.tdesSingleDesEncrypt(b1, slice(key, 0, 8)), b2), key);
return Decimalize.of(HEX.formatHex(r), length);
}
private static byte[] slice(byte[] b, int from, int to) {
byte[] out = new byte[to - from];
System.arraycopy(b, from, out, 0, to - from);
return out;
}
}
@@ -0,0 +1,348 @@
package io.floci.aws.services.paymentcryptography.crypto;
import io.floci.aws.core.common.Digests;
import java.util.HexFormat;
/**
* The canonical EMV ARQC/ARPC spine, and the primitives it rests on.
*
* <pre>
* 1. ICC master key derivation (EMV Book 2, Option A) IMK + PAN + PSN -&gt; MK
* 2. Common session key derivation (EMV Book 2 A1.3.1) MK + ATC -&gt; SK
* 3. ARQC = ISO 9797-1 MAC algorithm 3 over the transaction data, truncated to 8 bytes
* 4. ARPC method 1 = 3DES_EDE(SK, ARQC XOR (ARC || 00*6))
* </pre>
*
* <p>The transaction data reaches the service already padded, because the caller pads it
* the way the card padded it before the card enciphered it. The service enciphers it as
* it was sent, and the padding the service applies is the one it applies to the input it
* builds itself, which is the issuer authentication cryptogram.
*
* <p>All DES is done through three-key TDES rather than a single-DES provider:
* single DES is expressed as TDES with K||K||K.
*
* <p>The full PAN flows into master key derivation, because the derivation is
* defined over the whole of it.
*/
public final class EmvCrypto {
/** The hexadecimal the data plane's blobs are written in. */
private static final HexFormat HEX = HexFormat.of().withUpperCase();
private EmvCrypto() {
}
// ---- primitives ---------------------------------------------------------
/** Force every DES key byte to odd parity. */
public static byte[] adjustDesParity(byte[] key) {
byte[] out = new byte[key.length];
for (int i = 0; i < key.length; i++) {
int b = key[i] & 0xff;
int p = 0;
// The parity bit is bit 0; XOR bits 1..7, then force the byte odd.
for (int bit = 1; bit < 8; bit++) {
p ^= (b >> bit) & 1;
}
out[i] = (byte) ((b & 0xfe) | ((p ^ 0x01) & 0x01));
}
return out;
}
/**
* The ISO 9797-1 padding method used for an application cryptogram.
*
* <p>The transaction data reaches the service already padded: the user guide tells
* the caller to pad it before sending it, because the card padded it the same way
* before it enciphered it. The service therefore enciphers the data as it was
* given, and padding it again would encipher a block the card never enciphered.
*/
public enum Padding {
/**
* No padding: the data is enciphered exactly as it was given.
*/
NONE,
/**
* Method 2: append {@code 0x80}, then zeros to the next boundary,
* always adding a block even when the data is already aligned. The input of
* an issuer authentication cryptogram is built here rather than by the
* caller, so it is this one that is padded.
*/
METHOD2
}
/** Pad according to the given method. */
public static byte[] pad(byte[] data, Padding padding) {
return switch (padding) {
case NONE -> data;
case METHOD2 -> pad80(data);
};
}
/**
* ISO/IEC 9797-1 padding method 2: append {@code 0x80}, then zeros to the
* next 8-byte boundary. Always pads a block, so a block-aligned input gains
* a whole extra block.
*/
public static byte[] pad80(byte[] data) {
int total = data.length - (data.length % 8) + 8;
byte[] out = new byte[total];
System.arraycopy(data, 0, out, 0, data.length);
out[data.length] = (byte) 0x80;
return out;
}
/**
* ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key.
*
* <p>This is single-DES chaining, not three-key TDES. The key splits into
* K1 (left 8) and K2 (right 8); each block is enciphered under K1, and a
* single D_KR then E_KL final transform closes the tag:
*
* <pre>
* H_i = E_KL(D_i XOR H_{i-1}) for i = 1..n
* MAC = E_KL(D_KR(H_n))
* </pre>
*
* <p>Running a 3DES transform per block instead - the obvious reading -
* produces a different MAC.
*/
/** The retail MAC over data padded with the given ISO 9797-1 method. */
public static byte[] retailMac(byte[] key16, byte[] data, Padding padding) {
byte[] kl = slice(key16, 0, 8);
byte[] kr = slice(key16, 8, 16);
byte[] padded = pad(data, padding);
int nBlocks = padded.length / 8;
byte[] h = new byte[8];
for (int i = 0; i < nBlocks; i++) {
h = Ciphers.tdesSingleDesEncrypt(Ciphers.xor(h, slice(padded, i * 8, i * 8 + 8)), kl);
}
return Ciphers.tdesSingleDesEncrypt(Ciphers.tdesSingleDesDecrypt(h, kr), kl);
}
// ---- EMV key derivation -------------------------------------------------
/**
* EMV Book 2 Option A ICC master key derivation.
*
* <pre>
* Y = the RIGHT-MOST 16 digits of PAN || PSN, left-padded with zeros when shorter
* ZR = Y XOR FF..FF
* MK = 3DES(IMK, Y) || 3DES(IMK, ZR), odd parity adjusted
* </pre>
*
* <p>Y is the last sixteen digits, not the first. For a 16-digit PAN the two differ,
* and using the first changes the master key and every tag that follows. The rule is the
* one EMV 4.4 Book 2 Annex A1.4.1 gives, and the Visa Integrated Circuit Card
* Specification states it the same way: the rightmost sixteen digits of the PAN and the
* sequence number, padded on the left with zeros when they are shorter.
*/
public static byte[] deriveIccMasterKey(byte[] imk16, String pan, String psn) {
byte[] y = masterKeyInput(pan, psn);
byte[] zr = new byte[8];
for (int i = 0; i < 8; i++) {
zr[i] = (byte) (y[i] ^ 0xff);
}
return adjustDesParity(concat(
Ciphers.tdes2Encrypt(y, imk16),
Ciphers.tdes2Encrypt(zr, imk16)));
}
/**
* EMV Book 2 Option B master key derivation, for PANs longer than 16 digits.
*
* <pre>
* H = SHA-1(PAN || PSN as packed BCD)
* Y = the leftmost 16 digits of {H's decimal digits || H's other nibbles mod 10}
* MK = 3DES(IMK, Y) || 3DES(IMK, Y XOR FF..FF)
* </pre>
*
* <p>The decimal digits of the hash come first, in the order they appear, and the
* nibbles that are not decimal digits follow them, each reduced modulo ten. A hash
* of a packed account number and sequence number holds sixteen decimal digits
* almost every time, so the second part is rarely reached.
*
* <p>A PAN of sixteen digits or fewer is derived the Option A way: the hash is
* only there for the longer numbers.
*/
public static byte[] deriveIccMasterKeyOptionB(byte[] imk16, String pan, String psn) {
if (PinCrypto.digits(pan).length() <= 16) {
return deriveIccMasterKey(imk16, pan, psn);
}
byte[] b = packedBcd(pan, psn);
String hash = HEX.formatHex(Digests.sha1(b));
StringBuilder decimal = new StringBuilder(hash.length());
StringBuilder other = new StringBuilder(hash.length());
for (int i = 0; i < hash.length(); i++) {
char c = hash.charAt(i);
if (c >= '0' && c <= '9') {
decimal.append(c);
} else {
other.append((char) ('0' + (c - 'A')));
}
}
StringBuilder y = new StringBuilder(decimal).append(other);
if (y.length() < 16) {
throw new IllegalArgumentException("Option B: the SHA-1 hash yields fewer than 16 digits");
}
byte[] zl = HEX.parseHex(y.substring(0, 16));
byte[] zr = new byte[8];
for (int i = 0; i < 8; i++) {
zr[i] = (byte) (zl[i] ^ 0xff);
}
return adjustDesParity(concat(
Ciphers.tdes2Encrypt(zl, imk16),
Ciphers.tdes2Encrypt(zr, imk16)));
}
/**
* The EMV common session key (EMV 4.2 Book 2 Annex A1.3.1).
*
* <pre>
* F1 = ATC(2) || F0 || 00*5 SK_L = 3DES(MK, F1)
* F2 = ATC(2) || 0F || 00*5 SK_R = 3DES(MK, F2)
* </pre>
*
* <p>Each half carries odd DES parity.
*/
public static byte[] deriveSessionKey(byte[] mk16, byte[] atc) {
byte[] r = new byte[8];
System.arraycopy(atc, 0, r, 0, Math.min(2, atc.length));
return sessionKeyFromDiversifier(mk16, r);
}
/**
* The MasterCard proprietary session key derivation (M/Chip).
*
* <p>Identical to the EMV common session key except for the 8-byte
* diversification input, which here is the low two bytes of the application
* transaction counter followed by the low four bytes of the terminal's
* unpredictable number, rather than the counter followed by zeros.
*
* <p>Both halves still carry odd DES parity, as the MasterCard method
* requires.
*
* @param unpredictableNumber the terminal-generated unpredictable number; its
* low four bytes are used
*/
public static byte[] deriveSessionKeyMastercard(byte[] mk16, byte[] atc,
byte[] unpredictableNumber) {
byte[] r = new byte[8];
// The LOW bytes, so an over-long counter or
// unpredictable number gives the same result on both sides.
int atcFrom = Math.max(0, atc.length - 2);
System.arraycopy(atc, atcFrom, r, 0, Math.min(2, atc.length));
int unFrom = Math.max(0, unpredictableNumber.length - 4);
System.arraycopy(unpredictableNumber, unFrom, r, 4, Math.min(4, unpredictableNumber.length));
return sessionKeyFromDiversifier(mk16, r);
}
/** The shared tail of both derivations: the 0xF0/0x0F halves, enciphered, parity adjusted. */
private static byte[] sessionKeyFromDiversifier(byte[] mk16, byte[] r) {
byte[] f1 = r.clone();
f1[2] = (byte) 0xf0;
byte[] f2 = r.clone();
f2[2] = (byte) 0x0f;
return adjustDesParity(concat(
Ciphers.tdes2Encrypt(f1, mk16),
Ciphers.tdes2Encrypt(f2, mk16)));
}
// ---- cryptograms --------------------------------------------------------
/** An ARQC together with the session key it was computed under. */
public static final class Arqc {
public final byte[] arqc;
public final byte[] sessionKey;
public Arqc(byte[] arqc, byte[] sessionKey) {
this.arqc = arqc;
this.sessionKey = sessionKey;
}
}
/**
* ARPC method 1: {@code 3DES_EDE(SK, ARQC XOR (ARC || 00*6))}.
*
* @param arcHex the authorization response code, right-padded to 8 bytes
*/
public static byte[] computeArpcMethod1(byte[] sk, byte[] arqc, String arcHex) {
byte[] arc = HEX.parseHex(arcHex);
byte[] x = new byte[8];
System.arraycopy(arc, 0, x, 0, Math.min(8, arc.length));
return Ciphers.tdes2Encrypt(Ciphers.xor(arqc, x), sk);
}
/**
* ARPC method 2, the CSU-based one: the leftmost 4 bytes of the retail MAC
* over {@code ARQC || CSU || proprietary} under the session key.
*
* <p>The response code belongs in the input of the first method. The second
* method has none: the card status update and the proprietary data are what
* it is made from, and EMV Book 2 section 8.2.2 says so.
*
* <p>The request carries no way to ask for the other form: the model gives
* the card status update and the proprietary data, and nothing else.
*/
public static byte[] computeArpcMethod2(byte[] sk, byte[] arqc,
String csuHex, String padHex) {
byte[] data = concat(
arqc,
csuHex == null ? new byte[0] : HEX.parseHex(csuHex),
padHex == null ? new byte[0] : HEX.parseHex(padHex));
return slice(retailMac(sk, data, Padding.METHOD2), 0, 4);
}
// ---- helpers ------------------------------------------------------------
/** PAN concatenated with PSN as packed BCD, left-zero-padded to an even nibble count. */
static byte[] packedBcd(String pan, String psn) {
String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn);
if (digits.isEmpty()) {
throw new IllegalArgumentException("PAN and PSN must contain digits");
}
if (digits.length() % 2 != 0) {
digits = "0" + digits;
}
return HEX.parseHex(digits);
}
/**
* The block the ICC master key is derived over: the rightmost sixteen digits of the PAN
* and the PAN sequence number, padded on the left with zeros when they are shorter.
*/
private static byte[] masterKeyInput(String pan, String psn) {
String digits = PinCrypto.digits(pan) + PinCrypto.digits(psn == null ? "00" : psn);
if (digits.isEmpty()) {
throw new IllegalArgumentException("PAN and PSN must contain digits");
}
if (digits.length() > 16) {
digits = digits.substring(digits.length() - 16);
}
while (digits.length() < 16) {
digits = "0" + digits;
}
return HEX.parseHex(digits);
}
private static byte[] slice(byte[] b, int from, int to) {
byte[] out = new byte[to - from];
System.arraycopy(b, from, out, 0, to - from);
return out;
}
private static byte[] concat(byte[]... parts) {
int n = 0;
for (byte[] p : parts) {
n += p.length;
}
byte[] out = new byte[n];
int at = 0;
for (byte[] p : parts) {
System.arraycopy(p, 0, out, at, p.length);
at += p.length;
}
return out;
}
}