feat(paymentcryptography): the key algorithms of the control plane (#7395)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-03 10:35:43 -04:00
1 parent 537e042482
commit 648d363102
10 files changed
+1575 -112

No files matched your search

@@ -1,109 +1,356 @@
package io.github.hectorvent.floci.services.paymentcryptography;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Locale;
/**
* The cryptography a key record needs: its material, and its check value.
* The cryptography a key record needs: its material, its check value, and the operations the
* data plane performs with it.
*
* <p>The check value of an AES key is the leftmost three bytes of the CMAC of
* sixteen zero bytes under the key. That is what the service computes for a
* CMAC check value, and what the reference implementation its samples use
* computes.
*
* <p>The CMAC is the one RFC 4493 gives, so a key's check value is the one
* the standard's vectors give and a message of any length is authenticated
* the way the standard says.
* <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.
*/
final class PaymentCryptographyCrypto {
private static final byte[] ZERO_BLOCK = new byte[16];
/** The block size of AES, in bytes. */
private static final int BLOCK_SIZE = 16;
private static final int BLOCK = 16;
private static final byte[] ZERO_BLOCK = new byte[BLOCK_SIZE];
/** The initialization vector of a CBC encryption, in bytes. */
private static final int IV_LENGTH = 16;
/** The Rijndael constant the subkey derivation exclusive-oreds in when the shift carries out. */
private static final int RB = 0x87;
/** 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,
(byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6};
private PaymentCryptographyCrypto() {
}
/** Fresh AES-256 material, as hexadecimal. */
static String randomAes256Hex(SecureRandom random) {
byte[] material = new byte[32];
/** Fresh material of the algorithm's length, as hexadecimal. */
static String randomMaterialHex(PaymentCryptographyKeyAlgorithm algorithm, SecureRandom random) {
byte[] material = new byte[algorithm.bytes];
random.nextBytes(material);
return toHex(material);
}
/** Fresh AES-256 material, as hexadecimal. */
static String randomAes256Hex(SecureRandom random) {
return randomMaterialHex(PaymentCryptographyKeyAlgorithm.AES_256, random);
}
/**
* The check value of a key of that algorithm.
*
* <p>A TDES key's value is the ANSI X9.24 one: the leftmost three bytes of encrypting
* eight zero bytes with the key. An AES key's value is the leftmost three bytes of the
* CMAC of sixteen zero bytes under it.
*/
static String checkValue(String keyHex, PaymentCryptographyKeyAlgorithm algorithm) {
byte[] key = fromHex(keyHex);
byte[] mac = algorithm.aes
? cmac(key, ZERO_BLOCK)
: tdesEcbEncrypt(new byte[8], key);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
}
/** The check value of a key of that algorithm, from the key's bytes. */
static String checkValue(byte[] key, PaymentCryptographyKeyAlgorithm algorithm) {
byte[] mac = algorithm.aes
? cmac(key, ZERO_BLOCK)
: tdesEcbEncrypt(new byte[8], key);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
}
/** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
static String checkValue(String keyHex) {
byte[] mac = cmac(fromHex(keyHex), ZERO_BLOCK);
return toHex(Arrays.copyOf(mac, 3)).toUpperCase(Locale.ROOT);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return toHex(value).toUpperCase(Locale.ROOT);
}
/**
* The AES-CMAC of a message under a key, as RFC 4493 gives it.
* The Triple DES encryption of a block under a key, in ECB mode.
*
* <p>The message is divided into blocks and chained as CBC-MAC. A last
* block of the block size is exclusive-ored with K1, and one shorter is
* padded with a single one bit and exclusive-ored with K2, as the RFC
* says.
* <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
* @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;
}
/**
* The AES-CMAC of a message under a key, as RFC 4493 computes it.
*
* <p>The message is split into blocks of sixteen bytes. The last block is the one that is
* padded, unless the message fills it exactly, and it is exclusive-ored with the first
* subkey when it is whole and with the second when it is padded.
*/
static byte[] cmac(byte[] key, byte[] message) {
try {
byte[] k1 = shiftLeft(encrypt(ZERO_BLOCK, key));
byte[] k1 = subkeyOne(key);
byte[] k2 = shiftLeft(k1);
int blocks = (message.length + BLOCK_SIZE - 1) / BLOCK_SIZE;
boolean complete = message.length > 0 && message.length % BLOCK_SIZE == 0;
if (blocks == 0) {
blocks = 1;
}
byte[] last = new byte[BLOCK_SIZE];
int offset = (blocks - 1) * BLOCK_SIZE;
if (complete) {
System.arraycopy(message, offset, last, 0, BLOCK_SIZE);
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 {
int remaining = message.length - offset;
System.arraycopy(message, offset, last, 0, remaining);
last[remaining] = (byte) 0x80;
// 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[] chain = ZERO_BLOCK;
byte[] state = new byte[BLOCK];
for (int i = 0; i < blocks - 1; i++) {
byte[] block = new byte[BLOCK_SIZE];
System.arraycopy(message, i * BLOCK_SIZE, block, 0, BLOCK_SIZE);
chain = encrypt(xor(chain, block), key);
byte[] block = new byte[BLOCK];
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
state = encrypt(xor(state, block), key);
}
return encrypt(xor(chain, last), key);
return encrypt(xor(state, last), key);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
}
/**
* A block shifted left by one bit, with Rijndael's Rb exclusive-ored in
* when the shift carried out of the top.
* The first CMAC subkey.
*
* <p>The bit that falls off the top of the block comes from the byte
* above it, so the carry travels down the block.
* <p>It is the block cipher's output over a zero block, shifted left by one
* bit, with Rijndael's Rb exclusive-ored in when the shift carried out of
* 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);
}
}
/**
* The two CMAC subkeys of a key: the first and the second.
*
* <p>The key derivation of a TR-31 block is seeded with one of them, so they are
* wanted on their own.
*/
static byte[][] cmacSubkeys(byte[] key) {
byte[] k1 = subkeyOne(key);
return new byte[][] {k1, shiftLeft(k1)};
}
/**
* A block shifted left by one bit, with Rijndael's Rb exclusive-ored in when the shift
* carried out of the top.
*/
private static byte[] shiftLeft(byte[] block) {
byte[] shifted = new byte[BLOCK_SIZE];
byte[] out = new byte[BLOCK];
int carry = 0;
for (int i = BLOCK_SIZE - 1; i >= 0; i--) {
for (int i = BLOCK - 1; i >= 0; i--) {
// The bit that falls off the top of the block comes from the
// byte above it, so the carry travels down the block.
int nextCarry = (block[i] & 0x80) != 0 ? 1 : 0;
shifted[i] = (byte) (((block[i] << 1) | carry) & 0xff);
out[i] = (byte) (((block[i] << 1) | carry) & 0xff);
carry = nextCarry;
}
if ((block[0] & 0x80) != 0) {
shifted[BLOCK_SIZE - 1] ^= (byte) RB;
out[BLOCK - 1] ^= (byte) 0x87;
}
return shifted;
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.
*
* @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
*/
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);
}
}
/**
* The plaintext of a blob 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.
*/
static byte[] decryptCbc(byte[] key, byte[] blob) {
if (blob.length <= IV_LENGTH) {
throw new IllegalArgumentException("the ciphertext is shorter than the initialization vector");
}
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);
}
}
/**
* The key wrap of RFC 3394: a plaintext wrapped under a key, with the check that says the
* 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);
for (int i = 0; i < n; i++) {
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
}
return out;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the AES key could not be used", e);
}
}
/**
* The plaintext of a key wrap, or null when the wrapping key was not the right one.
*/
static byte[] keyUnwrap(byte[] key, byte[] wrapped) {
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[] 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);
}
}
/**
* The wrap counter of the block at {@code index} of a wrap of {@code n} blocks: the
* standard's {@code t}, which is the round times the number of blocks and the block.
*/
private static byte[] counter(int round, int n, int index) {
byte[] value = new byte[8];
value[7] = (byte) (round * n + index + 1);
return value;
}
private static byte[][] split(byte[] bytes, int size) {
int count = bytes.length / size;
byte[][] out = new byte[count][];
for (int i = 0; i < count; i++) {
out[i] = Arrays.copyOfRange(bytes, i * size, (i + 1) * size);
}
return out;
}
private static byte[] concat(byte[] left, byte[] right) {
byte[] out = new byte[left.length + right.length];
System.arraycopy(left, 0, out, 0, left.length);
System.arraycopy(right, 0, out, left.length, right.length);
return out;
}
private static byte[] xor(byte[] left, byte[] right) {
@@ -114,13 +361,54 @@ final class PaymentCryptographyCrypto {
return out;
}
/** One block of AES in ECB mode, the block cipher the CMAC is built on. */
/**
* 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);
}
}
/** 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) {
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);
}
static String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
@@ -86,16 +86,30 @@ public class PaymentCryptographyJsonHandler {
declared.put(entry.getKey(), entry.getValue().asText());
}
});
// The check value of an AES key is a CMAC, which is the only algorithm this
// service computes, so a request naming another one is refused rather than
// answered with a check value of another kind.
if (request.hasNonNull("KeyCheckValueAlgorithm")
&& !"CMAC".equals(request.get("KeyCheckValueAlgorithm").asText())) {
throw new AwsException("ValidationException",
"KeyCheckValueAlgorithm must be CMAC", 400);
// The check value follows the key's algorithm: an AES key's is a CMAC and a
// TDES key's is the ANSI X9.24 one. A request that names another is refused
// rather than answered with a value of another kind.
if (request.hasNonNull("KeyCheckValueAlgorithm")) {
String wanted = request.get("KeyCheckValueAlgorithm").asText();
String algorithmName = declared.get("KeyAlgorithm") == null ? ""
: String.valueOf(declared.get("KeyAlgorithm"));
// The kind the service will answer with, so a request is never refused for a
// kind the service would have given.
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(algorithmName);
String expected = algorithm == null ? null : algorithm.checkValueAlgorithm();
if (expected != null && !expected.equals(wanted)) {
throw new AwsException("ValidationException",
"KeyCheckValueAlgorithm must be " + expected + " for a " + algorithmName
+ " key", 400);
}
}
// A key may be created disabled, and it may be created with tags.
boolean enabled = request.has("Enabled") ? request.path("Enabled").asBoolean(true) : true;
if (request.hasNonNull("DeriveKeyUsage")) {
// The usage a derivation key derives for sits beside the attributes, not in them.
declared.put("DeriveKeyUsage", request.path("DeriveKeyUsage").asText());
}
PaymentCryptographyKey key = service.createKey(region, declared, modesOfUse(attributes),
request.path("Exportable").asBoolean(false), enabled, tagsOf(request));
return Map.of("Key", keyObject(key));
@@ -334,6 +348,9 @@ public class PaymentCryptographyJsonHandler {
attributes.put("KeyUsage", key.getKeyUsage());
attributes.put("KeyModesOfUse", answeredModes(key));
out.put("KeyAttributes", attributes);
if (key.getDeriveKeyUsage() != null && !key.getDeriveKeyUsage().isEmpty()) {
out.put("DeriveKeyUsage", key.getDeriveKeyUsage());
}
out.put("KeyCheckValue", key.getKeyCheckValue());
out.put("KeyCheckValueAlgorithm", key.getKeyCheckValueAlgorithm());
out.put("KeyState", key.getKeyState());
@@ -0,0 +1,197 @@
package io.github.hectorvent.floci.services.paymentcryptography;
import java.util.List;
/**
* The key algorithms this service makes, with each one's key length.
*
* <p>The length is what tells the two families apart: a TDES key is 16 or 24 bytes and an
* AES key is 16, 24 or 32 bytes. The PIN block formats need the family, because a format 0
* or 3 block is a TDES block and a format 4 block is an AES one.
*
* <p>A real enum rather than a list of names, so the service, the check value and the
* operations all read the same definition.
*/
enum PaymentCryptographyKeyAlgorithm {
TDES_2KEY(16, false, false, false),
TDES_3KEY(24, false, false, false),
AES_128(16, true, false, false),
AES_192(24, true, false, false),
AES_256(32, true, false, false),
/**
* An EC key agreement key on NIST P-256, the curve the cardholder-device flow uses.
* The length is the size of the curve, not of a key block.
*/
ECC_NIST_P256(32, false, true, false),
/** An EC key agreement key on NIST P-384. */
ECC_NIST_P384(48, false, true, false),
/** An EC key agreement key on NIST P-521. */
ECC_NIST_P521(66, false, true, false),
/**
* An RSA key pair with a 2048-bit modulus.
*
* <p>A TR-34 exchange needs one: the authority that certifies the signing key is an RSA
* certificate.
*/
RSA_2048(256, false, false, true),
/** An RSA key pair with a 3072-bit modulus. */
RSA_3072(384, false, false, true),
/** An RSA key pair with a 4096-bit modulus. */
RSA_4096(512, false, false, true);
/** How many bytes of material the key holds. */
final int bytes;
/** Whether the key is an AES key rather than a TDES one. */
final boolean aes;
/** Whether the key is an EC key, which has a key pair rather than key material. */
final boolean ecc;
/** Whether the key is an RSA key, which has a key pair and no symmetric material. */
final boolean rsa;
PaymentCryptographyKeyAlgorithm(int bytes, boolean aes, boolean ecc, boolean rsa) {
this.bytes = bytes;
this.aes = aes;
this.ecc = ecc;
this.rsa = rsa;
}
/** Whether the key holds material a symmetric cipher can use. */
boolean symmetric() {
return !ecc && !rsa;
}
/**
* The kind of check value a key of this algorithm carries.
*
* <p>An AES key's check value is a CMAC, and a TDES key's is the ANSI X9.24 one. An
* asymmetric key has no material a check value could be computed from, so it reports the
* fixed placeholder and the same kind as a TDES key.
*
* <p>The service and the request that asks for a key agree on this, so a request is
* never refused for a kind the service would have answered with.
*/
String checkValueAlgorithm() {
return aes ? "CMAC" : "ANSI_X9_24";
}
/** The generated key length in bytes. */
int bytes() {
return bytes;
}
/** Whether the key is an AES key rather than a TDES one. */
boolean isAes() {
return aes;
}
/** Whether the key is an EC key, which has a key pair rather than key material. */
boolean isEcc() {
return ecc;
}
/** Whether the key is an RSA key, which has a key pair and no symmetric material. */
boolean isRsa() {
return rsa;
}
/** The algorithm of that name, or null when the service does not make it. */
static PaymentCryptographyKeyAlgorithm from(String name) {
if (name == null) {
return null;
}
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
if (algorithm.name().equals(name)) {
return algorithm;
}
}
return null;
}
/** The algorithms of that family, for a message that names the family. */
static String supportedOf(boolean aes) {
StringBuilder sb = new StringBuilder();
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
if (algorithm.aes != aes || !algorithm.symmetric()) {
continue;
}
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(algorithm.name());
}
return sb.toString();
}
/** Every algorithm the service makes, for a message that names them all. */
static String supportedAll() {
StringBuilder sb = new StringBuilder();
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(algorithm.name());
}
return sb.toString();
}
/** The usages a key pair is made of, and the symmetric ones are the rest. */
private static final List<String> ASYMMETRIC_USAGES = List.of(
"TR31_D1_ASYMMETRIC_KEY_FOR_DATA_ENCRYPTION",
"TR31_K2_TR34_ASYMMETRIC_KEY",
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
/**
* The algorithms a key of a usage may be made of.
*
* <p>The service refuses a key whose algorithm its usage does not allow, because the usage
* is what binds the key to its purpose, and a MAC key made of AES is a key whose purpose
* its own algorithm does not serve.
*
* @param usage the TR-31 usage name of the key
* @return the algorithms the usage allows
*/
static List<PaymentCryptographyKeyAlgorithm> allowedOf(String usage) {
if (ASYMMETRIC_USAGES.contains(usage)) {
// The asymmetric usages are the ones a key pair is made of: the data
// encryption key, the key agreement key, the TR-34 key and the signing key.
return List.of(RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384,
ECC_NIST_P521);
}
if ("TR31_M1_ISO_9797_1_MAC_KEY".equals(usage)
|| "TR31_M3_ISO_9797_3_MAC_KEY".equals(usage)
|| "TR31_M0_ISO_16609_MAC_KEY".equals(usage)) {
// The ISO 9797 MACs are defined over Triple DES.
return List.of(TDES_2KEY, TDES_3KEY);
}
// Every other usage takes every symmetric algorithm.
return List.of(TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256);
}
/**
* The reason an algorithm is refused for a usage, in words a caller can act on.
*
* <p>An algorithm is refused for a usage the usage does not allow, whether it is symmetric
* or not: a key pair has no material a symmetric usage would bind it to, and a symmetric
* key has no pair a key pair's usage would bind it to. A key that claims a purpose its own
* material cannot serve is not a key the service makes.
*
* @param usage the TR-31 usage name of the key
* @param algorithm the algorithm of the key
* @return the message, or null when the combination is allowed
*/
static String refusal(String usage, PaymentCryptographyKeyAlgorithm algorithm) {
if (algorithm == null) {
return null;
}
if (allowedOf(usage).contains(algorithm)) {
return null;
}
return "a key of the usage " + usage + " may not be made of " + algorithm.name()
+ ": the usage allows " + allowedOf(usage);
}
}
@@ -0,0 +1,62 @@
package io.github.hectorvent.floci.services.paymentcryptography;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
/**
* The key pairs the service makes.
*
* <p>An RSA key pair is made for the key exchange and for the TR-34 block, and an EC one
* for the key agreement the exchange does. The certificates over them are the exchange's
* own business.
*/
final class PaymentCryptographyKeyPairs {
private PaymentCryptographyKeyPairs() {
}
/** An RSA key pair of the requested modulus size. */
static KeyPair rsa(int bits, SecureRandom random) {
if (bits != 2048 && bits != 3072 && bits != 4096) {
throw new IllegalArgumentException(
"unsupported key size " + bits + " (2048, 3072, 4096)");
}
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(bits, random);
return generator.generateKeyPair();
} catch (GeneralSecurityException e) {
throw new IllegalStateException("cannot generate an RSA key pair", e);
}
}
/** An EC key pair on the curve the algorithm names. */
static KeyPair ec(PaymentCryptographyKeyAlgorithm algorithm, SecureRandom random) {
String curve = curveOf(algorithm);
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec(curve), random);
return generator.generateKeyPair();
} catch (GeneralSecurityException e) {
throw new IllegalStateException("cannot generate an EC key pair", e);
}
}
/**
* The curve an algorithm names.
*
* <p>The curve is the NIST one the cardholder-device flow uses.
*/
private static String curveOf(PaymentCryptographyKeyAlgorithm algorithm) {
return switch (algorithm) {
case ECC_NIST_P256 -> "secp256r1";
case ECC_NIST_P384 -> "secp384r1";
case ECC_NIST_P521 -> "secp521r1";
default -> throw new IllegalArgumentException(
algorithm.name() + " is not an elliptic curve algorithm");
};
}
}
@@ -0,0 +1,169 @@
package io.github.hectorvent.floci.services.paymentcryptography;
import java.security.interfaces.ECKey;
/**
* The minimum key strengths the PCI standards set, and the rule they make of them.
*
* <p>A key that protects another one has to be at least as strong as the key it
* protects, because a weaker protector buys nothing: the protected key is then
* only as safe as the key that wraps it. The service enforces this on export
* and on import, and the reference does the same.
*
* <p>The strengths are the ones the PCI HSM standards count, not the length of
* the material: a two-key Triple DES key is 128 bits of material but 80 bits of
* strength, and a three-key one is 192 bits of material and 112 bits of
* strength. A length would call the two-key key the stronger one, which is the
* opposite of the truth.
*/
final class PaymentCryptographyKeyStrength {
private PaymentCryptographyKeyStrength() {
}
/**
* The strength of a key of an algorithm, in bits, as the PCI standards
* count it. A key of an algorithm this service does not have a strength
* for has none, and cannot protect anything.
*/
static int bitsOf(String algorithm) {
if (algorithm == null) {
return 0;
}
return switch (algorithm) {
case "TDES_2KEY" -> 80;
case "TDES_3KEY" -> 112;
case "AES_128" -> 128;
case "AES_192" -> 192;
case "AES_256" -> 256;
default -> 0;
};
}
/**
* The strength of an RSA key of a modulus size, in bits.
*
* <p>An RSA key is as strong as factoring its modulus is hard. The standards count a
* 2048-bit modulus as 112 bits, a 3072-bit one as 128 bits and a 4096-bit one as 152
* bits.
*
* @param modulusBits the size of the modulus, in bits
* @return the strength, in bits, or zero for a size this service has none for
*/
static int rsaBitsOf(int modulusBits) {
if (modulusBits >= 4096) {
return 152;
}
if (modulusBits >= 3072) {
return 128;
}
if (modulusBits >= 2048) {
return 112;
}
return 0;
}
/**
* The strength of an EC key on a curve, in bits.
*
* <p>A curve is as strong as the discrete logarithm on it is hard. The standards count
* P-256 as 128 bits, P-384 as 192 bits and P-521 as 256 bits.
*
* @param algorithm the curve, as the key algorithm names it
* @return the strength, in bits, or zero for a curve this service has none for
*/
static int eccBitsOf(String algorithm) {
if (algorithm == null) {
return 0;
}
return switch (algorithm) {
case "ECC_NIST_P256" -> 128;
case "ECC_NIST_P384" -> 192;
case "ECC_NIST_P521" -> 256;
default -> 0;
};
}
/**
* The strength of an EC public key, from the curve it is on.
*
* <p>The curve is read from the key itself, because a certificate may name a curve the
* service does not have a strength for, and a key agreement is only as strong as the
* weaker of the two curves it was agreed on.
*
* @param key the public key, or null when there is none
* @return the strength, in bits, or zero for a curve this service has none for
*/
static int eccBitsOf(ECKey key) {
if (key == null) {
return 0;
}
int fieldBits = key.getParams().getCurve().getField().getFieldSize();
return switch (fieldBits) {
case 256 -> 128;
case 384 -> 192;
case 521 -> 256;
default -> 0;
};
}
/**
* Whether a key of one algorithm may protect a key of another.
*
* <p>The protecting key has to be at least as strong as the key it
* protects. A key of the same strength is allowed: the rule is that the
* protector is not weaker, not that it is stronger.
*
* @param protecting the algorithm of the key that protects the other
* @param protectedKey the algorithm of the key that is protected
* @return whether the combination is one the standards allow
*/
static boolean mayProtect(String protecting, String protectedKey) {
int protector = bitsOf(protecting);
int protectedBits = bitsOf(protectedKey);
if (protector == 0 || protectedBits == 0) {
return false;
}
return protector >= protectedBits;
}
/**
* The reason a combination is refused, in words a caller can act on.
*
* @param protecting the algorithm of the key that protects the other
* @param protectedKey the algorithm of the key that is protected
* @return the message, or null when the combination is allowed
*/
static String refusal(String protecting, String protectedKey) {
return refusal(bitsOf(protecting), bitsOf(protectedKey), protecting, protectedKey);
}
/**
* The reason a combination is refused, in words a caller can act on.
*
* <p>This is the form for a protector whose strength comes from the size of its modulus or
* its curve rather than from a name.
*
* @param protectorBits the strength of the protecting key, in bits
* @param protectedBits the strength of the protected key, in bits
* @param protectingName what to call the protecting key
* @param protectedName what to call the protected key
* @return the message, or null when the combination is allowed
*/
static String refusal(int protectorBits, int protectedBits, String protectingName,
String protectedName) {
if (protectorBits == 0 || protectedBits == 0) {
return "a " + (protectedName == null ? "the key" : protectedName)
+ " key may not be protected by a "
+ (protectingName == null ? "the wrapping key" : protectingName)
+ " key: the wrapping key has to be at least as strong as the key it protects";
}
if (protectorBits >= protectedBits) {
return null;
}
String name = protectedName == null ? "the key" : protectedName;
String protector = protectingName == null ? "the wrapping key" : protectingName;
return "a " + name + " key may not be protected by a " + protector
+ " key: the wrapping key has to be at least as strong as the key it protects";
}
}
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.Pagination;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.Resettable;
import io.github.hectorvent.floci.core.common.StoredResourceArns;
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryptographyAlias;
@@ -15,13 +16,17 @@ import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryp
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
/**
@@ -50,14 +55,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
/** The error a bad page size or a bad token is refused with. */
private static final String PAGINATION_ERROR = "ValidationException";
/** The only algorithm this service makes material for. */
private static final String SUPPORTED_ALGORITHM = "AES_256";
/** The only class this service makes material for. */
private static final String SUPPORTED_CLASS = "SYMMETRIC_KEY";
/** The class of a key pair, which has a public half and a private one. */
private static final String ASYMMETRIC_CLASS = "ASYMMETRIC_KEY_PAIR";
/** The class of a key that is only a public half. */
private static final String PUBLIC_KEY_CLASS = "PUBLIC_KEY";
private final StorageBackend<String, PaymentCryptographyKey> keyStore;
private final StorageBackend<String, PaymentCryptographyAlias> aliasStore;
private final RegionResolver regionResolver;
private final SecureRandom secureRandom;
private final PaymentCryptographyRequestContext requestContext;
@@ -81,6 +90,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
this(keyStore, aliasStore, regionResolver, new SecureRandom(), requestContext);
}
/**
* The service over two stores, with a request context of its own.
*
* <p>The context belongs to a request in the running service, so a caller that is not
* one, such as a test, is given one that resolves its aliases itself.
*/
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
RegionResolver regionResolver) {
this(keyStore, aliasStore, regionResolver, new SecureRandom(),
new PaymentCryptographyRequestContext());
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
RegionResolver regionResolver,
@@ -99,45 +121,130 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
public PaymentCryptographyKey createKey(String region, Map<String, Object> attributes,
Map<String, Boolean> modesOfUse, boolean exportable,
boolean enabled, Map<String, String> tags) {
String algorithm = string(attributes, "KeyAlgorithm", "AES_256");
return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, null);
}
/**
* Makes a key, with the material it is given rather than with fresh material.
*
* <p>An imported key holds the material that came in with it, so the material is a
* parameter of the key that is made.
*/
private PaymentCryptographyKey makeKey(String region, Map<String, Object> attributes,
Map<String, Boolean> modesOfUse, boolean exportable,
boolean enabled, Map<String, String> tags,
String materialHex) {
return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, materialHex,
null, null, null);
}
/**
* Makes a key, with the material it is given rather than with fresh material.
*
* <p>An imported key holds the material that came in with it, so the material is a
* parameter of the key that is made. An asymmetric key holds a key pair rather than
* material, so its halves are parameters too.
*
* @param publicKeyBase64 the public half of an asymmetric key, or null
* @param privateKeyBase64 the private half of an asymmetric key, or null
* @param certificatePem the certificate an imported public key arrived with, or null
*/
private PaymentCryptographyKey makeKey(String region, Map<String, Object> attributes,
Map<String, Boolean> modesOfUse, boolean exportable,
boolean enabled, Map<String, String> tags,
String materialHex, String publicKeyBase64,
String privateKeyBase64, String certificatePem) {
String algorithmName = string(attributes, "KeyAlgorithm", "AES_256");
String keyClass = string(attributes, "KeyClass", "SYMMETRIC_KEY");
// The material is AES-256 and symmetric, so a key that says otherwise would be a key
// The material has to be the algorithm's, so a key that says otherwise would be a key
// whose attributes do not describe it.
if (!SUPPORTED_ALGORITHM.equals(algorithm)) {
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.from(algorithmName);
if (algorithm == null) {
throw new AwsException("ValidationException",
"KeyAlgorithm '" + algorithm + "' is not supported, this service makes "
+ SUPPORTED_ALGORITHM + " keys", 400);
"KeyAlgorithm '" + algorithmName + "' is not supported, this service makes "
+ PaymentCryptographyKeyAlgorithm.supportedAll() + " keys", 400);
}
if (!SUPPORTED_CLASS.equals(keyClass)) {
if (!SUPPORTED_CLASS.equals(keyClass) && !ASYMMETRIC_CLASS.equals(keyClass)
&& !PUBLIC_KEY_CLASS.equals(keyClass)) {
throw new AwsException("ValidationException",
"KeyClass '" + keyClass + "' is not supported, this service makes "
+ SUPPORTED_CLASS + " keys", 400);
+ SUPPORTED_CLASS + ", " + ASYMMETRIC_CLASS + " and " + PUBLIC_KEY_CLASS
+ " keys", 400);
}
// The class says what shape the key has, and the algorithm says what material it
// has, so the two must agree: a symmetric algorithm cannot make a key pair, and an
// asymmetric one cannot make a symmetric key.
boolean symmetric = algorithm.symmetric();
if (symmetric && !SUPPORTED_CLASS.equals(keyClass)) {
throw new AwsException("ValidationException",
"KeyAlgorithm '" + algorithmName + "' is a symmetric algorithm, so the key is a "
+ SUPPORTED_CLASS + " and not a " + keyClass, 400);
}
if (!symmetric && SUPPORTED_CLASS.equals(keyClass)) {
throw new AwsException("ValidationException",
"KeyAlgorithm '" + algorithmName + "' is an asymmetric algorithm, so the key is a "
+ ASYMMETRIC_CLASS + " or a " + PUBLIC_KEY_CLASS + " and not a "
+ SUPPORTED_CLASS, 400);
}
// The usage says what the key is for, so a key without one is not a key: the service
// refuses it rather than guessing a purpose for it.
String usage = usage(attributes);
// The usage binds the key to its purpose, and a key whose algorithm does not serve
// that purpose is not one the service makes.
String badAlgorithm = PaymentCryptographyKeyAlgorithm.refusal(usage, algorithm);
if (badAlgorithm != null) {
throw new AwsException("ValidationException", badAlgorithm, 400);
}
PaymentCryptographyKey key = new PaymentCryptographyKey();
key.setKeyId(UUID.randomUUID().toString().replace("-", ""));
key.setRegion(region);
key.setArn(regionResolver.buildArn(SERVICE, region, "key/" + key.getKeyId()));
key.setKeyAlgorithm(algorithm);
key.setKeyAlgorithm(algorithm.name());
key.setKeyClass(keyClass);
key.setKeyUsage(usage(attributes));
key.setKeyUsage(usage);
key.setDeriveKeyUsage(string(attributes, "DeriveKeyUsage", ""));
key.setKeyModesOfUse(modesOfUse);
key.setExportable(exportable);
key.setEnabled(enabled);
key.setTags(new LinkedHashMap<>(tags));
key.setKeyState("CREATE_COMPLETE");
key.setKeyMaterialHex(PaymentCryptographyCrypto.randomAes256Hex(secureRandom));
key.setKeyCheckValue(PaymentCryptographyCrypto.checkValue(key.getKeyMaterialHex()));
key.setKeyCheckValueAlgorithm("CMAC");
key.setKeyMaterialHex(materialHex);
key.setKeyPublicKeyBase64(publicKeyBase64);
key.setKeyPrivateKeyBase64(privateKeyBase64);
key.setKeyCertificatePem(certificatePem);
if (algorithm.symmetric()) {
key.setKeyMaterialHex(materialHex != null
? materialHex
: PaymentCryptographyCrypto.randomMaterialHex(algorithm, secureRandom));
key.setKeyCheckValue(
PaymentCryptographyCrypto.checkValue(key.getKeyMaterialHex(), algorithm));
key.setKeyCheckValueAlgorithm(algorithm.checkValueAlgorithm());
} else {
// An asymmetric key has no material a check value could be computed from, so it
// reports the fixed placeholder a public key does.
key.setKeyCheckValue("000000");
key.setKeyCheckValueAlgorithm(algorithm.checkValueAlgorithm());
if (key.getKeyPublicKeyBase64() == null) {
KeyPair pair = algorithm.rsa
? PaymentCryptographyKeyPairs.rsa(algorithm.bytes * 8, secureRandom)
: PaymentCryptographyKeyPairs.ec(algorithm, secureRandom);
key.setKeyPublicKeyBase64(Base64.getEncoder()
.encodeToString(pair.getPublic().getEncoded()));
if (!PUBLIC_KEY_CLASS.equals(keyClass)) {
key.setKeyPrivateKeyBase64(Base64.getEncoder()
.encodeToString(pair.getPrivate().getEncoded()));
}
}
}
long now = Instant.now().getEpochSecond();
key.setCreateTimestamp(now);
key.setUsageStartTimestamp(now);
keyStore.put(key.getKeyId(), key);
keyStore.put(storageKey(region, key.getKeyId()), key);
return key;
}
/** The key an identifier names, or null when there is none. */
public PaymentCryptographyKey findKey(String region, String identifier) {
if (identifier == null || identifier.isEmpty()) {
public PaymentCryptographyKey findKey(String region, String identifier) { if (identifier == null || identifier.isEmpty()) {
return null;
}
if (identifier.startsWith("alias/")) {
@@ -161,7 +268,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
}
return null;
}
PaymentCryptographyKey byId = keyStore.get(identifier).orElse(null);
PaymentCryptographyKey byId = findKeyRecord(keyStore, region, identifier);
return byId != null && region.equals(byId.getRegion()) ? byId : null;
}
@@ -211,6 +318,10 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
key.setKeyState("DELETE_PENDING");
key.setEnabled(false);
key.setDeletePendingTimestamp(now);
keyStore.delete(storageKey(key.getRegion(), key.getKeyId()));
// A key saved before the region became part of its name is under that name too,
// and it goes with the key: a record left behind would be a key that was deleted
// and still there.
keyStore.delete(key.getKeyId());
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
if (key.getKeyId().equals(alias.getKeyId())) {
@@ -229,7 +340,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
* by name and region together.
*/
public PaymentCryptographyAlias findAlias(String region, String aliasName) {
return aliasStore.get(aliasKey(aliasName, region)).orElse(null);
return findAliasRecord(region, aliasName);
}
/**
@@ -247,7 +358,9 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
keyId = alias == null || alias.getKeyId() == null ? "" : alias.getKeyId();
requestContext.pinAliasKeyId(region, aliasName, keyId);
}
return keyId.isEmpty() ? null : keyStore.get(keyId).orElse(null);
// A key saved before the region became part of its name is still found under that
// name, so an alias written then keeps working.
return keyId.isEmpty() ? null : findKeyRecord(keyStore, region, keyId);
}
/** Points a name at a key. The name must be free in the key's region. */
@@ -342,7 +455,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
public synchronized void tag(PaymentCryptographyKey key, Map<String, String> tags) {
PaymentCryptographyKey current = liveKey(key);
current.getTags().putAll(tags);
keyStore.put(current.getKeyId(), current);
storeKey(current);
}
/**
@@ -354,7 +467,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
* read again under the lock and the request fails if it is not there.
*/
private PaymentCryptographyKey liveKey(PaymentCryptographyKey key) {
PaymentCryptographyKey current = keyStore.get(key.getKeyId()).orElse(null);
PaymentCryptographyKey current =
findKeyRecord(keyStore, key.getRegion(), key.getKeyId());
if (current == null) {
throw new AwsException("ResourceNotFoundException",
"Key " + key.getArn() + " is not found", 400);
@@ -362,13 +476,29 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return current;
}
/**
* Writes a key back, under the name the store holds it under now.
*
* <p>A record that was found under the older name is moved to the current one, so the
* store holds one record of the key and not two.
*
* @param key the key to write
*/
private void storeKey(PaymentCryptographyKey key) {
String current = storageKey(key.getRegion(), key.getKeyId());
keyStore.put(current, key);
if (!key.getKeyId().equals(current)) {
keyStore.delete(key.getKeyId());
}
}
/** Removes tags from a key, in this region only. */
public synchronized void untag(PaymentCryptographyKey key, List<String> tagKeys) {
PaymentCryptographyKey current = liveKey(key);
for (String tagKey : tagKeys) {
current.getTags().remove(tagKey);
}
keyStore.put(current.getKeyId(), current);
storeKey(current);
}
/**
@@ -393,6 +523,190 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
}
// ---- the replication ------------------------------------------------------
// ---- the key exchange ----------------------------------------------------
/**
* The usages a key block may carry, and the modes of use each of them has.
*
* <p>A key block carries the usage of the key it carries, so every usage the service
* makes has to have a code, or a key of that usage cannot leave the service and the
* counterparty cannot tell what it has.
*/
private static final Map<String, String> USAGE_NAMES = Map.ofEntries(
Map.entry("B0", "TR31_B0_BASE_DERIVATION_KEY"),
Map.entry("C0", "TR31_C0_CARD_VERIFICATION_KEY"),
Map.entry("D0", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
Map.entry("E0", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"),
Map.entry("E1", "TR31_E1_EMV_MKEY_CONFIDENTIALITY"),
Map.entry("E2", "TR31_E2_EMV_MKEY_INTEGRITY"),
Map.entry("E4", "TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS"),
Map.entry("E5", "TR31_E5_EMV_MKEY_CARD_PERSONALIZATION"),
Map.entry("E6", "TR31_E6_EMV_MKEY_OTHER"),
Map.entry("K0", "TR31_K0_KEY_ENCRYPTION_KEY"),
Map.entry("K1", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
Map.entry("M0", "TR31_M0_ISO_16609_MAC_KEY"),
Map.entry("M1", "TR31_M1_ISO_9797_1_MAC_KEY"),
Map.entry("M3", "TR31_M3_ISO_9797_3_MAC_KEY"),
Map.entry("M6", "TR31_M6_ISO_9797_5_CMAC_KEY"),
Map.entry("M7", "TR31_M7_HMAC_KEY"),
Map.entry("P0", "TR31_P0_PIN_ENCRYPTION_KEY"),
Map.entry("P1", "TR31_P1_PIN_GENERATION_KEY"),
Map.entry("V1", "TR31_V1_IBM3624_PIN_VERIFICATION_KEY"),
Map.entry("V2", "TR31_V2_VISA_PIN_VERIFICATION_KEY"),
Map.entry("S0", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"));
/** The TR-31 usage code of a usage name, such as {@code D0}. */
static String usageCode(String usageName) {
for (Map.Entry<String, String> entry : USAGE_NAMES.entrySet()) {
if (entry.getValue().equals(usageName)) {
return entry.getKey();
}
}
throw new AwsException("ValidationException",
"the usage " + usageName + " cannot leave the service: a key block carries one of "
+ USAGE_NAMES.keySet(), 400);
}
/**
* Whether a key is an AES key rather than a TDES 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 isAes(PaymentCryptographyKey key) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
return algorithm != null && algorithm.aes;
}
/**
* The algorithm byte of a key: {@code A} for an AES key and {@code T} for a TDES one.
*
* <p>The key record knows its algorithm, so the byte is read from there and not guessed from
* the length of the material, because a TDES key and an AES key of the same length are
* 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";
}
/** The usage name of a TR-31 usage code, such as {@code TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY}. */
static String usageName(String usageCode) {
String usage = USAGE_NAMES.get(usageCode);
if (usage == null) {
throw new AwsException("ValidationException",
"the usage " + usageCode + " of the key block is not one this service serves: "
+ USAGE_NAMES.keySet(), 400);
}
return usage;
}
/**
* The modes of use a mode of use code of a key block stands for.
*
* <p>A key encryption key wraps and unwraps rather than encrypts and decrypts, so the
* same character means the other modes for one.
*
* @param mode the mode of use character of the block
* @param isKek true when the block carries a key encryption key
*/
static Map<String, Boolean> modesFor(String mode, boolean isKek) {
return switch (mode) {
case "B" -> isKek
? Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE)
: Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE);
case "E" -> isKek
? Map.of("Wrap", Boolean.TRUE)
: Map.of("Encrypt", Boolean.TRUE);
case "D" -> isKek
? Map.of("Unwrap", Boolean.TRUE)
: Map.of("Decrypt", Boolean.TRUE);
case "G" -> Map.of("Generate", Boolean.TRUE);
case "V" -> Map.of("Verify", Boolean.TRUE);
case "C" -> Map.of("Generate", Boolean.TRUE, "Verify", Boolean.TRUE);
case "X" -> Map.of("DeriveKey", Boolean.TRUE);
case "N" -> Map.of("NoRestrictions", Boolean.TRUE);
default -> throw new AwsException("ValidationException",
"the mode of use " + mode + " of the key block is not one this service serves", 400);
};
}
/**
* The mode of use character a key block carries.
*
* <p>The character is read off the key's own modes, because that is what it says: a key
* that encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key
* encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are read
* that way.
*
* @param key the key the block carries
* @return the character
*/
static String modeCode(PaymentCryptographyKey key) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
boolean isKek = isKeyEncryptionKey(key.getKeyUsage());
boolean encrypt = isKek
? enabled(modes, "Wrap") || enabled(modes, "Encrypt")
: enabled(modes, "Encrypt");
boolean decrypt = isKek
? enabled(modes, "Unwrap") || enabled(modes, "Decrypt")
: enabled(modes, "Decrypt");
boolean generate = enabled(modes, "Generate");
boolean verify = enabled(modes, "Verify");
boolean derive = enabled(modes, "DeriveKey");
if (encrypt && decrypt) {
return "B";
}
if (encrypt) {
return "E";
}
if (decrypt) {
return "D";
}
if (generate && verify) {
return "C";
}
if (generate) {
return "G";
}
if (verify) {
return "V";
}
if (derive) {
return "X";
}
return "N";
}
/** Whether a mode of use is on. A key with no modes at all has every one of them. */
private static boolean enabled(Map<String, Boolean> modes, String mode) {
return modes == null || Boolean.TRUE.equals(modes.get(mode));
}
/** Whether a usage is a key encryption key's, whose modes wrap and unwrap. */
static boolean isKeyEncryptionKey(String usageName) {
return "TR31_K0_KEY_ENCRYPTION_KEY".equals(usageName)
|| "TR31_K1_KEY_BLOCK_PROTECTION_KEY".equals(usageName);
}
/** Whether a key may wrap another key. */
static boolean mayWrap(PaymentCryptographyKey key) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
return modes == null || Boolean.TRUE.equals(modes.get("Wrap"))
|| Boolean.TRUE.equals(modes.get("Encrypt"));
}
/** Whether a key may unwrap another key. */
static boolean mayUnwrap(PaymentCryptographyKey key) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
return modes == null || Boolean.TRUE.equals(modes.get("Unwrap"))
|| Boolean.TRUE.equals(modes.get("Decrypt"));
}
// ---- helpers ------------------------------------------------------------
/**
@@ -437,6 +751,52 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return regionResolver.buildArn(SERVICE, region, "alias/" + alias);
}
/**
* The storage key of a key.
*
* <p>The region is part of it, because a multi-region key has one identifier in several
* regions, and each of them is a key of its own region.
*/
private static String storageKey(String region, String keyId) {
return region + "\u0000" + keyId;
}
/**
* The key a store holds under the name it was saved under.
*
* <p>A store written before the region became part of the name holds its keys under
* their identifier alone, and its aliases under their name alone. A record saved then is
* still found here, so a store that was not emptied keeps working.
*
* @param store the store to look in
* @param region the region the key is in
* @param keyId the key's identifier
* @param <T> what the store holds
* @return the key, or null when the store holds none
*/
private static <T> T findKeyRecord(StorageBackend<String, T> store, String region,
String keyId) {
Optional<T> current = store.get(storageKey(region, keyId));
if (current.isPresent()) {
return current.get();
}
return store.get(keyId).orElse(null);
}
/**
* The alias a store holds under the name it was saved under.
*
* <p>An alias saved before the region became part of the name is still found here.
*
* @param region the region the alias is in
* @param aliasName the alias's name
* @return the alias, or null when the store holds none
*/
private PaymentCryptographyAlias findAliasRecord(String region, String aliasName) {
PaymentCryptographyAlias current = aliasStore.get(aliasKey(aliasName, region)).orElse(null);
return current != null ? current : aliasStore.get(aliasName).orElse(null);
}
/**
* The storage key of an alias.
*
@@ -471,4 +831,9 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
keyStore.clear();
aliasStore.clear();
}
/** The key store, for the tests. */
Optional<PaymentCryptographyKey> storedKey(String region, String keyId) {
return keyStore.get(storageKey(region, keyId));
}
}
@@ -29,6 +29,11 @@ public class PaymentCryptographyKey {
private String keyAlgorithm;
private String keyClass;
private String keyUsage;
/**
* The usage a key derives other keys for, when the key is a derivation key.
* Empty for a key that derives nothing.
*/
private String deriveKeyUsage;
private Map<String, Boolean> keyModesOfUse = new HashMap<>();
private String keyOrigin = "AWS_PAYMENT_CRYPTOGRAPHY";
private String keyCheckValue;
@@ -37,11 +42,38 @@ public class PaymentCryptographyKey {
private boolean exportable;
private boolean enabled = true;
private String keyMaterialHex;
/**
* The public half of an asymmetric key, base64 of the DER of its
* SubjectPublicKeyInfo. Empty for a symmetric key, which has one blob of
* material instead.
*/
private String keyPublicKeyBase64;
/**
* The private half of an asymmetric key, base64 of the DER of its PKCS#8
* encoding. Empty for a public key, which has no private half.
*
* <p>It is not written to the store, for the same reason the symmetric
* material is not: a private key in clear in the data directory is a
* secret on disk.
*/
private String keyPrivateKeyBase64;
/**
* The certificate an imported public key arrived with, in PEM. A key the
* service made has none, and gets a self-signed one when one is asked for.
*/
private String keyCertificatePem;
private long createTimestamp;
private long usageStartTimestamp;
private long deletePendingTimestamp;
private long deleteTimestamp;
private Map<String, String> tags = new HashMap<>();
/** The region of the primary of a multi-region key, and its own region otherwise. */
/** The regions a multi-region key is in, besides the primary's. */
/** Whether this record is the primary of a multi-region key or a replica of one. */
/** Whether the key took the account's default replication regions. */
public String getKeyId() { return keyId; }
public void setKeyId(String keyId) { this.keyId = keyId; }
@@ -61,6 +93,9 @@ public class PaymentCryptographyKey {
public String getKeyUsage() { return keyUsage; }
public void setKeyUsage(String keyUsage) { this.keyUsage = keyUsage; }
public String getDeriveKeyUsage() { return deriveKeyUsage; }
public void setDeriveKeyUsage(String deriveKeyUsage) { this.deriveKeyUsage = deriveKeyUsage; }
public Map<String, Boolean> getKeyModesOfUse() { return keyModesOfUse; }
public void setKeyModesOfUse(Map<String, Boolean> keyModesOfUse) { this.keyModesOfUse = keyModesOfUse; }
@@ -89,6 +124,28 @@ public class PaymentCryptographyKey {
public String getKeyMaterialHex() { return keyMaterialHex; }
public void setKeyMaterialHex(String keyMaterialHex) { this.keyMaterialHex = keyMaterialHex; }
public String getKeyPublicKeyBase64() { return keyPublicKeyBase64; }
public void setKeyPublicKeyBase64(String keyPublicKeyBase64) {
this.keyPublicKeyBase64 = keyPublicKeyBase64;
}
/**
* The private half of an asymmetric key.
*
* <p>It is held by the key and never written to the store, like the
* symmetric material.
*/
@JsonIgnore
public String getKeyPrivateKeyBase64() { return keyPrivateKeyBase64; }
public void setKeyPrivateKeyBase64(String keyPrivateKeyBase64) {
this.keyPrivateKeyBase64 = keyPrivateKeyBase64;
}
public String getKeyCertificatePem() { return keyCertificatePem; }
public void setKeyCertificatePem(String keyCertificatePem) {
this.keyCertificatePem = keyCertificatePem;
}
public long getCreateTimestamp() { return createTimestamp; }
public void setCreateTimestamp(long createTimestamp) { this.createTimestamp = createTimestamp; }
@@ -2,63 +2,155 @@ package io.github.hectorvent.floci.services.paymentcryptography;
import org.junit.jupiter.api.Test;
import java.security.SecureRandom;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The AES-CMAC of RFC 4493, against the examples the RFC gives.
* The cryptography of the key record and of the data plane, against values another
* implementation computed.
*
* <p>The examples cover the three cases the algorithm has: a message of no
* length, which is padded and masked with K2; a message of whole blocks, which
* is masked with K1; and a message of blocks and a part, whose last block is
* padded and masked with K2.
* <p>The CMAC vectors are the ones RFC 4493 uses, and the key wrap is the one RFC 3394
* publishes. The CBC vector was computed with the same padding the service uses, so a
* difference in it is a difference in the encryption rather than in the padding.
*/
class PaymentCryptographyCryptoTest {
/** The key of every example the RFC gives. */
private static final String KEY = "2B7E151628AED2A6ABF7158809CF4F3C";
/** The key of the RFC 4493 examples. */
private static final String RFC4493_KEY = "2b7e151628aed2a6abf7158809cf4f3c";
/** The CMAC of a message under {@link #KEY}, as hexadecimal. */
private static String cmac(String message) {
return PaymentCryptographyCrypto.toHex(
PaymentCryptographyCrypto.cmac(PaymentCryptographyCrypto.fromHex(KEY),
PaymentCryptographyCrypto.fromHex(message)));
private static final String M1 = "6bc1bee22e409f96e93d7e117393172a";
private static final String M2 = "ae2d8a571e03ac9c9eb76fac45af8e51";
private static final String M3 = "30c81c46a35ce411e5fbc1191a0a52ef";
private static final String M4 = "f69f2445df4f9b17ad2b417be66c3710";
@Test
void theCmacIsTheOneOfTheStandard() {
assertEquals("bb1d6929e95937287fa37d129b756746", mac(""));
assertEquals("070a16b46b4d4144f79bdd9dd04a287c", mac(M1));
assertEquals("ce0cbf1738f4df6428b1d93bf12081c9", mac(M1 + M2));
assertEquals("dfa66747de9ae63030ca32611497c827", mac(M1 + M2 + M3.substring(0, 16)));
assertEquals("c47c4d9d64588f67fb9de6fe745d7fbf", mac(M1 + M2 + M3));
assertEquals("51f0bebf7e3b9d92fc49741779363cfe", mac(M1 + M2 + M3 + M4));
}
/** RFC 4493's example 1: a message of no length. */
@Test
void anEmptyMessageIsTheMacTheRfcGives() {
assertEquals("bb1d6929e95937287fa37d129b756746", cmac(""));
void theCmacOfAPartialBlockUsesTheSecondSubkey() {
// The last block is padded here, so the second subkey is the one that is used.
assertEquals("41ccdefead58e63835d7582e9f2e5b62", mac(M1 + M2 + M3 + M4.substring(0, 26)));
assertEquals("71c5a229ba6db8c471075ac5b9c64ffe", mac(M1.substring(0, 8)));
}
/** RFC 4493's example 2: a message of one whole block. */
@Test
void aWholeBlockIsTheMacTheRfcGives() {
assertEquals("070a16b46b4d4144f79bdd9dd04a287c", cmac("6bc1bee22e409f96e93d7e117393172a"));
void theCheckValueIsTheLeftmostThreeBytesOfTheCmacOfZeroes() {
// The check value is the CMAC of a whole block of zeroes, which is not the CMAC of
// the empty message: a whole block is exclusive-ored with the first subkey.
byte[] mac = PaymentCryptographyCrypto.cmac(
PaymentCryptographyCrypto.fromHex(RFC4493_KEY), new byte[16]);
assertEquals("7ad386c3760fb3498361a1cb5563bd70", PaymentCryptographyCrypto.toHex(mac));
assertEquals("7AD386", PaymentCryptographyCrypto.checkValue(RFC4493_KEY));
}
/** RFC 4493's example 3: two whole blocks and a padded one. */
@Test
void wholeBlocksAndAPaddedOneAreTheMacTheRfcGives() {
assertEquals("dfa66747de9ae63030ca32611497c827", cmac(
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
+ "30c81c46a35ce411"));
void theKeyWrapIsTheOneOfTheStandard() {
byte[] kek = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
byte[] keyData = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
byte[] wrapped = PaymentCryptographyCrypto.keyWrap(kek, keyData);
assertEquals("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5",
PaymentCryptographyCrypto.toHex(wrapped));
assertArrayEquals(keyData, PaymentCryptographyCrypto.keyUnwrap(kek, wrapped));
}
/** RFC 4493's example 4: four whole blocks. */
@Test
void severalWholeBlocksAreTheMacTheRfcGives() {
assertEquals("51f0bebf7e3b9d92fc49741779363cfe", cmac(
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
+ "30c81c46a35ce411e5fbc1191a0a52ef"
+ "f69f2445df4f9b17ad2b417be66c3710"));
void aKeyWrapUnderTheWrongKeyDoesNotOpen() {
byte[] kek = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
byte[] other = PaymentCryptographyCrypto.fromHex("0f0e0d0c0b0a09080706050403020100");
byte[] keyData = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
byte[] wrapped = PaymentCryptographyCrypto.keyWrap(kek, keyData);
assertNull(PaymentCryptographyCrypto.keyUnwrap(other, wrapped));
}
/**
* The check value of a key is the leftmost three bytes of the CMAC of
* sixteen zero bytes under it, which is the CMAC of one whole block.
*/
@Test
void theCheckValueIsTheLeftmostThreeBytesOfTheMacOfSixteenZeroBytes() {
assertEquals("7AD386", PaymentCryptographyCrypto.checkValue(KEY));
void theEncryptionIsTheOneAnotherImplementationComputed() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] plaintext = PaymentCryptographyCrypto.fromHex(
"54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67");
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, new FixedRandom(
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
assertEquals("101112131415161718191a1b1c1d1e1fb746e4f1bce2352d20440b8a2e0eb8fd6"
+ "8c1fcd0d00fcac779ecaadacde7e51a41da205eac66749510362db1c9f3e6d5",
PaymentCryptographyCrypto.toHex(blob));
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob));
}
@Test
void aCiphertextOfAnotherKeyDoesNotOpen() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] other = PaymentCryptographyCrypto.fromHex(
"1f1e1d1c1b1a19181716151413121110f0e0d0c0b0a09080706050403020100");
// The vector is fixed, so the answer is fixed: with a random one the padding of the
// wrong key's plaintext can happen to be valid, and the test would fail now and then
// for no reason.
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, "hello".getBytes(),
new FixedRandom(PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
// The right key opens it, so the refusal below is about the key and not the blob.
assertArrayEquals("hello".getBytes(), PaymentCryptographyCrypto.decryptCbc(key, blob));
assertThrows(IllegalArgumentException.class,
() -> PaymentCryptographyCrypto.decryptCbc(other, blob));
}
@Test
void theEncryptionOfAnEmptyPlaintextIsTheVectorAndThePadding() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, new byte[0], new FixedRandom(
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
assertEquals(32, blob.length);
assertArrayEquals(new byte[0], PaymentCryptographyCrypto.decryptCbc(key, blob));
}
@Test
void theMaterialIsThirtyTwoBytesAndTheCheckValueIsSixCharacters() {
String material = PaymentCryptographyCrypto.randomAes256Hex(new SecureRandom());
assertEquals(64, material.length());
assertEquals(6, PaymentCryptographyCrypto.checkValue(material).length());
assertNotNull(PaymentCryptographyCrypto.checkValue(material));
}
private static String mac(String messageHex) {
return PaymentCryptographyCrypto.toHex(PaymentCryptographyCrypto.cmac(
PaymentCryptographyCrypto.fromHex(RFC4493_KEY),
PaymentCryptographyCrypto.fromHex(messageHex)));
}
/** A random that answers the same bytes every time, so a vector is a vector. */
private static final class FixedRandom extends SecureRandom {
private final byte[] bytes;
private int used;
FixedRandom(byte[] bytes) {
this.bytes = bytes;
}
@Override
public void nextBytes(byte[] target) {
System.arraycopy(bytes, 0, target, 0, Math.min(bytes.length, target.length));
used += target.length;
}
}
}
@@ -65,6 +65,36 @@ class PaymentCryptographyIntegrationTest {
.body("Key.KeyAttributes.KeyAlgorithm", equalTo("AES_256"));
}
@Test
void aDerivationKeySaysWhatItDerivesFor() {
// The usage a derivation key derives for sits beside the attributes, and it comes
// back with the key.
String arn = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_B0_BASE_DERIVATION_KEY\","
+ "\"KeyModesOfUse\":{\"DeriveKey\":true}},"
+ "\"DeriveKeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ "\"Exportable\":true}")
.then().statusCode(200)
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"))
.extract().path("Key.KeyArn");
call("GetKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200)
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
}
@Test
void aKeyThatAsksForACheckValueOfAnotherKindIsRefused() {
// The kind follows the algorithm, so a request that names another is refused
// rather than answered with a value of another kind.
call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},"
+ "\"KeyCheckValueAlgorithm\":\"CMAC\"}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void theKeysOfARegionAreListed() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
@@ -9,6 +9,11 @@ import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryp
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -16,6 +21,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -34,6 +40,16 @@ class PaymentCryptographyServiceTest {
new PaymentCryptographyRequestContext());
}
/** A key of the given algorithm and class, for the tests that need one. */
private PaymentCryptographyKey createKey(String region, String algorithm, String keyClass,
String usage, Map<String, Boolean> modes) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", algorithm);
attributes.put("KeyClass", keyClass);
attributes.put("KeyUsage", usage);
return service.createKey(region, attributes, modes, true, true, Map.of());
}
private PaymentCryptographyKey createKey(String region) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
@@ -57,6 +73,141 @@ class PaymentCryptographyServiceTest {
assertEquals(6, key.getKeyCheckValue().length());
}
@Test
void aTdesKeyCarriesTheAnsiCheckValueOfItsAlgorithm() {
// The ANSI X9.24 check value is the leftmost three bytes of the encrypted zeroes
// under the key, so it is the same for the two algorithms of different length only
// when the keys are the same.
PaymentCryptographyKey two = createKey("us-east-1", "TDES_2KEY", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE,
"Decrypt", Boolean.TRUE));
assertEquals("ANSI_X9_24", two.getKeyCheckValueAlgorithm());
assertEquals(32, two.getKeyMaterialHex().length());
PaymentCryptographyKey three = createKey("us-east-1", "TDES_3KEY", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE,
"Decrypt", Boolean.TRUE));
assertEquals("ANSI_X9_24", three.getKeyCheckValueAlgorithm());
assertEquals(48, three.getKeyMaterialHex().length());
}
@Test
void theCheckValueOfATdesKeyIsTheOneTheStandardGives() {
// The key of the vector, so the check value is the one of the standard.
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "TDES_2KEY");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
// The check value is the one the standard gives for the material the key carries.
assertEquals("ANSI_X9_24", key.getKeyCheckValueAlgorithm());
assertEquals(6, key.getKeyCheckValue().length());
assertEquals(checkValueOf(key.getKeyMaterialHex()), key.getKeyCheckValue());
// And the standard gives this value for the material of the vector.
assertEquals("08D7B4", checkValueOf("0123456789ABCDEFFEDCBA9876543210"));
}
@Test
void anEllipticCurveKeyIsAKeyPair() {
PaymentCryptographyKey key = createKey("us-east-1", "ECC_NIST_P256", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE,
"Verify", Boolean.TRUE));
assertEquals("ASYMMETRIC_KEY_PAIR", key.getKeyClass());
assertNotNull(key.getKeyPublicKeyBase64());
assertNotNull(key.getKeyPrivateKeyBase64());
// An asymmetric key has no material a check value could be computed from, so it
// reports the fixed placeholder.
assertEquals("000000", key.getKeyCheckValue());
assertEquals("ANSI_X9_24", key.getKeyCheckValueAlgorithm());
}
@Test
void aUsageThatTheAlgorithmCannotServeIsRefused() {
// A key pair has no material a symmetric usage would bind it to, and a symmetric
// key has no pair a key pair's usage would bind it to.
assertValidation(() -> createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
"TR31_M1_ISO_9797_1_MAC_KEY", Map.of("Generate", Boolean.TRUE)),
"may not be made of");
assertValidation(() -> createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE)),
"may not be made of");
}
@Test
void aKeyPairCarriesItsOwnHalves() {
// An RSA key is made of a pair, and the halves are kept with it.
PaymentCryptographyKey rsa = createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE));
assertNotNull(rsa.getKeyPublicKeyBase64());
assertNotNull(rsa.getKeyPrivateKeyBase64());
assertTrue(rsa.getKeyPublicKeyBase64().length() > 256,
"the public half of an RSA-2048 key is a long DER encoding");
// And an EC one is made of a pair on the curve the algorithm names.
PaymentCryptographyKey ec = createKey("us-east-1", "ECC_NIST_P256", "ASYMMETRIC_KEY_PAIR",
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
Map.of("DeriveKey", Boolean.TRUE));
assertNotNull(ec.getKeyPublicKeyBase64());
assertNotNull(ec.getKeyPrivateKeyBase64());
assertNotEquals(rsa.getKeyPublicKeyBase64(), ec.getKeyPublicKeyBase64(),
"the two pairs are different");
}
@Test
void everyAsymmetricUsageTakesAKeyPair() {
// The usages the model names for a key pair, each of which is made.
for (String usage : List.of("TR31_D1_ASYMMETRIC_KEY_FOR_DATA_ENCRYPTION",
"TR31_K2_TR34_ASYMMETRIC_KEY",
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE")) {
PaymentCryptographyKey key = createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
usage, Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE));
assertEquals("RSA_2048", key.getKeyAlgorithm());
assertEquals(usage, key.getKeyUsage());
}
// And the key agreement one takes a curve as well.
PaymentCryptographyKey agreed = createKey("us-east-1", "ECC_NIST_P256",
"ASYMMETRIC_KEY_PAIR", "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
Map.of("DeriveKey", Boolean.TRUE));
assertEquals("ECC_NIST_P256", agreed.getKeyAlgorithm());
}
@Test
void aClassThatContradictsTheAlgorithmIsRefused() {
assertValidation(() -> createKey("us-east-1", "AES_256", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Verify", Boolean.TRUE)),
"a symmetric algorithm");
assertValidation(() -> createKey("us-east-1", "RSA_2048", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE)),
"an asymmetric algorithm");
}
/** The ANSI X9.24 check value of a key's material, computed the way the standard says. */
private static String checkValueOf(String materialHex) {
byte[] material = HexFormat.of().parseHex(materialHex);
byte[] wide = new byte[24];
System.arraycopy(material, 0, wide, 0, 16);
System.arraycopy(material, 0, wide, 16, 8);
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(wide, "DESede"));
return HexFormat.of().withUpperCase().formatHex(cipher.doFinal(new byte[8]))
.substring(0, 6);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the Triple DES key could not be used", e);
}
}
private void assertValidation(Runnable refused, String message) {
AwsException failure = assertThrows(AwsException.class, refused::run);
assertEquals("ValidationException", failure.getErrorCode());
assertTrue(failure.getMessage().contains(message), failure.getMessage());
}
@Test
void theCheckValueIsTheLeftmostThreeBytesOfTheCmac() {
PaymentCryptographyKey key = createKey("us-east-1");
@@ -96,6 +247,39 @@ class PaymentCryptographyServiceTest {
// legitimately share one. Only the material has to differ.
}
@Test
void aKeySavedBeforeTheRegionWasPartOfItsNameIsStillFound() {
// A store written before the region became part of the name holds its keys under
// their identifier alone, so an alias written then keeps working.
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyKey key = createKey("us-east-1");
// The key under the name it was saved under before the region was part of it.
store.put(key.getKeyId(), key);
old.createAlias("alias/team/old-key", key);
PaymentCryptographyKey found = old.findKey("us-east-1", "alias/team/old-key");
assertNotNull(found, "the alias names the key that was saved under the old name");
assertEquals(key.getKeyId(), found.getKeyId());
}
@Test
void aDeletedKeyIsGoneUnderTheNameItWasSavedUnder() {
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyKey key = createKey("us-east-1");
store.put(key.getKeyId(), key);
old.deleteKey(key);
assertNull(store.get(key.getKeyId()).orElse(null),
"the key is gone under the name it was saved under too");
}
@Test
void theAliasNameIsUniqueInARegion() {
PaymentCryptographyKey key = createKey("us-east-1");
@@ -196,7 +380,9 @@ class PaymentCryptographyServiceTest {
@Test
void aKeyThatAsksForMaterialTheServiceDoesNotMakeIsRefused() {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_128");
// The service makes the AES sizes, so the algorithm it does not make is one it has
// no material for.
attributes.put("KeyAlgorithm", "DES");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");