diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java index d12978c35e..d822ee702c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java +++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCrypto.java @@ -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. * *
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. * - *
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. + *
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. + * + *
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. * - *
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. + *
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. + * + *
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. * - *
The bit that falls off the top of the block comes from the byte - * above it, so the carry travels down the block. + *
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. + * + *
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. + * + *
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. + * + *
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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java index 954654d33c..2b39c71521 100644 --- a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyJsonHandler.java @@ -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()); diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java new file mode 100644 index 0000000000..f26e4677da --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java @@ -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. + * + *
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. + * + *
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. + * + *
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. + * + *
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. + * + *
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 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 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);
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyPairs.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyPairs.java
new file mode 100644
index 0000000000..2642c42437
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyPairs.java
@@ -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.
+ *
+ * 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.
+ *
+ * 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");
+ };
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyStrength.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyStrength.java
new file mode 100644
index 0000000000..3d32e499d8
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyKeyStrength.java
@@ -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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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";
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyService.java b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyService.java
index 43b8ffab98..e520b476c6 100644
--- a/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyService.java
@@ -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 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 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 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 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 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 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.
+ *
+ * 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.
+ *
+ * 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 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 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.
+ *
+ * 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 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 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 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; }
diff --git a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCryptoTest.java b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCryptoTest.java
index 22d069fb29..706afb7de1 100644
--- a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCryptoTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyCryptoTest.java
@@ -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.
*
- * 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.
+ * 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;
+ }
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
index a3e831e071..fe274c9e88 100644
--- a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
@@ -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)
diff --git a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyServiceTest.java
index e36f3c743f..2f53557bce 100644
--- a/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/paymentcryptography/PaymentCryptographyServiceTest.java
@@ -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