feat(paymentcryptography): the data plane as a service of its own (#7396)

* feat(paymentcryptography): the data plane as a service of its own

docs(paymentcryptography): the data plane has a page of its own

fix(paymentcryptography): a MAC under a three-key Triple DES key is computed

test(paymentcryptography): a key of another purpose does not encrypt data

feat(paymentcryptography): the data plane's IAM is generated

fix(paymentcryptography): a DUKPT MAC needs a base derivation key

fix(paymentcryptography): a key whose material is not held is refused

docs(paymentcryptography): the data plane's example runs

test(paymentcryptography): the data plane through the AWS SDK

test(paymentcryptography): the data plane through the AWS CLI

fix(paymentcryptography): the CLI test removes the keys it makes

docs(compat): the AWS CLI suite names the data plane

test(paymentcryptography): the route is read as the registry reads it

test(paymentcryptography): the request names its method and its URI

fix(paymentcryptography): the cipher pads no data

fix(paymentcryptography): the data plane takes the service scope

fix(paymentcryptography): a MAC length that is not a number is refused

docs(paymentcryptography): the data plane says the cipher pads no data

fix(paymentcryptography): the data plane ciphers with Triple DES as well

fix(paymentcryptography): the scope alias names the model's scope

fix(paymentcryptography): the Triple DES cipher is BouncyCastle's

fix(paymentcryptography): the usage and the blob keep their comments

fix(paymentcryptography): a key's family is read from its algorithm

fix(paymentcryptography): the cipher reads the vector through one helper

test(paymentcryptography): the keys are built by one builder

fix(paymentcryptography): the data plane checks the model's rules

fix(paymentcryptography): the Triple DES check value is BouncyCastle's

fix(paymentcryptography): the SDK names it TDES_2_KEY

docs(contributing): the ciphers come from BouncyCastle

refactor(paymentcryptography): the model owns the request shapes

refactor(paymentcryptography): the ciphers are BouncyCastle's

test(compat): one helper makes a key of either algorithm

docs(contributing): the cipher rule comes out

fix(paymentcryptography): the refusals are the model's

refactor(paymentcryptography): the ciphers are one helper each

refactor(paymentcryptography): the generators share the helper

docs(paymentcryptography): the javadocs name both ciphers

test(aws): the moved constants read from the shared helper

fix(paymentcryptography): the deprecated cipher constructors go

chore(paymentcryptography): the duplicate import goes

test(paymentcryptography): the DUKPT vectors the standard publishes

fix(paymentcryptography): the DUKPT refusal is the derivation's

docs(paymentcryptography): the retail MAC is over a double-length key

fix(paymentcryptography): the ISO 9797-1 MAC pads only a partial block

refactor(paymentcryptography): the refusals the model already makes

chore(aws): the routes are generated from the models again

* chore(aws): the IAM resources are generated again
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-06 20:05:00 -04:00
1 parent ae196fb9ac
commit 4617e4a4f8
45 files changed
+3942 -356

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.PaymentCryptographyCryptoController;
import io.floci.aws.services.pipes.PipesController;
import io.floci.aws.services.quicksight.QuickSightController;
import io.floci.aws.services.quicksight.QuickSightEmbedController;
@@ -122,7 +123,11 @@ public class ResolvedServiceCatalog {
* directory-bucket requests as {@code s3express} while the actions, ARNs and condition keys
* remain {@code s3}; the IoT Jobs Data Plane signs as {@code iot-jobs-data} while its actions
* are {@code iot:} ({@code iot:DescribeJobExecution} and peers in the Service Authorization
* Reference). Keep this minimal: every entry suppresses a distinct IAM namespace.
* Reference); the Payment Cryptography data plane's model signs as
* {@code payment-cryptography}, the service the control plane signs for as well, while a
* client that signs under the data plane's own name {@code payment-cryptography-data} is
* served as that same namespace, whose actions are {@code payment-cryptography:}. Keep
* this minimal: every entry suppresses a distinct IAM namespace.
*/
private static final Map<String, String> CREDENTIAL_SCOPE_ALIASES =
Map.of(
@@ -130,7 +135,8 @@ public class ResolvedServiceCatalog {
"iot-jobs-data", "iot",
"monitoring", "cloudwatch",
"awsssoportal", "sso",
"eventsv2", "events");
"eventsv2", "events",
"payment-cryptography-data", "payment-cryptography");
private final ServiceCatalog catalog;
@@ -304,6 +310,19 @@ public class ResolvedServiceCatalog {
protocols(ServiceProtocol.JSON),
Set.of("PaymentCryptographyControlPlane."), Set.of("payment-cryptography"),
Set.of(), Set.of()),
descriptor("payment-cryptography-data", "paymentcryptography",
config.services().paymentcryptography().enabled(), true,
"paymentcryptography",
storageMode(config.storage().services().paymentcryptography().mode(),
config.storage().mode()),
config.storage().services().paymentcryptography().flushIntervalMs(), null,
ServiceProtocol.REST_JSON,
protocols(ServiceProtocol.REST_JSON),
// The data plane is a rest-json service of its own, and its client
// signs for the service, which is one scope for both of its planes; the
// scope its own plane is named by is an alias of that one.
Set.of(), Set.of("payment-cryptography", "payment-cryptography-data"), Set.of(),
Set.of(PaymentCryptographyCryptoController.class)),
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,
@@ -5,6 +5,7 @@ import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
/**
@@ -26,7 +27,7 @@ import java.util.function.Predicate;
public final class SignedServiceRoute {
private final ResolvedServiceCatalog catalog;
private final String externalKey;
private final Set<String> externalKeys;
private final String internalPrefix;
private final Predicate<String> publicPaths;
@@ -37,12 +38,25 @@ public final class SignedServiceRoute {
*/
public SignedServiceRoute(ResolvedServiceCatalog catalog, String externalKey, String internalPrefix,
Predicate<String> publicPaths) {
this(catalog, Set.of(externalKey), internalPrefix, publicPaths);
}
/**
* A service with more than one plane has one external key per plane, and a request signed for
* either of them belongs to the service.
*
* @param externalKeys the service's external keys, one per plane
* @param internalPrefix one path segment beginning with an underscore, such as {@code /_dlm}
* @param publicPaths which normalized request paths are the service's contested routes
*/
public SignedServiceRoute(ResolvedServiceCatalog catalog, Set<String> externalKeys, String internalPrefix,
Predicate<String> publicPaths) {
if (!internalPrefix.startsWith("/_") || internalPrefix.indexOf('/', 1) >= 0) {
throw new IllegalArgumentException("Internal prefix must be one segment starting with '/_': "
+ internalPrefix);
}
this.catalog = catalog;
this.externalKey = externalKey;
this.externalKeys = Set.copyOf(externalKeys);
this.internalPrefix = internalPrefix;
this.publicPaths = publicPaths;
}
@@ -84,7 +98,7 @@ public final class SignedServiceRoute {
return signingService(ctx)
.flatMap(catalog::byCredentialScope)
.map(ServiceDescriptor::externalKey)
.filter(externalKey::equals)
.filter(externalKeys::contains)
.isPresent();
}
@@ -1,15 +1,11 @@
package io.floci.aws.services.paymentcryptography;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.Locale;
/**
* The cryptography a key record needs: its material, its check value, and the operations the
@@ -20,21 +16,30 @@ import java.util.Locale;
* CMAC check value, and what the reference implementation its samples use
* computes.
*
* <p>The data plane encrypts with AES in CBC mode and the padding the service calls PKCS#5,
* which is PKCS#7 for a block cipher, and answers with the initialization vector and the
* ciphertext in one blob. The MAC is the CMAC of the message under the key, cut to the
* length the caller asks for.
* <p>The data plane encrypts with AES or Triple DES in CBC mode and pads no data, so the
* caller supplies whole blocks and the ciphertext is as long as the plaintext it holds, and
* answers with the initialization vector and the ciphertext in one blob. The MAC is the CMAC of
* the message under the key, cut to the length the caller asks for.
*/
final class PaymentCryptographyCrypto {
private static final byte[] ZERO_BLOCK = new byte[16];
/** The hexadecimal the key material is written in. */
private static final HexFormat HEX = HexFormat.of();
/** The hexadecimal a check value is written in: the capitals the reference writes it in. */
private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase();
/** The block size of AES, in bytes. */
private static final int BLOCK = 16;
/** The initialization vector of a CBC encryption, in bytes. */
private static final int IV_LENGTH = 16;
/** The initialization vector of a Triple DES CBC encryption, in bytes. */
private static final int TDES_IV_LENGTH = 8;
/** The initial value of a key wrap, which the standard gives as it. */
private static final byte[] INITIAL_VALUE = {
(byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6,
@@ -69,7 +74,7 @@ final class PaymentCryptographyCrypto {
: tdesEcbEncrypt(new byte[8], key);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
return HEX_UPPER.formatHex(value);
}
/** The check value of a key of that algorithm, from the key's bytes. */
@@ -79,7 +84,7 @@ final class PaymentCryptographyCrypto {
: tdesEcbEncrypt(new byte[8], key);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
return HEX_UPPER.formatHex(value);
}
/** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
@@ -87,36 +92,25 @@ final class PaymentCryptographyCrypto {
byte[] mac = cmac(fromHex(keyHex), ZERO_BLOCK);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
return HEX_UPPER.formatHex(value);
}
/**
* The Triple DES encryption of a block under a key, in ECB mode.
* The Triple DES encryption of one block under a key, in ECB mode.
*
* <p>The check value of a Triple DES key is the leftmost three bytes of the encrypted
* zeroes, so the block is encrypted and the first three bytes are taken.
*
* @param data the bytes to encrypt
* <p>BouncyCastle's cipher is used rather than the JCE's, whose Triple DES is not
* registered in the native image: a request that needs it there hangs until the job
* is cancelled at its timeout.
*
* @param block8 the eight-byte block to encrypt
* @param key the key, sixteen or twenty-four bytes
* @return the encrypted bytes
*/
private static byte[] tdesEcbEncrypt(byte[] data, byte[] key) {
try {
byte[] key24 = key.length == 24 ? key : widenTdesKey(key);
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key24, "DESede"));
return cipher.doFinal(data);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the Triple DES key could not be used", e);
}
}
/** A two-key Triple DES key widened to the three the cipher takes. */
private static byte[] widenTdesKey(byte[] key) {
byte[] wide = new byte[24];
System.arraycopy(key, 0, wide, 0, 16);
System.arraycopy(key, 0, wide, 16, 8);
return wide;
private static byte[] tdesEcbEncrypt(byte[] block8, byte[] key) {
return Ciphers.tdes2Encrypt(block8, key);
}
/**
@@ -127,30 +121,26 @@ final class PaymentCryptographyCrypto {
* subkey when it is whole and with the second when it is padded.
*/
static byte[] cmac(byte[] key, byte[] message) {
try {
byte[] k1 = subkeyOne(key);
byte[] k2 = shiftLeft(k1);
int blocks = Math.max(1, (message.length + BLOCK - 1) / BLOCK);
byte[] last = new byte[BLOCK];
int lastLength = message.length - (blocks - 1) * BLOCK;
System.arraycopy(message, (blocks - 1) * BLOCK, last, 0, lastLength);
if (lastLength == BLOCK) {
last = xor(last, k1);
} else {
// The padding of a partial block is a one bit and zeroes, as the standard says.
last[lastLength] = (byte) 0x80;
last = xor(last, k2);
}
byte[] state = new byte[BLOCK];
for (int i = 0; i < blocks - 1; i++) {
byte[] block = new byte[BLOCK];
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
state = encrypt(xor(state, block), key);
}
return encrypt(xor(state, last), key);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
byte[] k1 = subkeyOne(key);
byte[] k2 = shiftLeft(k1);
int blocks = Math.max(1, (message.length + BLOCK - 1) / BLOCK);
byte[] last = new byte[BLOCK];
int lastLength = message.length - (blocks - 1) * BLOCK;
System.arraycopy(message, (blocks - 1) * BLOCK, last, 0, lastLength);
if (lastLength == BLOCK) {
last = Ciphers.xor(last, k1);
} else {
// The padding of a partial block is a one bit and zeroes, as the standard says.
last[lastLength] = (byte) 0x80;
last = Ciphers.xor(last, k2);
}
byte[] state = new byte[BLOCK];
for (int i = 0; i < blocks - 1; i++) {
byte[] block = new byte[BLOCK];
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
state = Ciphers.aesEcbEncrypt(Ciphers.xor(state, block), key);
}
return Ciphers.aesEcbEncrypt(Ciphers.xor(state, last), key);
}
/**
@@ -161,11 +151,7 @@ final class PaymentCryptographyCrypto {
* the top.
*/
private static byte[] subkeyOne(byte[] key) {
try {
return shiftLeft(encrypt(ZERO_BLOCK, key));
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
return shiftLeft(Ciphers.aesEcbEncrypt(ZERO_BLOCK, key));
}
/**
@@ -199,74 +185,78 @@ final class PaymentCryptographyCrypto {
return out;
}
/**
* The ciphertext of a plaintext under a key: the initialization vector and the encrypted
* bytes in one blob, which is how the service answers.
*/
static byte[] encryptCbc(byte[] key, byte[] plaintext, SecureRandom random) {
return encryptCbc(key, plaintext, null, random);
}
/**
* The ciphertext of a plaintext under a key, with the initialization vector the request
* names.
*
* <p>A request that names a vector gets the ciphertext under it, so two parties that
* agree on the vector can read each other's ciphertext. A request that names none gets a
* fresh one.
* zero vector, which is what the reference uses.
*
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for a fresh one
* @param random the randomness a fresh vector comes from
* @return the vector and the encrypted bytes in one blob
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @return the encrypted bytes
*/
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector,
SecureRandom random) {
try {
byte[] iv;
if (initializationVector == null) {
iv = new byte[IV_LENGTH];
random.nextBytes(iv);
} else {
if (initializationVector.length != IV_LENGTH) {
throw new IllegalArgumentException("the initialization vector is "
+ initializationVector.length + " bytes; it is " + IV_LENGTH);
}
iv = initializationVector.clone();
}
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
byte[] encrypted = cipher.doFinal(plaintext);
byte[] out = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, out, 0, iv.length);
System.arraycopy(encrypted, 0, out, iv.length, encrypted.length);
return out;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector) {
return aesCbcEncrypt(key, vector(initializationVector, IV_LENGTH), plaintext);
}
/**
* The plaintext of a blob the service encrypted.
* The plaintext of a ciphertext the service encrypted.
*
* <p>The blob is the initialization vector and the ciphertext, so the vector is read first
* and the rest is decrypted under it. A blob that is not the key's does not decrypt, and
* the padding does not hold.
* <p>The ciphertext is decrypted under the vector the request names. The cipher pads no
* data, so a ciphertext that is not a whole number of blocks does not decrypt, and a
* ciphertext that is not the key's does not decrypt either.
*
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @return the plaintext
*/
static byte[] decryptCbc(byte[] key, byte[] blob) {
if (blob.length <= IV_LENGTH) {
throw new IllegalArgumentException("the ciphertext is shorter than the initialization vector");
static byte[] decryptCbc(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return aesCbcDecrypt(key, vector(initializationVector, IV_LENGTH), ciphertext);
}
/**
* The ciphertext of a plaintext under a Triple DES key, with the initialization vector the
* request names.
*
* <p>The cipher pads no data, so the caller supplies whole blocks of eight bytes, and the
* ciphertext is as long as the plaintext it holds. A two-key key is used under the three keys
* it holds, as the cipher takes them.
*
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @return the encrypted bytes
*/
static byte[] tdesCbcEncrypt(byte[] key, byte[] plaintext, byte[] initializationVector) {
return Ciphers.tdesCbcEncrypt(plaintext, key, vector(initializationVector, TDES_IV_LENGTH));
}
/**
* The plaintext of a ciphertext the service encrypted under a Triple DES key.
*
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @return the plaintext
*/
static byte[] tdesCbcDecrypt(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return Ciphers.tdesCbcDecrypt(ciphertext, key, vector(initializationVector, TDES_IV_LENGTH));
}
/** The vector a cipher starts from, the zero vector when the request names none. */
private static byte[] vector(byte[] initializationVector, int length) {
if (initializationVector == null) {
return new byte[length];
}
try {
byte[] iv = Arrays.copyOfRange(blob, 0, IV_LENGTH);
byte[] encrypted = Arrays.copyOfRange(blob, IV_LENGTH, blob.length);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(encrypted);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("the ciphertext did not open under the key", e);
if (initializationVector.length != length) {
throw new IllegalArgumentException("the initialization vector is "
+ initializationVector.length + " bytes; it is " + length);
}
return initializationVector.clone();
}
/**
@@ -274,28 +264,24 @@ final class PaymentCryptographyCrypto {
* key was the right one.
*/
static byte[] keyWrap(byte[] key, byte[] plaintext) {
try {
byte[] a = INITIAL_VALUE.clone();
byte[][] r = split(plaintext, 8);
int n = r.length;
for (int j = 0; j < 6; j++) {
for (int i = 0; i < n; i++) {
byte[] block = concat(a, r[i]);
byte[] encrypted = encrypt(block, key);
a = Arrays.copyOfRange(encrypted, 0, 8);
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
a = xor(a, counter(j, n, i));
}
}
byte[] out = new byte[8 + plaintext.length];
System.arraycopy(a, 0, out, 0, 8);
byte[] a = INITIAL_VALUE.clone();
byte[][] r = split(plaintext, 8);
int n = r.length;
for (int j = 0; j < 6; j++) {
for (int i = 0; i < n; i++) {
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
byte[] block = concat(a, r[i]);
byte[] encrypted = Ciphers.aesEcbEncrypt(block, key);
a = Arrays.copyOfRange(encrypted, 0, 8);
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
a = Ciphers.xor(a, counter(j, n, i));
}
return out;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
byte[] out = new byte[8 + plaintext.length];
System.arraycopy(a, 0, out, 0, 8);
for (int i = 0; i < n; i++) {
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
}
return out;
}
/**
@@ -305,27 +291,23 @@ final class PaymentCryptographyCrypto {
if (wrapped.length < 16 || (wrapped.length - 8) % 8 != 0) {
return null;
}
try {
byte[] a = Arrays.copyOfRange(wrapped, 0, 8);
byte[][] r = split(Arrays.copyOfRange(wrapped, 8, wrapped.length), 8);
int n = r.length;
for (int j = 5; j >= 0; j--) {
for (int i = n - 1; i >= 0; i--) {
byte[] block = concat(xor(a, counter(j, n, i)), r[i]);
byte[] decrypted = decrypt(block, key);
a = Arrays.copyOfRange(decrypted, 0, 8);
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
}
byte[] a = Arrays.copyOfRange(wrapped, 0, 8);
byte[][] r = split(Arrays.copyOfRange(wrapped, 8, wrapped.length), 8);
int n = r.length;
for (int j = 5; j >= 0; j--) {
for (int i = n - 1; i >= 0; i--) {
byte[] block = concat(Ciphers.xor(a, counter(j, n, i)), r[i]);
byte[] decrypted = Ciphers.aesEcbDecrypt(block, key);
a = Arrays.copyOfRange(decrypted, 0, 8);
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
}
byte[] check = INITIAL_VALUE;
byte[] out = new byte[wrapped.length - 8];
for (int i = 0; i < n; i++) {
System.arraycopy(r[i], 0, out, i * 8, 8);
}
return Arrays.equals(a, check) ? out : null;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
byte[] check = INITIAL_VALUE;
byte[] out = new byte[wrapped.length - 8];
for (int i = 0; i < n; i++) {
System.arraycopy(r[i], 0, out, i * 8, 8);
}
return Arrays.equals(a, check) ? out : null;
}
/**
@@ -354,72 +336,33 @@ final class PaymentCryptographyCrypto {
return out;
}
private static byte[] xor(byte[] left, byte[] right) {
byte[] out = new byte[left.length];
for (int i = 0; i < left.length; i++) {
out[i] = (byte) (left[i] ^ right[i % right.length]);
}
return out;
}
/**
* The AES-CBC encryption of data under a key and an initialization vector, without
* padding: the vector is the length of the data's block size already.
*/
static byte[] aesCbcEncrypt(byte[] key, byte[] iv, byte[] data) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(data);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
return Ciphers.aesCbcEncrypt(data, key, iv);
}
/** The AES-CBC decryption of data under a key and an initialization vector, without padding. */
static byte[] aesCbcDecrypt(byte[] key, byte[] iv, byte[] data) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
return cipher.doFinal(data);
} catch (GeneralSecurityException e) {
return Ciphers.aesCbcDecrypt(data, key, iv);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("the data did not decrypt under the key", e);
}
}
/** One block of AES in ECB mode. */
static byte[] aesEcbEncrypt(byte[] input, byte[] key) {
try {
return encrypt(input, key);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
}
/** One block of AES in ECB mode. */
private static byte[] encrypt(byte[] input, byte[] key) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
return cipher.doFinal(input);
}
/** One block of AES in ECB mode, the other way round. */
private static byte[] decrypt(byte[] input, byte[] key) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
return cipher.doFinal(input);
return Ciphers.aesEcbEncrypt(input, key);
}
static String toHex(byte[] bytes) {
return HexFormat.of().formatHex(bytes);
return HEX.formatHex(bytes);
}
static byte[] fromHex(String hex) {
int length = hex.length() / 2;
byte[] out = new byte[length];
for (int i = 0; i < length; i++) {
out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return out;
return HEX.parseHex(hex);
}
}
@@ -0,0 +1,69 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
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.PathParam;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.Response;
/**
* The data plane's encryption and its MACs.
*
* <p>The routes are the ones the AWS SDK builds: the key is in the path, and the body says
* what to do with it.
*/
@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
public class PaymentCryptographyCryptoController extends PaymentCryptographyDataPlaneController {
private final PaymentCryptographyCryptoHandler handler;
@Inject
public PaymentCryptographyCryptoController(PaymentCryptographyCryptoHandler handler,
ObjectMapper objectMapper,
RegionResolver regionResolver) {
super(objectMapper, regionResolver);
this.handler = handler;
}
@POST
@Path("/keys/{keyIdentifier:.+}/encrypt")
public Response encryptData(@PathParam("keyIdentifier") String keyIdentifier, String body,
@Context HttpHeaders headers) {
return respond(handler.encryptData(request(body, keyIdentifier, "KeyIdentifier"), region(headers)));
}
@POST
@Path("/keys/{keyIdentifier:.+}/decrypt")
public Response decryptData(@PathParam("keyIdentifier") String keyIdentifier, String body,
@Context HttpHeaders headers) {
return respond(handler.decryptData(request(body, keyIdentifier, "KeyIdentifier"), region(headers)));
}
@POST
@Path("/keys/{incomingKeyIdentifier:.+}/reencrypt")
public Response reEncryptData(@PathParam("incomingKeyIdentifier") String incomingKeyIdentifier,
String body, @Context HttpHeaders headers) {
// The key the block is encrypted under is in the body, and it is the only other
// key the request may name. The model says the request must name it, so a request
// that does not is refused there.
JsonNode request = request(body, incomingKeyIdentifier, "IncomingKeyIdentifier");
return respond(handler.reEncryptData(request, region(headers)));
}
@POST
@Path("/mac/generate")
public Response generateMac(String body, @Context HttpHeaders headers) {
return respond(handler.generateMac(parse(body), region(headers)));
}
@POST
@Path("/mac/verify")
public Response verifyMac(String body, @Context HttpHeaders headers) {
return respond(handler.verifyMac(parse(body), region(headers)));
}
}
@@ -0,0 +1,684 @@
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.Ciphers;
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.MessageDigest;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The data plane's encryption and its MACs: the operations that use a key to protect data.
*
* <p>The data plane is a service of its own, with its own host and its own sign name, and it
* is served over rest-json rather than over the control plane's awsJson. The operations are
* the same either way, so they live here and the protocol handler calls them.
*/
@ApplicationScoped
public class PaymentCryptographyCryptoHandler {
/** The usages a key may have for the data encryption operations. */
private static final List<String> DATA_ENCRYPTION_USAGES = List.of(
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
/** The usages a key may have for the MAC operations. */
private static final List<String> MAC_USAGES = List.of(
"TR31_M0_ISO_16609_MAC_KEY",
"TR31_M1_ISO_9797_1_MAC_KEY",
"TR31_M3_ISO_9797_3_MAC_KEY",
"TR31_M6_ISO_9797_5_CMAC_KEY",
"TR31_M7_HMAC_KEY");
/** The usages a key may have for the derivation a DUKPT MAC key is made by. */
private static final List<String> DERIVATION_USAGES = List.of(
"TR31_B0_BASE_DERIVATION_KEY");
/** The hexadecimal the blobs of the protocol carry themselves in. */
private static final HexFormat HEX = HexFormat.of().withUpperCase();
/** The block size of AES, in bytes: the block the cipher works in. */
private static final int AES_BLOCK = 16;
/** The block size of Triple DES, in bytes: the block the cipher works in. */
private static final int TDES_BLOCK = 8;
/** The shortest MAC the service computes, in bytes. */
private static final int SHORTEST_MAC = 4;
/** The longest MAC the ISO 9797 algorithms give, in bytes. */
private static final int LONGEST_MAC = 8;
/** The longest MAC the CMAC gives, in bytes: a whole AES block. */
private static final int LONGEST_CMAC = 16;
private final PaymentCryptographyService service;
@Inject
public PaymentCryptographyCryptoHandler(PaymentCryptographyService service) {
this.service = service;
}
/**
* Encrypts the plaintext under the key the request names.
*
* <p>The service encrypts with the cipher the key's algorithm names, in CBC mode, and
* pads no data, so the plaintext fills whole blocks, and answers with the ciphertext
* alone: the initialization vector travels in the request's attributes.
*/
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);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
requireMode(key, "Encrypt", "encrypt");
Encryption encryption = encryptionAttributes(request.get("EncryptionAttributes"));
requireCipherFamily(key, "encrypt");
requireUsage(key, DATA_ENCRYPTION_USAGES, "encrypt data");
byte[] plaintext = blob(request, "PlainText");
requireBlockAligned(plaintext, key, "PlainText");
byte[] ciphertext = encrypt(material(key), plaintext,
initializationVector(encryption, key, "encrypting"), key);
return answer(key, Map.of("CipherText", encode(ciphertext)));
}
/**
* Decrypts a blob the service encrypted.
*/
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);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
requireMode(key, "Decrypt", "decrypt");
Encryption encryption = encryptionAttributes(request.get("DecryptionAttributes"));
requireCipherFamily(key, "decrypt");
requireUsage(key, DATA_ENCRYPTION_USAGES, "decrypt data");
byte[] ciphertext = blob(request, "CipherText");
requireBlockAligned(ciphertext, key, "CipherText");
byte[] plaintext = decrypt(material(key), ciphertext,
initializationVector(encryption, key, "decrypting"), key);
return answer(key, Map.of("PlainText", encode(plaintext)));
}
/**
* Decrypts under one key and encrypts under another.
*/
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);
PaymentCryptographyKey incoming = requiredKey(request, region, "IncomingKeyIdentifier");
requireMode(incoming, "Decrypt", "decrypt");
PaymentCryptographyKey outgoing = requiredKey(request, region, "OutgoingKeyIdentifier");
requireMode(outgoing, "Encrypt", "encrypt");
Encryption incomingEncryption =
encryptionAttributes(request.get("IncomingEncryptionAttributes"));
Encryption outgoingEncryption =
encryptionAttributes(request.get("OutgoingEncryptionAttributes"));
requireCipherFamily(incoming, "decrypt");
requireCipherFamily(outgoing, "encrypt");
requireUsage(incoming, DATA_ENCRYPTION_USAGES, "decrypt data");
requireUsage(outgoing, DATA_ENCRYPTION_USAGES, "encrypt data");
byte[] ciphertext = blob(request, "CipherText");
requireBlockAligned(ciphertext, incoming, "CipherText");
byte[] plaintext = decrypt(material(incoming), ciphertext,
initializationVector(incomingEncryption, incoming, "decrypting"), incoming);
requireBlockAligned(plaintext, outgoing, "the plaintext");
byte[] reEncrypted = encrypt(material(outgoing), plaintext,
initializationVector(outgoingEncryption, outgoing, "encrypting"), outgoing);
return answer(outgoing, Map.of("CipherText", encode(reEncrypted)));
}
/**
* The MAC of a message under the key: the CMAC of the message, cut to the length the
* caller asks for.
*/
public Map<String, Object> generateMac(JsonNode request, String region) {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("GenerateMac", request);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
MacLeg leg = resolveMacLeg(request.get("GenerationAttributes"), key, region, "Generate",
"generating a MAC with");
byte[] message = blob(request, "MessageData");
int length = macLength(request, leg, leg.longest);
byte[] mac = leg.mac.apply(leg.keyBytes, message);
byte[] answer = new byte[length];
System.arraycopy(mac, 0, answer, 0, length);
return answer(key, Map.of("Mac", encode(answer)));
}
/**
* The verdict of a MAC over a message.
*/
public Map<String, Object> verifyMac(JsonNode request, String region) {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("VerifyMac", request);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
MacLeg leg = resolveMacLeg(request.get("VerificationAttributes"), key, region, "Verify",
"verifying a MAC with");
byte[] message = blob(request, "MessageData");
byte[] mac = blob(request, "Mac");
int length = macLength(request, leg, mac.length);
if (length != mac.length) {
throw new AwsException("ValidationException",
"MacLength does not match the length of Mac", 400);
}
byte[] expected = leg.mac.apply(leg.keyBytes, message);
byte[] cut = new byte[length];
System.arraycopy(expected, 0, cut, 0, Math.min(length, expected.length));
if (!MessageDigest.isEqual(cut, mac)) {
// The service does not answer that a MAC is not valid: it fails, because a caller
// that asks whether a MAC is good gets an error rather than a false.
throw new AwsException("VerificationFailedException",
"This request failed verification.", 400, Map.of("Reason", "INVALID_MAC"));
}
return answer(key, Map.of());
}
/** The PIN data of a card account, verified against a generation key. */
/** The PIN data of one scheme translated into another. */
/** The card validation value of a card account. */
/** The card validation value of a card account, verified. */
/** The cryptogram of an authorization request, verified. */
/** The cryptogram of an authorization request, generated. */
/** The material of a key translated into another form. */
public Map<String, Object> translateKeyMaterial(JsonNode request, String region) {
refused("TranslateKeyMaterial");
return Map.of();
}
/**
* The operation is not served, and says so.
*/
private static void refused(String operation) {
throw new AwsException("ValidationException",
operation + " is not served: its algorithm belongs to the payment scheme, and this "
+ "service does not make one up", 400);
}
/** The answer of an operation: what the operation made, and which key it made it with. */
private static Map<String, Object> answer(PaymentCryptographyKey key, Map<String, Object> made) {
Map<String, Object> out = new LinkedHashMap<>(made);
out.put("KeyArn", key.getArn());
out.put("KeyCheckValue", key.getKeyCheckValue());
return out;
}
/**
* The cipher the request asks for.
*
* <p>The attributes name the mode and, for a symmetric cipher, the initialization vector.
* The service encrypts in CBC mode, so a request that names another mode is refused
* rather than answered with a cipher it did not ask for.
*
* @param attributes the attributes of the request, which may be absent
* @return the cipher the request asks for
*/
private static Encryption encryptionAttributes(JsonNode attributes) {
if (attributes == null || attributes.isNull()) {
throw new AwsException("ValidationException",
"the encryption attributes are required", 400);
}
String variant = soleVariant(attributes);
if (variant == null) {
throw new AwsException("ValidationException",
"the encryption attributes must specify exactly one variant", 400);
}
if (!"Symmetric".equals(variant)) {
throw new AwsException("ValidationException",
"the encryption variant '" + variant + "' is not supported by this service "
+ "(Symmetric)", 400);
}
JsonNode symmetric = attributes.get(variant);
String mode = symmetric == null ? "" : symmetric.path("Mode").asText();
if (!"CBC".equals(mode)) {
throw new AwsException("ValidationException",
"the encryption mode '" + (mode.isEmpty() ? "(missing)" : mode)
+ "' is not supported by this service (CBC)", 400);
}
if (symmetric != null && symmetric.hasNonNull("PaddingType")) {
throw new AwsException("ValidationException",
"PaddingType applies to RSA only; the symmetric cipher does not pad", 400);
}
byte[] iv = null;
if (symmetric != null && symmetric.hasNonNull("InitializationVector")) {
String hex = symmetric.path("InitializationVector").asText();
if (!hex.isEmpty()) {
// The model's pattern says the vector is hexadecimal, so it only decodes here.
iv = HexFormat.of().parseHex(hex);
}
}
return new Encryption(iv);
}
/**
* The initialization vector of a request, checked against the cipher's block size.
*
* <p>The length follows the key: an AES key takes a sixteen-byte vector and a Triple DES
* one an eight-byte one, so a vector for one is not a vector for the other. A vector of
* the wrong length is refused here, where the caller can act on it, and not by the
* cipher, where it would be a server error.
*
* @param encryption the attributes of the request
* @param key the key the cipher runs under
* @param what the operation that is refused, for the message
* @return the vector, or null when the request names none
*/
private static byte[] initializationVector(Encryption encryption, PaymentCryptographyKey key,
String what) {
byte[] iv = encryption.initializationVector();
if (iv == null) {
return null;
}
int length = isAes(key) ? 16 : 8;
if (iv.length != length) {
throw new AwsException("ValidationException",
"the initialization vector is " + iv.length + " bytes; " + what + " under a "
+ (isAes(key) ? "AES" : "Triple DES") + " key takes " + length, 400);
}
return iv;
}
/**
* Whether a key is an AES key.
*
* <p>The key record knows its algorithm, so the family is read from there and not guessed
* from the length of the material: a sixteen-byte key is a two-key Triple DES one and an
* AES-128 one.
*/
private static boolean isAes(PaymentCryptographyKey key) {
return PaymentCryptographyService.isAes(key);
}
/**
* Whether the key is a Triple DES one.
*
* <p>The reference ciphers with AES and with Triple DES, and the block and the vector follow
* the key's family: sixteen bytes and a sixteen-byte vector for AES, eight for Triple DES.
*
* @param key the key the cipher runs under
* @return whether the key is a Triple DES one
*/
private static boolean isTdes(PaymentCryptographyKey key) {
return PaymentCryptographyService.isTdes(key);
}
/**
* The family a key's algorithm has to be for an operation.
*
* <p>The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
* the CMAC over AES, so a key of the other family would be read as bytes it is not.
*
* @param key the key the operation runs under
* @param aes whether the operation needs an AES key
* @param what the operation, for the message
*/
private static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
if (isAes(key) != aes) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
+ what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
}
}
/**
* The family a key's algorithm belongs to.
*
* <p>The cipher runs under the key's own algorithm: an AES key is encrypted with AES and
* a Triple DES one with Triple DES. A key whose algorithm this service does not cipher
* with is refused rather than run through the cipher it does have.
*
* @param key the key the cipher runs under
* @param what the operation that is refused, for the message
*/
private static void requireCipherFamily(PaymentCryptographyKey key, String what) {
if (!isAes(key) && !isTdes(key)) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm()
+ " key, and this service does not cipher with that algorithm to "
+ what, 400);
}
}
/**
* The ciphertext of a plaintext under the key, in the cipher the key's family runs.
*
* @param key the key's material
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under
* @param record the key the cipher runs under, whose family names the cipher
* @return the encrypted bytes
*/
private byte[] encrypt(byte[] key, byte[] plaintext, byte[] initializationVector,
PaymentCryptographyKey record) {
return isAes(record)
? PaymentCryptographyCrypto.encryptCbc(key, plaintext, initializationVector)
: PaymentCryptographyCrypto.tdesCbcEncrypt(key, plaintext, initializationVector);
}
/**
* The plaintext of a ciphertext the service encrypted under the key.
*
* @param key the key's material
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under
* @param record the key the cipher runs under, whose family names the cipher
* @return the plaintext
*/
private static byte[] decrypt(byte[] key, byte[] ciphertext, byte[] initializationVector,
PaymentCryptographyKey record) {
return isAes(record)
? PaymentCryptographyCrypto.decryptCbc(key, ciphertext, initializationVector)
: PaymentCryptographyCrypto.tdesCbcDecrypt(key, ciphertext, initializationVector);
}
/** The cipher a request asks for. */
private record Encryption(byte[] initializationVector) {
}
/** The key the request names, in the member the operation names it in. */
private PaymentCryptographyKey requiredKey(JsonNode request, String region, String member) {
String identifier = request.path(member).asText();
if (identifier.isEmpty()) {
throw new AwsException("ValidationException", member + " is required", 400);
}
PaymentCryptographyKey key = service.findKey(region, identifier);
if (key == null) {
throw new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
}
requireEnabled(key);
return key;
}
/**
* A key that is disabled does no work.
*
* <p>The service reads a disabled key and tells the caller about it, but it does not
* encrypt with it, decrypt with it, or make a MAC under it.
*
* @param key the key the request names
*/
private static void requireEnabled(PaymentCryptographyKey key) {
if (!key.isEnabled()) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is disabled", 400);
}
}
/**
* The material of a key.
*
* <p>The material is held by the key while the emulator runs and is not written to the
* store, so a key read back after a restart has none. A request that needs the material
* is then refused with an error that says so, rather than failing on the missing value.
*
* @param key the key the operation runs under
* @return the key's material
*/
private static byte[] material(PaymentCryptographyKey key) {
return PaymentCryptographyCrypto.fromHex(materialHex(key));
}
/**
* The material of a key, as it is held.
*
* <p>The material is held by the key while the emulator runs and is not written to the
* store, so a key read back after a restart has none. A request that needs the material
* is then refused with an error that says so, rather than failing on the missing value.
*
* @param key the key the operation runs under
* @return the key's material, as hexadecimal
*/
private static String materialHex(PaymentCryptographyKey key) {
String hex = key.getKeyMaterialHex();
if (hex == null || hex.isEmpty()) {
throw new AwsException("ValidationException",
"the material of the key " + key.getArn() + " is not held: it is kept while the "
+ "emulator runs and is not written to the store, so a key read back after "
+ "a restart has none", 400);
}
return hex;
}
/**
* The block the key's cipher works in: sixteen bytes for AES and eight for Triple DES, as
* the reference says.
*
* @param key the key the cipher runs under
* @return the block size, in bytes
*/
private static int blockOf(PaymentCryptographyKey key) {
return isAes(key) ? AES_BLOCK : TDES_BLOCK;
}
/**
* The data must fill whole blocks of the key's cipher.
*
* <p>The cipher pads no data, so the caller supplies whole blocks: a plaintext that does
* not fill them is refused, rather than padded into a ciphertext that is longer than the
* data it holds. The block follows the key's cipher, as the reference says: sixteen bytes
* for AES and eight for Triple DES.
*
* @param data the data the request names
* @param key the key the cipher runs under, whose cipher sets the block size
* @param member the member the data is, for the message
*/
private static void requireBlockAligned(byte[] data, PaymentCryptographyKey key, String member) {
int block = blockOf(key);
if (data.length % block != 0) {
throw new AwsException("ValidationException",
member + " must be a multiple of " + block + " bytes (one "
+ (isAes(key) ? "AES" : "TDES") + " block)", 400);
}
}
/**
* The usage a key has to have for an operation.
*
* <p>The usage is what binds a key to its purpose, so an operation that belongs to one
* purpose is not served with a key of another: a PIN encryption key does not encrypt
* arbitrary data, and a MAC key does not either. The check is on the usage itself, not
* on the mode, because a key may carry the mode and still be of another purpose.
*
* @param key the key the operation runs under
* @param usages the usages the operation serves
* @param what the operation, for the message
*/
private static void requireUsage(PaymentCryptographyKey key, List<String> usages, String what) {
String usage = key.getKeyUsage();
if (usage == null || usages.contains(usage)) {
return;
}
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
}
/** The modes of use a key has to have for an operation. */
private static void requireMode(PaymentCryptographyKey key, String mode, String what) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
if (modes == null) {
return;
}
// A NoRestrictions that is false is not a permission: a request that names the
// member says nothing about what it allows, so the mode itself decides.
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
return;
}
if (!Boolean.TRUE.equals(modes.get(mode))) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " does not have the mode of use " + mode
+ ", which it needs to " + what, 400);
}
}
/**
* The MAC a request asks for, and the key it is computed under.
*
* <p>The attributes name the algorithm: the ISO 9797-1 algorithms 1 and 3 for the
* {@code Algorithm} variant, and the DUKPT derivations of the same two for the DUKPT
* variants. A DUKPT MAC key is derived from the base derivation key, so that is what the
* key has to allow.
*/
private MacLeg resolveMacLeg(JsonNode attributes, PaymentCryptographyKey key, String region,
String mode, String what) {
String variant = soleVariant(attributes);
if (variant == null) {
throw new AwsException("ValidationException",
"MacAttributes must specify exactly one variant", 400);
}
if ("Algorithm".equals(variant)) {
// The algorithm is a member of the attributes themselves, not of the variant.
String algorithm = text(attributes, "Algorithm");
if ("ISO9797_ALGORITHM1".equals(algorithm)) {
requireMode(key, mode, what);
requireUsage(key, MAC_USAGES, what);
// The ISO 9797 MACs are defined over Triple DES, so the key is one.
requireFamily(key, false, what);
return new MacLeg(Ciphers::iso9797Alg1, material(key), LONGEST_MAC);
}
if ("ISO9797_ALGORITHM3".equals(algorithm)) {
requireMode(key, mode, what);
requireUsage(key, MAC_USAGES, what);
requireFamily(key, false, what);
return new MacLeg(Ciphers::iso9797Alg3, material(key), LONGEST_MAC);
}
if ("CMAC".equals(algorithm)) {
// The CMAC is the AES-CMAC of RFC 4493, which is a whole block
// wide, so it is cut to a length the caller asks for.
requireMode(key, mode, what);
requireUsage(key, MAC_USAGES, what);
// The CMAC is defined over AES, so the key is one.
requireFamily(key, true, what);
return new MacLeg(PaymentCryptographyCrypto::cmac, material(key), LONGEST_CMAC);
}
throw new AwsException("ValidationException",
"Algorithm '" + algorithm + "' not supported by this service "
+ "(ISO9797_ALGORITHM1, ISO9797_ALGORITHM3, CMAC)", 400);
}
if ("DukptIso9797Algorithm1".equals(variant) || "DukptIso9797Algorithm3".equals(variant)) {
// A DUKPT MAC key is derived from the base derivation key, so that is what the key
// has to allow, and the derivation is over Triple DES, so the key is one.
requireMode(key, "DeriveKey", "deriving a MAC key");
requireUsage(key, DERIVATION_USAGES, "deriving a MAC key");
requireFamily(key, false, "deriving a MAC key");
JsonNode variantAttributes = attributes.get(variant);
// The model's pattern says the serial number is hexadecimal, so it only decodes here.
String ksn = text(variantAttributes, "KeySerialNumber");
String keyVariant = text(variantAttributes, "DukptKeyVariant");
if (!keyVariant.isEmpty() && !"REQUEST".equals(keyVariant)) {
throw new AwsException("ValidationException",
variant + ".DukptKeyVariant '" + keyVariant
+ "' not supported by this service (REQUEST)", 400);
}
String derivationType = text(variantAttributes, "DukptDerivationType");
if (!derivationType.isEmpty() && !"TDES_2KEY".equals(derivationType)) {
throw new AwsException("ValidationException",
variant + ".DukptDerivationType '" + derivationType
+ "' not supported by this service (TDES_2KEY)", 400);
}
byte[] derived;
try {
derived = DukptCrypto.macKey(materialHex(key), ksn);
} catch (IllegalArgumentException e) {
// The derivation refuses what the request names, so the refusal is the
// caller's to act on. Anything else is a fault of the service and is
// left to travel as one.
throw new AwsException("ValidationException",
"DUKPT derivation failed: " + e.getMessage(), 400);
}
return new MacLeg("DukptIso9797Algorithm1".equals(variant)
? Ciphers::iso9797Alg1 : Ciphers::iso9797Alg3, derived, LONGEST_MAC);
}
throw new AwsException("ValidationException",
"MacAttributes." + variant + " not supported by this service", 400);
}
/** The MAC a request asks for, and the key it is computed under. */
private static final class MacLeg {
final MacFunction mac;
final byte[] keyBytes;
/** The longest MAC this algorithm gives, in bytes. */
final int longest;
MacLeg(MacFunction mac, byte[] keyBytes, int longest) {
this.mac = mac;
this.keyBytes = keyBytes;
this.longest = longest;
}
}
/** A MAC over a message under a key. */
private interface MacFunction {
byte[] apply(byte[] key, byte[] message);
}
/** The one variant of an attributes structure, or null when there is not exactly one. */
private static String soleVariant(JsonNode attributes) {
if (attributes == null || !attributes.isObject()) {
return null;
}
String found = null;
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
while (fields.hasNext()) {
if (found != null) {
return null;
}
found = fields.next().getKey();
}
return found;
}
/** The text of a member. */
private static String text(JsonNode request, String member) {
if (request == null) {
return "";
}
JsonNode declared = request.get(member);
return declared == null || declared.isNull() ? "" : declared.asText("");
}
/**
* A blob of the request.
*
* <p>The data plane carries its blobs as hexadecimal, which is what the reference says it
* does. The request has already been checked against the model, which says that the
* member is there, that it is a string and what it holds, so this only decodes it.
*/
private static byte[] blob(JsonNode request, String member) {
return PaymentCryptographyCrypto.fromHex(request.get(member).textValue());
}
/**
* The length of the MAC the caller asks for, which the service computes.
*
* <p>The model says the length is a whole number of at least four bytes, and the
* request has been checked against it. What the algorithm gives is shorter than the
* model allows, so a length above it is refused here.
*/
private static int macLength(JsonNode request, MacLeg leg, int fallback) {
int length = request.path("MacLength").asInt(fallback);
if (length < SHORTEST_MAC || length > leg.longest) {
throw new AwsException("ValidationException",
"MacLength must be between " + SHORTEST_MAC + " and " + leg.longest, 400);
}
return length;
}
/** A blob as the protocol carries it: hexadecimal. */
private static String encode(byte[] bytes) {
return HEX.formatHex(bytes);
}
}
@@ -0,0 +1,95 @@
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 jakarta.inject.Inject;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import java.util.Map;
/**
* What the data plane's controllers share: the body of a request, the region it is for, and
* the answer it gives.
*
* <p>The data plane is a service of its own (Smithy restJson1): it has its own host, its own
* sign name and its own protocol, and its operations are routed by the path rather than by a
* target header. The routes are the ones the AWS SDK builds, so a client reaches them without
* knowing anything about this service.
*
* <p>A path that names the key is the key the operation acts on. The body may name one
* besides it, and then the two must agree, so a request cannot act on a key other than the
* one its path names.
*
* <p>{@code /mac}, {@code /pindata}, {@code /cardvalidationdata} and {@code /cryptogram} are
* two-segment paths, which S3's path-style routes would claim, so
* {@link PaymentCryptographyDataPlaneRouteFilter} moves them for the requests signed for this
* service.
*
* <p>The operations are grouped by what they do, and each group has its own controller: the
* encryption and the MACs, the PIN data, and the card validation values with the authorization
* cryptograms. The groups share this base and nothing else, so each of them can be read on
* its own.
*/
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public abstract class PaymentCryptographyDataPlaneController {
private final ObjectMapper objectMapper;
private final RegionResolver regionResolver;
@Inject
public PaymentCryptographyDataPlaneController(ObjectMapper objectMapper,
RegionResolver regionResolver) {
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
}
/** The body of a request, with the key the path names. */
protected JsonNode request(String body, String pathIdentifier, String member) {
JsonNode request = parse(body);
String named = request.path(member).asText();
if (!named.isEmpty() && !named.equals(pathIdentifier)) {
throw new AwsException("ValidationException",
member + " in the body is not the key the path names", 400);
}
ObjectNode withKey = ((ObjectNode) request).deepCopy();
withKey.put(member, pathIdentifier);
return withKey;
}
/** The body of a request, which is a JSON object. */
protected JsonNode parse(String body) {
if (body == null || body.isBlank()) {
return objectMapper.createObjectNode();
}
try {
JsonNode request = objectMapper.readTree(body);
if (request == null || !request.isObject()) {
throw new AwsException("ValidationException", "the body must be a JSON object", 400);
}
return request;
} catch (AwsException e) {
throw e;
} catch (Exception e) {
throw new AwsException("ValidationException", "the body is not valid JSON", 400);
}
}
/** The region the request is for. */
protected String region(HttpHeaders headers) {
return regionResolver.resolveRegion(headers);
}
/** The answer of an operation. */
protected static Response respond(Map<String, Object> answer) {
return Response.ok(answer).build();
}
}
@@ -0,0 +1,47 @@
package io.floci.aws.services.paymentcryptography;
import io.floci.aws.core.common.ResolvedServiceCatalog;
import io.floci.aws.core.common.SignedServiceRoute;
import jakarta.inject.Inject;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerRequestFilter;
import jakarta.ws.rs.container.PreMatching;
import jakarta.ws.rs.ext.Provider;
import java.util.Set;
/**
* Rewrites the data plane's two-segment paths to an internal prefix before JAX-RS route
* matching. Registered directly, {@code /mac/generate} and the rest would outrank S3's
* {@code /{bucket}/{key}} routes, so a path-style request for a bucket of that name would
* reach the data plane. Only a request signed for the data plane is rewritten; anything else
* falls through to S3.
*/
@Provider
@PreMatching
public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequestFilter {
static final String INTERNAL_PREFIX = "/_paymentcryptography";
private final SignedServiceRoute route;
@Inject
public PaymentCryptographyDataPlaneRouteFilter(ResolvedServiceCatalog catalog) {
// Both planes of the service are signed for the same scope, so the
// path says which plane a request is for, and the control plane never
// uses these paths. A client that signs for the data plane's own scope
// is served as well, so that either scope reaches the data plane.
this.route = new SignedServiceRoute(catalog,
Set.of("paymentcryptography", "payment-cryptography-data"), INTERNAL_PREFIX,
SignedServiceRoute.under("/mac")
.or(SignedServiceRoute.under("/pindata"))
.or(SignedServiceRoute.under("/cardvalidationdata"))
.or(SignedServiceRoute.under("/cryptogram"))
.or(SignedServiceRoute.under("/keys")));
}
@Override
public void filter(ContainerRequestContext ctx) {
route.apply(ctx);
}
}
@@ -0,0 +1,35 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.RequestConstraintCheck;
/**
* Checks a Payment Cryptography data plane request against the constraints vendored in
* {@code aws/payment-cryptography-data-request-shapes.json} by
* {@code tools/aws/regen_payment_cryptography_data_shapes.py}.
*
* <p>The patterns are what settle which key a request may name: {@code KeyIdentifier} takes the ARN
* of a key, the ARN of an alias or the name of an alias, and the identifier of a key on its own
* names none of them. A violation is a {@code ValidationException}, with the member's path from
* the request's top level.
*/
final class PaymentCryptographyDataRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/payment-cryptography-data-request-shapes.json",
"Payment Cryptography data plane request shapes",
PaymentCryptographyShapeErrors.MESSAGES);
private PaymentCryptographyDataRequestShapes() {
}
/**
* Checks a request of an operation against the constraints the model states for it.
*
* @param operation the operation the request is
* @param request the request
*/
static void check(String operation, JsonNode request) {
CHECK.check(operation, request);
}
}
@@ -88,6 +88,16 @@ enum PaymentCryptographyKeyAlgorithm {
return aes;
}
/**
* Whether the key is a Triple DES key rather than an AES one.
*
* <p>A symmetric key is an AES one or a Triple DES one, so the family follows from the
* two.
*/
boolean isTdes() {
return symmetric() && !aes;
}
/** Whether the key is an EC key, which has a key pair rather than key material. */
boolean isEcc() {
return ecc;
@@ -1,11 +1,8 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
/**
* Checks a Payment Cryptography request against the constraints vendored in
* {@code aws/payment-cryptography-request-shapes.json} by
@@ -20,35 +17,7 @@ final class PaymentCryptographyRequestShapes {
private static final RequestConstraintCheck CHECK = RequestConstraintCheck.load(
"aws/payment-cryptography-request-shapes.json", "Payment Cryptography request shapes",
new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path, "Member must be a " + type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
return min != null && size < min
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path, "must satisfy regular expression '" + pattern + "'");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path, "Member must satisfy enum value set: " + values);
}
@Override
public AwsException required(String path) {
return invalid(path, "Member must not be null");
}
});
PaymentCryptographyShapeErrors.MESSAGES);
private PaymentCryptographyRequestShapes() {
}
@@ -56,12 +25,4 @@ final class PaymentCryptographyRequestShapes {
static void check(String operation, JsonNode request) {
CHECK.check(operation, request);
}
/** The member's path below the operation, with list elements folded into their list. */
private static AwsException invalid(String path, String rule) {
int dot = path.indexOf('.');
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
return new AwsException("ValidationException",
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
}
}
@@ -582,6 +582,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return algorithm != null && algorithm.aes;
}
/**
* Whether a key is a Triple DES key rather than an AES one.
*
* <p>The key record knows its algorithm, so the family is read from there and not guessed
* from the length of the material, because a 16-byte key is a two-key TDES one and an
* AES-128 one, and a 24-byte key is a three-key TDES one and an AES-192 one.
*/
static boolean isTdes(PaymentCryptographyKey key) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
return algorithm != null && algorithm.isTdes();
}
/**
* The algorithm byte of a key: {@code A} for an AES key and {@code T} for a TDES one.
*
@@ -590,8 +603,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
* different keys.
*/
static String algorithmByte(PaymentCryptographyKey key) {
return "AES_256".equals(key.getKeyAlgorithm()) || "AES_192".equals(key.getKeyAlgorithm())
|| "AES_128".equals(key.getKeyAlgorithm()) ? "A" : "T";
return isAes(key) ? "A" : "T";
}
/** The usage name of a TR-31 usage code, such as {@code TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY}. */
@@ -0,0 +1,59 @@
package io.floci.aws.services.paymentcryptography;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestConstraintCheck;
import java.util.List;
/**
* How a Payment Cryptography request that breaks a constraint is refused.
*
* <p>The control plane and the data plane are checked by the same machinery and are worded the
* same way, so the wording is here rather than in each of them. The path a violation names is the
* member's path below the operation, with the list elements folded into their list.
*/
final class PaymentCryptographyShapeErrors {
/** The wording every constraint violation of this service is refused with. */
static final RequestConstraintCheck.Messages MESSAGES = new RequestConstraintCheck.Messages() {
@Override
public AwsException type(String path, String type) {
return invalid(path, "Member must be a " + type);
}
@Override
public AwsException bounds(String path, String type, Long min, Long max, long size) {
String measure = "integer".equals(type) || "long".equals(type) ? "value" : "length";
return min != null && size < min
? invalid(path, "Member must have " + measure + " greater than or equal to " + min)
: invalid(path, "Member must have " + measure + " less than or equal to " + max);
}
@Override
public AwsException pattern(String path, String pattern) {
return invalid(path, "must satisfy regular expression '" + pattern + "'");
}
@Override
public AwsException enumValue(String path, List<String> values) {
return invalid(path, "Member must satisfy enum value set: " + values);
}
@Override
public AwsException required(String path) {
return invalid(path, "Member must not be null");
}
};
private PaymentCryptographyShapeErrors() {
}
/** The violation, as the service refuses it. */
static AwsException invalid(String path, String rule) {
int dot = path.indexOf('.');
String member = (dot < 0 ? "" : path.substring(dot + 1)).replace("[]", "");
return new AwsException("ValidationException",
"Invalid parameter at '" + member + "' failed to satisfy constraint: '" + rule + "'", 400);
}
}
@@ -0,0 +1,261 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
import org.bouncycastle.crypto.macs.ISO9797Alg3Mac;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
/**
* The block ciphers the data plane's MACs are built from.
*
* <p>The Triple DES and the Single DES are the two the ISO 9797-1 MACs and the DUKPT
* derivations use, and both are used in ECB mode over a single block. BouncyCastle is used
* for them rather than the JCE, whose provider defaults differ: its {@code DESede} takes the
* two-key form K1||K2 as the three keys K1||K2||K1, so both the cipher and the key are the
* ones the MAC is defined over.
*
* <p>The JCE's Triple DES is not registered in the native image, so a request that needs
* it there hangs until the job is cancelled at its timeout, and the suite that would have
* caught it never answers. Every cipher here is BouncyCastle's, so none of them depends
* on what the image happens to carry.
*
* <p>ECB is the mode the block ciphers implement themselves, so one block goes in and one
* block comes out, which is what the MACs read.
*/
public final class Ciphers {
private Ciphers() {
}
/**
* The AES encryption of data under a key and an initialization vector, in CBC mode, without
* padding.
*
* <p>The cipher pads no data, so the caller supplies whole blocks: a partial block is
* refused rather than padded.
*
* @param data the bytes to encrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @param iv16 the sixteen-byte vector to encrypt under
* @return the encrypted bytes
*/
public static byte[] aesCbcEncrypt(byte[] data, byte[] key, byte[] iv16) {
return blocks(AESEngine.newInstance(), true, data, key, iv16);
}
/**
* The AES decryption of data under a key and an initialization vector, in CBC mode, without
* padding.
*
* @param data the bytes to decrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @param iv16 the sixteen-byte vector to decrypt under
* @return the decrypted bytes
*/
public static byte[] aesCbcDecrypt(byte[] data, byte[] key, byte[] iv16) {
return blocks(AESEngine.newInstance(), false, data, key, iv16);
}
/**
* One block of AES in ECB mode.
*
* @param block16 the sixteen-byte block to encrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @return the encrypted bytes
*/
public static byte[] aesEcbEncrypt(byte[] block16, byte[] key) {
return block(AESEngine.newInstance(), true, block16, key);
}
/**
* One block of AES in ECB mode, the other way round.
*
* @param block16 the sixteen-byte block to decrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @return the decrypted bytes
*/
public static byte[] aesEcbDecrypt(byte[] block16, byte[] key) {
return block(AESEngine.newInstance(), false, block16, key);
}
/**
* The Triple DES encryption of a block under a two-key key, in ECB mode.
*
* <p>The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
* is what the two-key form means. A three-key key is taken as it is.
*
* @param block8 the eight-byte block to encrypt
* @param key the sixteen- or twenty-four-byte key
* @return the encrypted block
*/
public static byte[] tdes2Encrypt(byte[] block8, byte[] key) {
return tdes3Encrypt(block8, key);
}
/**
* The Triple DES encryption of a block under a three-key key, in ECB mode.
*
* @param block8 the eight-byte block to encrypt
* @param key24 the twenty-four-byte key
* @return the encrypted block
*/
public static byte[] tdes3Encrypt(byte[] block8, byte[] key24) {
return block(new DESedeEngine(), true, block8, key24);
}
/**
* The Single DES encryption of a block under a key, in ECB mode.
*
* @param block8 the eight-byte block to encrypt
* @param key8 the eight-byte key
* @return the encrypted block
*/
public static byte[] tdesSingleDesEncrypt(byte[] block8, byte[] key8) {
return block(new DESEngine(), true, block8, key8);
}
/**
* The Triple DES encryption of data under a two-key key, in CBC mode.
*
* <p>The two-key form is K1||K2, and the cipher takes three keys, so it is widened to
* K1||K2||K1, which is what the two-key form means. A three-key key is taken as it is.
* The cipher pads no data, so the data fills whole blocks of eight bytes.
*
* @param data the data to encrypt, a whole number of blocks
* @param key the sixteen- or twenty-four-byte key
* @param iv8 the eight-byte vector to encrypt under
* @return the encrypted bytes
*/
public static byte[] tdesCbcEncrypt(byte[] data, byte[] key, byte[] iv8) {
return blocks(new DESedeEngine(), true, data, key, iv8);
}
/**
* The Triple DES decryption of data under a two-key key, in CBC mode.
*
* @param data the encrypted bytes, a whole number of blocks
* @param key the sixteen- or twenty-four-byte key
* @param iv8 the eight-byte vector to decrypt under
* @return the plaintext
*/
public static byte[] tdesCbcDecrypt(byte[] data, byte[] key, byte[] iv8) {
return blocks(new DESedeEngine(), false, data, key, iv8);
}
/**
* The exclusive-or of two byte arrays of the same length.
*
* @param a the first bytes
* @param b the second bytes
* @return the exclusive-or of the two
*/
public static byte[] xor(byte[] a, byte[] b) {
if (a == null || b == null) {
throw new IllegalArgumentException("both byte arrays are required");
}
if (a.length != b.length) {
throw new IllegalArgumentException("the byte arrays are of different lengths: "
+ a.length + " and " + b.length);
}
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ b[i]);
}
return out;
}
/**
* The ISO 9797-1 MAC algorithm 1 over Triple DES, with padding method 1.
*
* <p>Algorithm 1 is the CBC mode's chain over the zero-padded message, so the last
* block it leaves is the MAC.
*
* <p>Padding method 1 pads the message with zeroes only when it does not already fill
* its blocks: a message that fills them is chained as it is, and no block is added.
*
* @param key16 the sixteen-byte key
* @param data the message to authenticate
* @return the eight-byte MAC
*/
public static byte[] iso9797Alg1(byte[] key16, byte[] data) {
// The MAC without a padding of its own pads the last block with zeroes, which is
// padding method 1. A padder that fills a whole block would chain an empty one
// after a message that already fills its blocks, which the standard does not do.
CBCBlockCipherMac mac = new CBCBlockCipherMac(new DESedeEngine(), 64);
mac.init(new ParametersWithIV(new KeyParameter(key16), new byte[8]));
mac.update(data, 0, data.length);
byte[] out = new byte[mac.getMacSize()];
mac.doFinal(out, 0);
return out;
}
/**
* The ISO 9797-1 MAC algorithm 3, the retail MAC, over a double-length DES key,
* with padding method 1.
*
* <p>Algorithm 3 is the retail MAC: a single-DES chain under K1 for all but the
* last block, then a final EDE under K1||K2.
*
* @param key16 the sixteen-byte key, K1||K2
* @param data the message to authenticate
* @return the eight-byte MAC
*/
public static byte[] iso9797Alg3(byte[] key16, byte[] data) {
ISO9797Alg3Mac mac = new ISO9797Alg3Mac(new DESEngine());
mac.init(new KeyParameter(key16));
mac.update(data, 0, data.length);
byte[] out = new byte[mac.getMacSize()];
mac.doFinal(out, 0);
return out;
}
/**
* The encryption or decryption of one block under a key, in the cipher's own ECB mode.
*/
private static byte[] block(BlockCipher cipher, boolean encrypt, byte[] block, byte[] key) {
int size = cipher.getBlockSize();
if (block == null || block.length != size) {
throw new IllegalArgumentException("the block is "
+ (block == null ? "missing" : block.length + " bytes") + "; it is " + size);
}
if (key == null) {
throw new IllegalArgumentException("key is required");
}
cipher.init(encrypt, new KeyParameter(key));
byte[] out = new byte[size];
cipher.processBlock(block, 0, out, 0);
return out;
}
/**
* The encryption or decryption of whole blocks under a key, in CBC mode.
*/
private static byte[] blocks(BlockCipher cipher, boolean encrypt, byte[] data, byte[] key, byte[] iv) {
int size = cipher.getBlockSize();
if (data == null || data.length % size != 0) {
throw new IllegalArgumentException("the data is "
+ (data == null ? "missing" : data.length + " bytes")
+ "; it is a whole number of " + size + "-byte blocks");
}
if (key == null) {
throw new IllegalArgumentException("key is required");
}
if (iv == null || iv.length != size) {
throw new IllegalArgumentException("the initialization vector is "
+ (iv == null ? "missing" : iv.length + " bytes") + "; it is " + size);
}
BlockCipher cbc = CBCBlockCipher.newInstance(cipher);
cbc.init(encrypt, new ParametersWithIV(new KeyParameter(key), iv));
byte[] out = new byte[data.length];
for (int offset = 0; offset < data.length; offset += size) {
cbc.processBlock(data, offset, out, offset);
}
return out;
}
}
@@ -0,0 +1,137 @@
package io.floci.aws.services.paymentcryptography.crypto;
import java.util.Arrays;
import java.util.HexFormat;
/**
* ANSI X9.24-1 TDES DUKPT - Derived Unique Key Per Transaction.
*
* <pre>
* 1. IPEK derivation BDK + initial KSN -&gt; IPEK
* 2. Transaction key IPEK + KSN counter bits -&gt; derived key (one-way)
* 3. Working-key variant derived key XOR mask -&gt; MAC-request key
* </pre>
*
* <p>Validated against the vectors ANSI X9.24-1 publishes, which the test holds: the
* initial sequence of the standard's annex A.4.2. TDES only: AES DUKPT (X9.24-3) is
* out of scope.
*
* <p>The odd parity the standard puts on the key bytes is not enforced here. The cipher
* ignores the parity bits, and the published vectors carry parity-bearing keys, so the
* derivation holds for the keys the standard defines.
*/
public final class DukptCrypto {
private static final byte[] KEY_VARIANT = HexFormat.of().parseHex("C0C0C0C000000000C0C0C0C000000000");
private static final byte[] MAC_REQUEST_MASK = HexFormat.of().parseHex("000000000000FF00000000000000FF00");
private DukptCrypto() {
}
/**
* Normalize a KSN to 10 bytes. A shorter KSN is left-padded with F nibbles:
* transmitted KSNs routinely drop leading FF padding.
*/
public static byte[] normalizeKsn(String ksnHex) {
String h = ksnHex == null ? "" : ksnHex.toUpperCase();
if (h.isEmpty() || !h.matches("[0-9A-F]+")) {
throw new IllegalArgumentException("KSN must be hexadecimal");
}
if (h.length() > 20) {
throw new IllegalArgumentException("KSN must be at most 20 hex characters (10 bytes)");
}
StringBuilder padded = new StringBuilder(20);
for (int i = h.length(); i < 20; i++) {
padded.append('F');
}
padded.append(h);
return HexFormat.of().parseHex(padded.toString());
}
/** The rightmost 21 bits of the KSN: the transaction counter. */
public static int ksnCounter(byte[] ksn10) {
return ((ksn10[7] & 0x1f) << 16) | ((ksn10[8] & 0xff) << 8) | (ksn10[9] & 0xff);
}
/** A copy of the KSN with the 21 counter bits zeroed. */
public static byte[] zeroCounter(byte[] ksn10) {
byte[] z = ksn10.clone();
z[7] &= (byte) 0xe0;
z[8] = 0;
z[9] = 0;
return z;
}
/**
* {@code IPEK = TDES(BDK, left8) || TDES(BDK XOR C0C0..., left8)}, where
* {@code left8} is the KSN with its counter cleared, first 8 bytes.
*/
public static byte[] deriveIpek(String bdkHex, String ksnHex) {
byte[] bdk = HexFormat.of().parseHex(bdkHex);
if (bdk.length != 16) {
throw new IllegalArgumentException("BDK must be a 16-byte (double-length TDES) key");
}
byte[] left8 = Arrays.copyOfRange(zeroCounter(normalizeKsn(ksnHex)), 0, 8);
return concat(
Ciphers.tdes2Encrypt(left8, bdk),
Ciphers.tdes2Encrypt(left8, Ciphers.xor(bdk, KEY_VARIANT)));
}
/** The X9.24-1 non-reversible key generation step, the single-DES "black box". */
public static byte[] deriveStep(byte[] key16, byte[] reg8) {
// Order matters: the variant-keyed half comes first.
return concat(right(Ciphers.xor(key16, KEY_VARIANT), reg8), right(key16, reg8));
}
/**
* The derived transaction key for the KSN's counter, by walking the set
* counter bits from most to least significant.
*/
public static byte[] deriveTransactionKey(String bdkHex, String ksnHex) {
byte[] ksn = normalizeKsn(ksnHex);
int counter = ksnCounter(ksn);
if (counter == 0) {
throw new IllegalArgumentException("KSN transaction counter must be non-zero");
}
byte[] key = deriveIpek(bdkHex, ksnHex);
// The rightmost 8 bytes of the counter-cleared KSN, which become the
// shift register the counter bits are written into.
byte[] reg = Arrays.copyOfRange(zeroCounter(ksn), 2, 10);
for (int bit = 20; bit >= 0; bit--) {
int mask = 1 << bit;
if ((counter & mask) == 0) {
continue;
}
reg[5] |= (byte) ((mask >> 16) & 0x1f);
reg[6] |= (byte) ((mask >> 8) & 0xff);
reg[7] |= (byte) (mask & 0xff);
key = deriveStep(key, reg);
}
return key;
}
/** The MAC-request working key. */
public static byte[] macKey(String bdkHex, String ksnHex) {
return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), MAC_REQUEST_MASK);
}
private static byte[] right(byte[] key16, byte[] reg8) {
byte[] kl = Arrays.copyOfRange(key16, 0, 8);
byte[] kr = Arrays.copyOfRange(key16, 8, 16);
return Ciphers.xor(Ciphers.tdesSingleDesEncrypt(Ciphers.xor(reg8, kr), kl), kr);
}
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;
}
}