blocks) {
+ StringBuilder out = new StringBuilder();
+ for (String[] block : blocks) {
+ String id = block[0];
+ String value = block[1];
+ // The length covers the whole block, the identifier and the length included.
+ out.append(id).append(two(4 + value.length(), 16)).append(value);
+ }
+ return out.toString();
+ }
+
+ /**
+ * How many characters the block's optional blocks take.
+ *
+ * An optional block is its identifier over two characters, its length over two, and
+ * then its value. The length covers the whole block in characters, the identifier and the
+ * length included, and it is written in hexadecimal. The header says how many of them
+ * there are.
+ *
+ * @param header the block's header
+ * @param block the whole block
+ * @return the length of the optional blocks, in characters
+ */
+ static int optionalLength(String header, String block) {
+ int count = parseInt(header.substring(12, 14), "the number of optional blocks");
+ int length = 0;
+ for (int i = 0; i < count; i++) {
+ length += optionalBlockLength(block, HEADER_LENGTH + length);
+ }
+ return length;
+ }
+
+ /**
+ * How many characters the optional block at a place takes.
+ *
+ *
The length field says how long the whole block is, the identifier and the length
+ * included. A block longer than a length field can hold says so with a zero length, and
+ * then the number of characters the length itself takes follows, and the length after
+ * that.
+ *
+ * @param block the whole block
+ * @param at where the optional block starts
+ * @return the length of the optional block, in characters
+ */
+ private static int optionalBlockLength(String block, int at) {
+ if (block.length() < at + 4) {
+ throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ + "is too short to hold them");
+ }
+ int length = parseInt(block.substring(at + 2, at + 4),
+ "the length of an optional block", 16);
+ if (length != 0) {
+ return length;
+ }
+ // The length did not fit in its field, so the field says so and the length follows
+ // the number of characters it takes.
+ if (block.length() < at + 8) {
+ throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ + "is too short to hold them");
+ }
+ int digits = parseInt(block.substring(at + 4, at + 6),
+ "the length of the length of an optional block", 16);
+ if (digits == 0 || block.length() < at + 6 + digits) {
+ throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ + "is too short to hold them");
+ }
+ return parseInt(block.substring(at + 6, at + 6 + digits),
+ "the length of an optional block", 16);
+ }
+
+ /** The usage code of a block's header, such as {@code D0}. */
+ static String usageOf(String block) {
+ return block.substring(5, 7);
+ }
+
+ /**
+ * Whether a block is a type D one, which is derived with AES.
+ *
+ *
The type is in the block's own header, so it is read from there and not from the
+ * wrapping key: a type D block is protected with AES and a type B one with TDES.
+ */
+ static boolean typeOf(String block) {
+ return "D".equals(block.substring(0, 1));
+ }
+
+ /** The type of a block, {@code D} or {@code B}, for a message that names it. */
+ static String typeName(String block) {
+ return block.substring(0, 1);
+ }
+
+ /** The mode of use code of a block's header, such as {@code B}. */
+ static String modeOf(String block) {
+ return block.substring(8, 9);
+ }
+
+ /** The exportability of a block's header: {@code E}, {@code N} or {@code S}. */
+ static String exportabilityOf(String block) {
+ return block.substring(11, 12);
+ }
+
+ /**
+ * The 16-character header of a block, whose layout the standard fixes.
+ *
+ * @param blockLength the length of the whole block, in characters
+ */
+ private static String header16(String type, String usage, String mode, String exportability,
+ int blockLength, String algorithm, String version,
+ int optionalBlocks) {
+ String header = type
+ + pad4(blockLength)
+ + usage
+ + algorithm // the algorithm of the key the block carries
+ + mode
+ + version // the version of the key
+ + exportability
+ + two(optionalBlocks, 10) // the number of optional blocks
+ + "00"; // the reserved characters
+ if (header.length() != HEADER_LENGTH) {
+ throw new IllegalArgumentException("the key block header must be 16 characters");
+ }
+ return header;
+ }
+
+ /** The algorithm the header of a block names for the key it carries. */
+ static String algorithmInHeader(String block) {
+ return block.substring(7, 8);
+ }
+
+ /** The length of the MAC of a block of that type, in characters. */
+ private static int macLength(boolean aes) {
+ return aes ? 32 : 16;
+ }
+
+ /**
+ * The two masks of the last block of the MAC: the CMAC subkeys of the MAC key.
+ *
+ *
A last block that needed no padding is masked with the first subkey and one that was
+ * padded with the second, which is what the reference implementation does.
+ */
+ private static byte[][] masksOf(byte[] macKey, boolean aes) {
+ if (aes) {
+ byte[][] subkeys = PaymentCryptographyCrypto.cmacSubkeys(macKey);
+ return new byte[][] {subkeys[0], subkeys[1]};
+ }
+ byte[] subkeys = cmacSubkeys(macKey, 8, TDEA_RB);
+ return new byte[][] {Arrays.copyOfRange(subkeys, 0, 8), Arrays.copyOfRange(subkeys, 8, 16)};
+ }
+
+ /**
+ * The key as a length encoded block: its length in bits in front of it, zero padded to the
+ * block size.
+ */
+ static byte[] lengthEncode(byte[] clearKey, int blockSize) {
+ byte[] body = new byte[2 + clearKey.length];
+ body[0] = (byte) ((clearKey.length * 8) >> 8);
+ body[1] = (byte) (clearKey.length * 8);
+ System.arraycopy(clearKey, 0, body, 2, clearKey.length);
+ int padding = (blockSize - (body.length % blockSize)) % blockSize;
+ byte[] out = new byte[body.length + padding];
+ System.arraycopy(body, 0, out, 0, body.length);
+ return out;
+ }
+
+ /** The block size of AES, in bytes. */
+ private static final int BLOCK_SIZE = 16;
+
+ /**
+ * The MAC of a block: the CBC-MAC of the header and the length encoded key under the MAC
+ * key, with the last block masked by a subkey of it.
+ *
+ *
A last block that needed no padding is masked with the first subkey and one that was
+ * padded with the second, which is what the reference implementation does.
+ */
+ static byte[] computeMac(String header, byte[] lengthEncoded, byte[] macKey, boolean aes) {
+ int blockSize = aes ? BLOCK_SIZE : 8;
+ byte[][] masks = masksOf(macKey, aes);
+ byte[] data = new byte[header.length() + lengthEncoded.length];
+ System.arraycopy(header.getBytes(StandardCharsets.US_ASCII), 0, data, 0, header.length());
+ System.arraycopy(lengthEncoded, 0, data, header.length(), lengthEncoded.length);
+
+ byte[] last;
+ if (data.length % blockSize != 0) {
+ int padding = blockSize - (data.length % blockSize);
+ data = Arrays.copyOf(data, data.length + padding);
+ data[data.length - padding] = (byte) 0x80;
+ last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[1]);
+ } else {
+ last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[0]);
+ }
+ byte[] macInput = Arrays.copyOf(data, data.length);
+ System.arraycopy(last, 0, macInput, macInput.length - blockSize, blockSize);
+ byte[] out = aes
+ ? PaymentCryptographyCrypto.aesCbcEncrypt(macKey, new byte[BLOCK_SIZE], macInput)
+ : Ciphers.tdesCbcEncrypt(macInput, Ciphers.widenTdesKey(macKey), new byte[8]);
+ return Arrays.copyOfRange(out, out.length - blockSize, out.length);
+ }
+
+ /**
+ * The two keys a block is made under: the one that encrypts the key and the one that
+ * authenticates it.
+ *
+ *
The derivation follows the family of the protection key, because the block type does
+ * too: a type D block is derived with AES and a type B one with Triple DES.
+ */
+ static byte[][] deriveKeys(byte[] protectionKey, boolean aes) {
+ return aes ? deriveAesKeys(protectionKey) : deriveTypeBKeys(protectionKey);
+ }
+
+ /**
+ * The derived keys of a type D block.
+ *
+ *
The derivation is the counter mode key derivation of NIST SP800-108, seeded with the
+ * second CMAC subkey of the protection key and encrypted by the protection key itself. The
+ * derived key is as long as the protection key: a 192-bit protection key derives a 192-bit
+ * key, whose second part is truncated to eight bytes, so the cipher that uses the result is
+ * AES-192 rather than a widened AES-256.
+ */
+ private static byte[][] deriveAesKeys(byte[] protectionKey) {
+ int bits = protectionKey.length * 8;
+ if (bits != 128 && bits != 192 && bits != 256) {
+ throw new IllegalArgumentException("a type D block needs a 128, 192 or 256 bit key block "
+ + "protection key, and this one is " + bits + " bits");
+ }
+ int derivedBytes = bits / 8;
+ int firstPart = 16;
+ int secondPart = derivedBytes - firstPart;
+ byte[] seed = PaymentCryptographyCrypto.cmacSubkeys(protectionKey)[1];
+
+ byte[] encryptionKey = new byte[derivedBytes];
+ byte[] macKey = new byte[derivedBytes];
+ System.arraycopy(part(seed, bits, false, 1, protectionKey), 0, encryptionKey, 0, firstPart);
+ System.arraycopy(part(seed, bits, true, 1, protectionKey), 0, macKey, 0, firstPart);
+ if (secondPart > 0) {
+ System.arraycopy(part(seed, bits, false, 2, protectionKey), 0, encryptionKey, firstPart,
+ secondPart);
+ System.arraycopy(part(seed, bits, true, 2, protectionKey), 0, macKey, firstPart, secondPart);
+ }
+ return new byte[][] {encryptionKey, macKey};
+ }
+
+ /**
+ * The derived keys of a type B block.
+ *
+ *
The derivation is the counter mode key derivation of NIST SP800-108, seeded with the
+ * first CMAC subkey of the protection key, and the reduction constant of Triple DES is the
+ * whole buffer rather than the top bit alone.
+ */
+ private static byte[][] deriveTypeBKeys(byte[] protectionKey) {
+ int bits = protectionKey.length * 8;
+ if (bits != 128 && bits != 192) {
+ throw new IllegalArgumentException("a type B block needs a 128 or 192 bit key block "
+ + "protection key, and this one is " + bits + " bits");
+ }
+ byte[] wide = Ciphers.widenTdesKey(protectionKey);
+ int parts = bits == 192 ? 3 : 2;
+ byte[] seed = Arrays.copyOfRange(cmacSubkeys(wide, 8, TDEA_RB), 0, 8);
+ byte[] encryptionKey = new byte[parts * 8];
+ byte[] macKey = new byte[parts * 8];
+ for (int counter = 1; counter <= parts; counter++) {
+ byte[] input = xor(seed, fromHex(typeBConstant(bits, false, counter)));
+ byte[] part = Ciphers.tdes3Encrypt(input, wide);
+ System.arraycopy(part, 0, encryptionKey, (counter - 1) * 8, 8);
+ input = xor(seed, fromHex(typeBConstant(bits, true, counter)));
+ part = Ciphers.tdes3Encrypt(input, wide);
+ System.arraycopy(part, 0, macKey, (counter - 1) * 8, 8);
+ }
+ return new byte[][] {encryptionKey, macKey};
+ }
+
+ /** The constant of the type B key derivation. */
+ private static String typeBConstant(int bits, boolean mac, int counter) {
+ String algorithm = bits == 192 ? "0001" : "0000";
+ String use = mac ? "0001" : "0000";
+ String keyLength = bits == 192 ? "00C0" : "0080";
+ return (counter < 10 ? "0" + counter : Integer.toString(counter))
+ + use + "00" + algorithm + keyLength;
+ }
+
+ /**
+ * The CMAC subkeys of a TDES key.
+ *
+ *
The reduction constant of Triple DES is the whole buffer, which is what the reference
+ * implementation does, and it is not the top bit alone.
+ */
+ private static byte[] cmacSubkeys(byte[] key, int blockSize, String rbHex) {
+ byte[] s = Ciphers.tdes3Encrypt(new byte[blockSize], key);
+ byte[] rb = fromHex(rbHex);
+ byte[] k1 = shiftXor(s, rb);
+ byte[] k2 = shiftXor(k1, rb);
+ byte[] out = new byte[k1.length + k2.length];
+ System.arraycopy(k1, 0, out, 0, k1.length);
+ System.arraycopy(k2, 0, out, k1.length, k2.length);
+ return out;
+ }
+
+ /** A left shift by one bit, then the reduction constant when the top bit was set. */
+ private static byte[] shiftXor(byte[] value, byte[] rb) {
+ byte[] out = new byte[value.length];
+ int carry = 0;
+ for (int i = value.length - 1; i >= 0; i--) {
+ int nextCarry = (value[i] & 0x80) != 0 ? 1 : 0;
+ out[i] = (byte) (((value[i] << 1) | carry) & 0xff);
+ carry = nextCarry;
+ }
+ if ((value[0] & 0x80) != 0) {
+ for (int i = 0; i < out.length; i++) {
+ out[i] ^= rb[i % rb.length];
+ }
+ }
+ return out;
+ }
+
+ /** One part of the derivation: the protection key encrypts the seeded constant. */
+ private static byte[] part(byte[] seed, int bits, boolean mac, int counter, byte[] protectionKey) {
+ byte[] constant = fromHex(derivationConstant(bits, mac, counter));
+ byte[] input = xor(seed, constant);
+ return PaymentCryptographyCrypto.aesEcbEncrypt(input, protectionKey);
+ }
+
+ /** The constant of the key derivation, which says what is derived and how long it is. */
+ private static String derivationConstant(int bits, boolean mac, int counter) {
+ String algorithm = bits == 128 ? "0002" : bits == 192 ? "0003" : "0004";
+ String use = mac ? "0001" : "0000";
+ String keyLength = bits == 128 ? "0080" : bits == 192 ? "00C0" : "0100";
+ return (counter < 10 ? "0" + counter : Integer.toString(counter))
+ + use + "00" + algorithm + keyLength + AES_IV_CONST;
+ }
+
+ /** Two byte arrays, one after the other. */
+
+ private static byte[] xor(byte[] left, byte[] right) {
+ byte[] out = new byte[left.length];
+ for (int i = 0; i < left.length; i++) {
+ out[i] = (byte) (left[i] ^ right[i % right.length]);
+ }
+ return out;
+ }
+
+ /** The length of the block, in four decimal characters. */
+ private static String pad4(int value) {
+ String text = Integer.toString(value);
+ if (text.length() > 4) {
+ throw new IllegalArgumentException("the key block is too long: " + value);
+ }
+ return "0000".substring(0, 4 - text.length()) + text;
+ }
+
+ /**
+ * A number of two characters, in the radix the field it goes into is written in.
+ *
+ *
The header's count of the optional blocks is written in ten, and the length of an
+ * optional block in sixteen, as the standard has it.
+ *
+ * @param value the number
+ * @param radix the radix the field is written in
+ * @return the number, in two characters
+ */
+ private static String two(int value, int radix) {
+ String text = Integer.toString(value, radix).toUpperCase(Locale.ROOT);
+ if (text.length() > 2) {
+ throw new IllegalArgumentException("the number does not fit in two characters: " + value);
+ }
+ return "00".substring(0, 2 - text.length()) + text;
+ }
+
+ private static int parseInt(String text, String what) {
+ return parseInt(text, what, 10);
+ }
+
+ /**
+ * A number of the text.
+ *
+ *
The length of the block is written in decimal and the length of the key in the
+ * length encoded block is written in hexadecimal, so the base is a parameter.
+ */
+ private static int parseInt(String text, String what, int radix) {
+ try {
+ return Integer.parseInt(text, radix);
+ } catch (NumberFormatException e) {
+ throw new IllegalArgumentException(what + " is not a number: " + text);
+ }
+ }
+
+ private static String hexUpper(byte[] bytes) {
+ return PaymentCryptographyCrypto.toHex(bytes).toUpperCase(Locale.ROOT);
+ }
+
+ private static byte[] fromHex(String hex) {
+ try {
+ return PaymentCryptographyCrypto.fromHex(hex);
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException("the key block is not hexadecimal");
+ }
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java
new file mode 100644
index 0000000000..b3039ff9ac
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Certificates.java
@@ -0,0 +1,134 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import io.floci.aws.core.common.CertificateMaterialException;
+import io.floci.aws.core.common.Pem;
+import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
+import org.bouncycastle.util.io.pem.PemObject;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.security.cert.CertificateException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Base64;
+
+/**
+ * The certificates the key exchange hands out and reads.
+ *
+ *
The service gives a counterparty a certificate over a key pair it made for the occasion,
+ * and reads the certificate a counterparty brings. A certificate travels in three shapes: PEM,
+ * base64 of PEM (which is how the service returns one), and base64 of DER.
+ *
+ *
Reading a certificate is the emulator's own business, through {@link Pem}; minting one
+ * belongs to ACM's generator, which the service asks for a certificate with.
+ */
+public final class Certificates {
+
+ private Certificates() {
+ }
+
+ /** A minted certificate, in the two forms the service uses it in. */
+ public record Minted(byte[] der, String pem) {
+ }
+
+ /**
+ * Parse a certificate the service hands over, or one a counterparty brings.
+ *
+ *
PEM, base64 of PEM and base64 of DER are all accepted: the service returns a
+ * certificate as base64 of its PEM, and a client certificate arrives the same way.
+ *
+ * @param pemOrBase64 the certificate, in any of those shapes
+ * @return the parsed certificate
+ * @throws IllegalArgumentException if the text is not a certificate in any of them
+ */
+ public static X509Certificate parseCertificate(String pemOrBase64) {
+ String text = pemOrBase64 == null ? "" : pemOrBase64.trim();
+ if (text.contains("-----BEGIN")) {
+ return readPem(text);
+ }
+ byte[] decoded;
+ try {
+ decoded = Base64.getMimeDecoder().decode(text);
+ } catch (IllegalArgumentException e) {
+ throw new IllegalArgumentException("the certificate is neither PEM nor base64");
+ }
+ String decodedText = new String(decoded, StandardCharsets.UTF_8);
+ // base64 of a PEM, which is how the service returns one, or base64 of the DER itself.
+ if (decodedText.contains("-----BEGIN")) {
+ return readPem(decodedText);
+ }
+ return readDer(decoded);
+ }
+
+ /** The certificate a DER document holds. */
+ private static X509Certificate readDer(byte[] der) {
+ try {
+ return (X509Certificate) CertificateFactory.getInstance("X.509")
+ .generateCertificate(new ByteArrayInputStream(der));
+ } catch (CertificateException e) {
+ throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage());
+ }
+ }
+
+ /** The certificate a PEM document holds, read by the emulator's own PEM reader. */
+ private static X509Certificate readPem(String pem) {
+ try {
+ return Pem.parseCertificate(pem);
+ } catch (CertificateMaterialException e) {
+ throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage());
+ }
+ }
+
+ /**
+ * The identifier a TR-34 block uses to name its recipient.
+ *
+ *
A RecipientInfo carries the receiver's certificate identifier: an
+ * IssuerAndSerialNumber, which is the issuer's name and the certificate's serial number.
+ * Both are taken from the certificate itself, so the identifier is the one the receiver's
+ * own certificate carries.
+ *
+ * @param certDer the certificate in DER
+ * @return the issuer and serial number, as the DER of an IssuerAndSerialNumber
+ */
+ public static byte[] certificateId(byte[] certDer) {
+ X509Certificate certificate = readDer(certDer);
+ try {
+ return new IssuerAndSerialNumber(
+ new X500Name(certificate.getIssuerX500Principal().getName()),
+ certificate.getSerialNumber()).getEncoded();
+ } catch (IOException e) {
+ throw new IllegalStateException("cannot encode the certificate identifier", e);
+ }
+ }
+
+ /**
+ * Wrap DER as a PEM document.
+ *
+ * @param der the certificate in DER
+ * @return the certificate in PEM
+ */
+ public static String toPem(byte[] der) {
+ StringWriter writer = new StringWriter();
+ try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) {
+ pemWriter.writeObject(new PemObject("CERTIFICATE", der));
+ } catch (IOException e) {
+ throw new IllegalStateException("cannot write the certificate as PEM", e);
+ }
+ return writer.toString();
+ }
+
+ /**
+ * A PEM certificate as base64, which is how the service returns one.
+ *
+ * @param pem the certificate in PEM
+ * @return the base64 of the PEM
+ */
+ public static String pemBase64(String pem) {
+ return Base64.getEncoder().encodeToString(pem.getBytes(StandardCharsets.US_ASCII));
+ }
+
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
index 374ee9c352..6db226f350 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
@@ -84,6 +84,34 @@ public final class Ciphers {
return block(AESEngine.newInstance(), false, block16, key);
}
+ /**
+ * Widen a two-key (sixteen-byte) Triple DES key to the three-key form, K1||K2 to
+ * K1||K2||K1.
+ *
+ *
The cipher takes the three keys K1||K2||K1, which is what the two-key form means,
+ * and TR-31 derives a type B block's keys from the widened form, so the derivation and
+ * the cipher have to be on the same key. A three-key key is returned as it is.
+ *
+ * @param key the sixteen- or twenty-four-byte key
+ * @return the twenty-four-byte key
+ */
+ public static byte[] widenTdesKey(byte[] key) {
+ if (key == null) {
+ throw new IllegalArgumentException("key is required");
+ }
+ if (key.length == 24) {
+ return key;
+ }
+ if (key.length != 16) {
+ throw new IllegalArgumentException(
+ "TDES key must be 16 or 24 bytes, got " + key.length);
+ }
+ byte[] out = new byte[24];
+ System.arraycopy(key, 0, out, 0, 16);
+ System.arraycopy(key, 0, out, 16, 8);
+ return out;
+ }
+
/**
* The Triple DES encryption of a block under a two-key key, in ECB mode.
*
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java
new file mode 100644
index 0000000000..e23a39dfd0
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/ConcatKdf.java
@@ -0,0 +1,112 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import org.bouncycastle.crypto.Digest;
+import org.bouncycastle.crypto.digests.SHA256Digest;
+import org.bouncycastle.crypto.digests.SHA384Digest;
+import org.bouncycastle.crypto.digests.SHA512Digest;
+
+import java.util.Arrays;
+
+/**
+ * The NIST SP 800-56A concatenation KDF, as the service applies it.
+ *
+ *
It is the single-step KDF of SP 800-56A with the counter, the shared
+ * secret and the shared information concatenated in that order:
+ *
+ *
+ * K = H(counter || Z || OtherInfo) for counter = 1, 2, ... truncated to length
+ *
+ *
+ * The other information is what binds the derived key to the two parties and
+ * to the context, so the same shared secret derived under different shared
+ * information gives a different key.
+ */
+public final class ConcatKdf {
+
+ private ConcatKdf() {
+ }
+
+ /**
+ * Derive key material from a shared secret.
+ *
+ * @param hash the digest algorithm: {@code SHA-256}, {@code SHA-384} or
+ * {@code SHA-512}
+ * @param secret the shared secret
+ * @param otherInfo the shared information
+ * @param length how many bytes to derive
+ * @return the derived key
+ */
+ public static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length) {
+ return derive(hash, secret, otherInfo, length, true);
+ }
+
+ /**
+ * The ANSI X9.63 key derivation.
+ *
+ *
The same construction as the SP 800-108 concatenation KDF, but with
+ * the shared secret and the counter the other way round:
+ *
+ *
+ * K = H(Z || counter || OtherInfo)
+ *
+ *
+ * So the two derivations over the same secret give different keys, and
+ * a caller has to say which one it means.
+ */
+ public static byte[] deriveX963(String hash, byte[] secret, byte[] otherInfo, int length) {
+ return derive(hash, secret, otherInfo, length, false);
+ }
+
+ private static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length,
+ boolean counterFirst) {
+ if (length <= 0) {
+ throw new IllegalArgumentException("the derived length must be positive");
+ }
+ Digest digest = digestFor(hash);
+ int hashBytes = digest.getDigestSize();
+ int reps = (length + hashBytes - 1) / hashBytes;
+ byte[] out = new byte[reps * hashBytes];
+ byte[] block = new byte[hashBytes];
+ for (int i = 1; i <= reps; i++) {
+ digest.reset();
+ if (counterFirst) {
+ digest.update(counter(i), 0, 4);
+ digest.update(secret, 0, secret.length);
+ } else {
+ digest.update(secret, 0, secret.length);
+ digest.update(counter(i), 0, 4);
+ }
+ digest.update(otherInfo, 0, otherInfo.length);
+ digest.doFinal(block, 0);
+ System.arraycopy(block, 0, out, (i - 1) * hashBytes, hashBytes);
+ }
+ return Arrays.copyOf(out, length);
+ }
+
+ /** The four-byte big-endian counter, starting at one. */
+ private static byte[] counter(int n) {
+ return new byte[] {
+ (byte) (n >>> 24), (byte) (n >>> 16), (byte) (n >>> 8), (byte) n,
+ };
+ }
+
+ /**
+ * The digest for a wire hash name.
+ *
+ *
The service names the digests with an underscore, and the library
+ * knows them as the SHA-2 family.
+ */
+ private static Digest digestFor(String hash) {
+ if ("SHA_256".equals(hash)) {
+ return new SHA256Digest();
+ }
+ if ("SHA_384".equals(hash)) {
+ return new SHA384Digest();
+ }
+ if ("SHA_512".equals(hash)) {
+ return new SHA512Digest();
+ }
+ throw new IllegalArgumentException("unsupported digest '" + hash
+ + "' (SHA_256, SHA_384, SHA_512)");
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java
new file mode 100644
index 0000000000..92443d2119
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ecdh.java
@@ -0,0 +1,62 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
+import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
+import org.bouncycastle.crypto.agreement.ECDHBasicAgreement;
+import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
+import org.bouncycastle.crypto.params.ECPublicKeyParameters;
+import org.bouncycastle.crypto.util.PrivateKeyFactory;
+import org.bouncycastle.crypto.util.PublicKeyFactory;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.GeneralSecurityException;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+
+/**
+ * The elliptic curve key agreement the key exchange derives its shared secret with.
+ *
+ *
The keys are the ones the service holds, which are the JDK's key objects. They are
+ * turned into the library's own parameters through their encodings, which carry the curve
+ * by name, so the two parties' keys are read on the same curve rather than on two curves
+ * that happen to look alike.
+ */
+public final class Ecdh {
+
+ private Ecdh() {
+ }
+
+ /**
+ * The secret the two parties agree.
+ *
+ * @param privateKey the service's own private key
+ * @param counterpartyKey the other party's public key
+ * @return the shared secret, the x coordinate of the agreed point
+ * @throws GeneralSecurityException when the two keys are not on the same curve
+ */
+ public static byte[] agree(ECPrivateKey privateKey, ECPublicKey counterpartyKey)
+ throws GeneralSecurityException {
+ try {
+ ECPrivateKeyParameters own = (ECPrivateKeyParameters) PrivateKeyFactory
+ .createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded()));
+ ECPublicKeyParameters other = (ECPublicKeyParameters) PublicKeyFactory
+ .createKey(SubjectPublicKeyInfo.getInstance(counterpartyKey.getEncoded()));
+ ECDHBasicAgreement agreement = new ECDHBasicAgreement();
+ agreement.init(own);
+ // The agreed point's x coordinate, in as many bytes as the field is wide.
+ BigInteger x = agreement.calculateAgreement(other);
+ int size = agreement.getFieldSize();
+ byte[] raw = x.toByteArray();
+ byte[] secret = new byte[size];
+ int from = Math.max(0, raw.length - size);
+ System.arraycopy(raw, from, secret, size - (raw.length - from), raw.length - from);
+ return secret;
+ } catch (IOException | ClassCastException | IllegalArgumentException
+ | IllegalStateException e) {
+ // The library raises IllegalStateException when the two keys are on different
+ // curves, which is a refusal and not a crash.
+ throw new GeneralSecurityException("the key agreement failed: " + e.getMessage(), e);
+ }
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java
index a34baf1bef..a528af1d83 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/EmvCrypto.java
@@ -19,8 +19,8 @@ import java.util.HexFormat;
* it was sent, and the padding the service applies is the one it applies to the input it
* builds itself, which is the issuer authentication cryptogram.
*
- *
All DES is done through three-key TDES rather than a single-DES provider:
- * single DES is expressed as TDES with K||K||K.
+ *
Each cipher says which one it uses: the retail MAC is single DES, and the
+ * key derivations are two-key TDES, which the cipher takes as K1||K2||K1.
*
*
The full PAN flows into master key derivation, because the derivation is
* defined over the whole of it.
@@ -94,11 +94,12 @@ public final class EmvCrypto {
}
/**
- * ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key.
+ * The retail MAC over data padded with the given ISO 9797-1 method.
*
- *
This is single-DES chaining, not three-key TDES. The key splits into
- * K1 (left 8) and K2 (right 8); each block is enciphered under K1, and a
- * single D_KR then E_KL final transform closes the tag:
+ *
This is ISO/IEC 9797-1 MAC algorithm 3 with a 16-byte key, and it is
+ * single-DES chaining, not three-key TDES. The key splits into K1 (left 8)
+ * and K2 (right 8); each block is enciphered under K1, and a single D_KR
+ * then E_KL final transform closes the tag:
*
*
* H_i = E_KL(D_i XOR H_{i-1}) for i = 1..n
@@ -108,7 +109,6 @@ public final class EmvCrypto {
* Running a 3DES transform per block instead - the obvious reading -
* produces a different MAC.
*/
- /** The retail MAC over data padded with the given ISO 9797-1 method. */
public static byte[] retailMac(byte[] key16, byte[] data, Padding padding) {
byte[] kl = slice(key16, 0, 8);
byte[] kr = slice(key16, 8, 16);
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java
new file mode 100644
index 0000000000..46e10f99ef
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/RsaOaep.java
@@ -0,0 +1,114 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import org.bouncycastle.crypto.AsymmetricBlockCipher;
+import org.bouncycastle.crypto.Digest;
+import org.bouncycastle.crypto.InvalidCipherTextException;
+import org.bouncycastle.crypto.digests.SHA256Digest;
+import org.bouncycastle.crypto.digests.SHA512Digest;
+import org.bouncycastle.crypto.encodings.OAEPEncoding;
+import org.bouncycastle.crypto.engines.RSABlindedEngine;
+import org.bouncycastle.crypto.engines.RSAEngine;
+import org.bouncycastle.crypto.params.RSAKeyParameters;
+import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
+
+import java.security.Key;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.interfaces.RSAPrivateCrtKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+
+/**
+ * RSA-OAEP, with the parameters built explicitly.
+ *
+ *
MGF1 follows the OAEP digest. The parameters are still
+ * built by hand rather than by asking for {@code OAEPWithSHA-256AndMGF1Padding},
+ * for two reasons. There is no {@code OAEPWithSHA-512AndMGF1Padding} constant,
+ * so the SHA-512 wrapping specification has to be constructed - and a spec
+ * built by copying a SHA-1 example leaves MGF1 on SHA-1 and fails with an
+ * opaque OAEP decoding error on a hex string that looks perfectly valid. And
+ * every OAEP operation in this project routes through here, so the two digests
+ * cannot drift apart again.
+ */
+public final class RsaOaep {
+
+ private RsaOaep() {
+ }
+
+ /** The OAEP digest for a wrapping specification, or null when unsupported. */
+ public static String digestFor(String wrappingSpec) {
+ if ("RSA_OAEP_SHA_256".equals(wrappingSpec) || wrappingSpec == null) {
+ return "SHA-256";
+ }
+ if ("RSA_OAEP_SHA_512".equals(wrappingSpec)) {
+ return "SHA-512";
+ }
+ return null;
+ }
+
+ /** Decrypt an OAEP-wrapped block. */
+ public static byte[] decrypt(PrivateKey key, byte[] ciphertext, String digest) {
+ return run(false, key, null, ciphertext, digest);
+ }
+
+ /** Encrypt to an OAEP-wrapped block. Used by tests and by the demo. */
+ public static byte[] encrypt(PublicKey key, byte[] plaintext, String digest) {
+ return run(true, null, key, plaintext, digest);
+ }
+
+ /**
+ * The OAEP encoding, with the requested digest for the OAEP digest and for MGF1.
+ *
+ *
The label is empty, which is what the reference implementation's
+ * {@code PSource.PSpecified.DEFAULT} means.
+ */
+ private static OAEPEncoding encoding(String digest, boolean encrypt) {
+ // The private operation is the blinded one: it decrypts what a caller brought, so its
+ // timing must not say how far the exponentiation has come. The public operation
+ // exponentiates with a public exponent, and blinding that protects nothing.
+ AsymmetricBlockCipher engine = encrypt ? new RSAEngine() : new RSABlindedEngine();
+ Digest hash = "SHA-512".equals(digest) ? new SHA512Digest() : new SHA256Digest();
+ return new OAEPEncoding(engine, hash, hash, null);
+ }
+
+ private static byte[] run(boolean encrypt, PrivateKey priv, PublicKey pub,
+ byte[] input, String digest) {
+ try {
+ OAEPEncoding oaep = encoding(digest, encrypt);
+ if (encrypt) {
+ RSAPublicKey rsa = (RSAPublicKey) pub;
+ oaep.init(true, new RSAKeyParameters(false, rsa.getModulus(), rsa.getPublicExponent()));
+ } else {
+ oaep.init(false, privateParameters((RSAPrivateKey) priv));
+ }
+ return oaep.processBlock(input, 0, input.length);
+ } catch (InvalidCipherTextException e) {
+ throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e);
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * The private key's parameters, with the CRT values when the key carries them.
+ *
+ *
The blinded engine blinds the exponentiation it is given, and it does so with the
+ * CRT values, so a key that has them is passed as they are.
+ *
+ * @param key the private key
+ * @return the parameters the engine works with
+ */
+ private static RSAKeyParameters privateParameters(RSAPrivateKey key) {
+ if (key instanceof RSAPrivateCrtKey crt) {
+ return new RSAPrivateCrtKeyParameters(crt.getModulus(), crt.getPublicExponent(),
+ crt.getPrivateExponent(), crt.getPrimeP(), crt.getPrimeQ(),
+ crt.getPrimeExponentP(), crt.getPrimeExponentQ(), crt.getCrtCoefficient());
+ }
+ return new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
+ }
+
+ /** Decrypt with a key given as the generic {@link Key} type. */
+ public static byte[] decrypt(Key key, byte[] ciphertext, String digest) {
+ return decrypt((PrivateKey) key, ciphertext, digest);
+ }
+}
diff --git a/src/main/resources/aws/payment-cryptography-data-request-shapes.json b/src/main/resources/aws/payment-cryptography-data-request-shapes.json
index 458680d7f9..42c35064ea 100644
--- a/src/main/resources/aws/payment-cryptography-data-request-shapes.json
+++ b/src/main/resources/aws/payment-cryptography-data-request-shapes.json
@@ -4,19 +4,21 @@
"botocore": "botocore 1.43.118 (installed package)"
},
"operations": {
- "EncryptData": "EncryptDataInput",
"DecryptData": "DecryptDataInput",
- "ReEncryptData": "ReEncryptDataInput",
- "GenerateMac": "GenerateMacInput",
- "VerifyMac": "VerifyMacInput",
- "GeneratePinData": "GeneratePinDataInput",
- "VerifyPinData": "VerifyPinDataInput",
- "TranslatePinData": "TranslatePinDataInput",
- "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput",
- "GenerateCardValidationData": "GenerateCardValidationDataInput",
- "VerifyCardValidationData": "VerifyCardValidationDataInput",
+ "EncryptData": "EncryptDataInput",
+ "GenerateAs2805KekValidation": "GenerateAs2805KekValidationInput",
"GenerateAuthRequestCryptogram": "GenerateAuthRequestCryptogramInput",
- "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput"
+ "GenerateCardValidationData": "GenerateCardValidationDataInput",
+ "GenerateMac": "GenerateMacInput",
+ "GenerateMacEmvPinChange": "GenerateMacEmvPinChangeInput",
+ "GeneratePinData": "GeneratePinDataInput",
+ "ReEncryptData": "ReEncryptDataInput",
+ "TranslateKeyMaterial": "TranslateKeyMaterialInput",
+ "TranslatePinData": "TranslatePinDataInput",
+ "VerifyAuthRequestCryptogram": "VerifyAuthRequestCryptogramInput",
+ "VerifyCardValidationData": "VerifyCardValidationDataInput",
+ "VerifyMac": "VerifyMacInput",
+ "VerifyPinData": "VerifyPinDataInput"
},
"shapes": {
"AmexAttributes": {
@@ -63,6 +65,13 @@
"max": 16,
"pattern": "[0-9a-fA-F]+"
},
+ "As2805KekValidationType": {
+ "type": "structure",
+ "members": {
+ "KekValidationRequest": "KekValidationRequest",
+ "KekValidationResponse": "KekValidationResponse"
+ }
+ },
"As2805PekDerivationAttributes": {
"type": "structure",
"required": [
@@ -74,6 +83,12 @@
"TransactionAmount": "TransactionAmountType"
}
},
+ "As2805RandomKeyMaterial": {
+ "type": "string",
+ "min": 16,
+ "max": 48,
+ "pattern": "(?:[0-9a-fA-F]{16}|[0-9a-fA-F]{32}|[0-9a-fA-F]{48})"
+ },
"AsymmetricEncryptionAttributes": {
"type": "structure",
"members": {
@@ -235,6 +250,12 @@
"Mastercard": "MasterCardAttributes"
}
},
+ "DiffieHellmanDerivationData": {
+ "type": "structure",
+ "members": {
+ "SharedInformation": "SharedInformation"
+ }
+ },
"DiscoverDynamicCardVerificationCode": {
"type": "structure",
"required": [
@@ -466,6 +487,19 @@
"OFB"
]
},
+ "GenerateAs2805KekValidationInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "KekValidationType",
+ "RandomKeySendVariantMask"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "KekValidationType": "As2805KekValidationType",
+ "RandomKeySendVariantMask": "RandomKeySendVariantMask"
+ }
+ },
"GenerateAuthRequestCryptogramInput": {
"type": "structure",
"required": [
@@ -661,6 +695,35 @@
"PinValidationData": "PinValidationDataType"
}
},
+ "IncomingDiffieHellmanTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "PrivateKeyIdentifier",
+ "CertificateAuthorityPublicKeyIdentifier",
+ "PublicKeyCertificate",
+ "DeriveKeyAlgorithm",
+ "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm",
+ "DerivationData",
+ "WrappedKeyBlock"
+ ],
+ "members": {
+ "PrivateKeyIdentifier": "KeyArnOrKeyAliasType",
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "PublicKeyCertificate": "CertificateType",
+ "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm",
+ "KeyDerivationFunction": "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm",
+ "DerivationData": "DiffieHellmanDerivationData",
+ "WrappedKeyBlock": "Tr31WrappedKeyBlock"
+ }
+ },
+ "IncomingKeyMaterial": {
+ "type": "structure",
+ "members": {
+ "DiffieHellmanTr31KeyBlock": "IncomingDiffieHellmanTr31KeyBlock"
+ }
+ },
"InitializationVectorType": {
"type": "string",
"min": 16,
@@ -687,6 +750,25 @@
"min": 4,
"max": 32
},
+ "KekValidationRequest": {
+ "type": "structure",
+ "required": [
+ "DeriveKeyAlgorithm"
+ ],
+ "members": {
+ "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm",
+ "RandomKeyMaxLength": "RandomKeyMaxLength"
+ }
+ },
+ "KekValidationResponse": {
+ "type": "structure",
+ "required": [
+ "RandomKeySend"
+ ],
+ "members": {
+ "RandomKeySend": "As2805RandomKeyMaterial"
+ }
+ },
"KeyArnOrKeyAliasType": {
"type": "string",
"min": 7,
@@ -810,6 +892,21 @@
"max": 2,
"pattern": "[0-9]+"
},
+ "OutgoingKeyMaterial": {
+ "type": "structure",
+ "members": {
+ "Tr31KeyBlock": "OutgoingTr31KeyBlock"
+ }
+ },
+ "OutgoingTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "WrappingKeyIdentifier"
+ ],
+ "members": {
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
"PaddingType": {
"type": "string",
"enum": [
@@ -904,6 +1001,21 @@
"max": 16,
"pattern": "[0-9a-fA-F]+"
},
+ "RandomKeyMaxLength": {
+ "type": "string",
+ "enum": [
+ "BYTES_8",
+ "BYTES_16",
+ "BYTES_24"
+ ]
+ },
+ "RandomKeySendVariantMask": {
+ "type": "string",
+ "enum": [
+ "VARIANT_MASK_82C0",
+ "VARIANT_MASK_82"
+ ]
+ },
"ReEncryptDataInput": {
"type": "structure",
"required": [
@@ -1109,6 +1221,18 @@
"max": 1024,
"pattern": "[0-9a-fA-F]+"
},
+ "TranslateKeyMaterialInput": {
+ "type": "structure",
+ "required": [
+ "IncomingKeyMaterial",
+ "OutgoingKeyMaterial"
+ ],
+ "members": {
+ "IncomingKeyMaterial": "IncomingKeyMaterial",
+ "OutgoingKeyMaterial": "OutgoingKeyMaterial",
+ "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm"
+ }
+ },
"TranslatePinDataInput": {
"type": "structure",
"required": [
diff --git a/src/main/resources/aws/payment-cryptography-request-shapes.json b/src/main/resources/aws/payment-cryptography-request-shapes.json
index 973325d26c..287447b9b8 100644
--- a/src/main/resources/aws/payment-cryptography-request-shapes.json
+++ b/src/main/resources/aws/payment-cryptography-request-shapes.json
@@ -4,29 +4,144 @@
"botocore": "botocore 1.43.118 (installed package)"
},
"operations": {
- "CreateKey": "CreateKeyInput",
- "GetKey": "GetKeyInput",
- "ListKeys": "ListKeysInput",
- "DeleteKey": "DeleteKeyInput",
+ "AddKeyReplicationRegions": "AddKeyReplicationRegionsInput",
+ "AssociateMpaTeam": "AssociateMpaTeamInput",
"CreateAlias": "CreateAliasInput",
- "GetAlias": "GetAliasInput",
- "ListAliases": "ListAliasesInput",
- "UpdateAlias": "UpdateAliasInput",
+ "CreateKey": "CreateKeyInput",
"DeleteAlias": "DeleteAliasInput",
+ "DeleteKey": "DeleteKeyInput",
+ "DeleteResourcePolicy": "DeleteResourcePolicyInput",
+ "DisableDefaultKeyReplicationRegions": "DisableDefaultKeyReplicationRegionsInput",
+ "DisassociateMpaTeam": "DisassociateMpaTeamInput",
+ "EnableDefaultKeyReplicationRegions": "EnableDefaultKeyReplicationRegionsInput",
+ "ExportKey": "ExportKeyInput",
+ "GetAlias": "GetAliasInput",
+ "GetCertificateSigningRequest": "GetCertificateSigningRequestInput",
+ "GetDefaultKeyReplicationRegions": "GetDefaultKeyReplicationRegionsInput",
+ "GetKey": "GetKeyInput",
+ "GetMpaTeamAssociation": "GetMpaTeamAssociationInput",
+ "GetParametersForExport": "GetParametersForExportInput",
+ "GetParametersForImport": "GetParametersForImportInput",
+ "GetPublicKeyCertificate": "GetPublicKeyCertificateInput",
+ "GetResourcePolicy": "GetResourcePolicyInput",
+ "ImportKey": "ImportKeyInput",
+ "ListAliases": "ListAliasesInput",
+ "ListKeys": "ListKeysInput",
+ "ListTagsForResource": "ListTagsForResourceInput",
+ "PutResourcePolicy": "PutResourcePolicyInput",
+ "RemoveKeyReplicationRegions": "RemoveKeyReplicationRegionsInput",
+ "RestoreKey": "RestoreKeyInput",
+ "StartKeyUsage": "StartKeyUsageInput",
+ "StopKeyUsage": "StopKeyUsageInput",
"TagResource": "TagResourceInput",
"UntagResource": "UntagResourceInput",
- "ListTagsForResource": "ListTagsForResourceInput"
+ "UpdateAlias": "UpdateAliasInput"
},
"shapes": {
+ "AddKeyReplicationRegionsInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "ReplicationRegions"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "ReplicationRegions": "Regions"
+ }
+ },
"AliasName": {
"type": "string",
"min": 7,
"max": 256,
"pattern": "alias/[a-zA-Z0-9/_-]+"
},
+ "As2805KeyVariant": {
+ "type": "string",
+ "enum": [
+ "TERMINAL_MAJOR_KEY_VARIANT_00",
+ "PIN_ENCRYPTION_KEY_VARIANT_28",
+ "MESSAGE_AUTHENTICATION_KEY_VARIANT_24",
+ "DATA_ENCRYPTION_KEY_VARIANT_22"
+ ]
+ },
+ "AssociateMpaTeamInput": {
+ "type": "structure",
+ "required": [
+ "Action",
+ "MpaTeamArn"
+ ],
+ "members": {
+ "Action": "MpaOperation",
+ "MpaTeamArn": "MpaTeamArn",
+ "RequesterComment": "MpaRequesterComment"
+ }
+ },
"Boolean": {
"type": "boolean"
},
+ "CertificateSubjectType": {
+ "type": "structure",
+ "required": [
+ "CommonName"
+ ],
+ "members": {
+ "CommonName": "CertificateSubjectTypeCommonNameString",
+ "OrganizationUnit": "CertificateSubjectTypeOrganizationUnitString",
+ "Organization": "CertificateSubjectTypeOrganizationString",
+ "City": "CertificateSubjectTypeCityString",
+ "Country": "CertificateSubjectTypeCountryString",
+ "StateOrProvince": "CertificateSubjectTypeStateOrProvinceString",
+ "EmailAddress": "CertificateSubjectTypeEmailAddressString"
+ }
+ },
+ "CertificateSubjectTypeCityString": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[^\\[;\\]<>]+"
+ },
+ "CertificateSubjectTypeCommonNameString": {
+ "type": "string",
+ "min": 1,
+ "max": 64,
+ "pattern": "[^\\[;\\]<>]+"
+ },
+ "CertificateSubjectTypeCountryString": {
+ "type": "string",
+ "min": 2,
+ "max": 2,
+ "pattern": "[A-Za-z]+"
+ },
+ "CertificateSubjectTypeEmailAddressString": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[a-zA-Z0-9.!#$%&\u2019*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*"
+ },
+ "CertificateSubjectTypeOrganizationString": {
+ "type": "string",
+ "min": 1,
+ "max": 64,
+ "pattern": "[^\\[;\\]<>]+"
+ },
+ "CertificateSubjectTypeOrganizationUnitString": {
+ "type": "string",
+ "min": 1,
+ "max": 64,
+ "pattern": "[^\\[;\\]<>]+"
+ },
+ "CertificateSubjectTypeStateOrProvinceString": {
+ "type": "string",
+ "min": 1,
+ "max": 128,
+ "pattern": "[^\\[;\\]<>]+"
+ },
+ "CertificateType": {
+ "type": "string",
+ "min": 1,
+ "max": 32768,
+ "pattern": "[^\\[;\\]<>]+"
+ },
"CreateAliasInput": {
"type": "structure",
"required": [
@@ -77,6 +192,15 @@
"min": 3,
"max": 180
},
+ "DeleteResourcePolicyInput": {
+ "type": "structure",
+ "required": [
+ "ResourceArn"
+ ],
+ "members": {
+ "ResourceArn": "ResourceArn"
+ }
+ },
"DeriveKeyUsage": {
"type": "string",
"enum": [
@@ -101,6 +225,161 @@
"TR31_V2_VISA_PIN_VERIFICATION_KEY"
]
},
+ "DiffieHellmanDerivationData": {
+ "type": "structure",
+ "members": {
+ "SharedInformation": "SharedInformation"
+ }
+ },
+ "DisableDefaultKeyReplicationRegionsInput": {
+ "type": "structure",
+ "required": [
+ "ReplicationRegions"
+ ],
+ "members": {
+ "ReplicationRegions": "Regions"
+ }
+ },
+ "DisassociateMpaTeamInput": {
+ "type": "structure",
+ "required": [
+ "Action"
+ ],
+ "members": {
+ "Action": "MpaOperation",
+ "RequesterComment": "MpaRequesterComment"
+ }
+ },
+ "EnableDefaultKeyReplicationRegionsInput": {
+ "type": "structure",
+ "required": [
+ "ReplicationRegions"
+ ],
+ "members": {
+ "ReplicationRegions": "Regions"
+ }
+ },
+ "EvenHexLengthBetween16And32": {
+ "type": "string",
+ "min": 16,
+ "max": 32,
+ "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
+ },
+ "ExportAs2805KeyCryptogram": {
+ "type": "structure",
+ "required": [
+ "WrappingKeyIdentifier",
+ "As2805KeyVariant"
+ ],
+ "members": {
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "As2805KeyVariant": "As2805KeyVariant"
+ }
+ },
+ "ExportAttributes": {
+ "type": "structure",
+ "members": {
+ "ExportDukptInitialKey": "ExportDukptInitialKey",
+ "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm"
+ }
+ },
+ "ExportDiffieHellmanTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "PrivateKeyIdentifier",
+ "CertificateAuthorityPublicKeyIdentifier",
+ "PublicKeyCertificate",
+ "DeriveKeyAlgorithm",
+ "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm",
+ "DerivationData"
+ ],
+ "members": {
+ "PrivateKeyIdentifier": "KeyArnOrKeyAliasType",
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "PublicKeyCertificate": "CertificateType",
+ "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm",
+ "KeyDerivationFunction": "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm",
+ "DerivationData": "DiffieHellmanDerivationData",
+ "KeyBlockHeaders": "KeyBlockHeaders"
+ }
+ },
+ "ExportDukptInitialKey": {
+ "type": "structure",
+ "required": [
+ "KeySerialNumber"
+ ],
+ "members": {
+ "KeySerialNumber": "HexLength20Or24"
+ }
+ },
+ "ExportKeyCryptogram": {
+ "type": "structure",
+ "required": [
+ "CertificateAuthorityPublicKeyIdentifier",
+ "WrappingKeyCertificate"
+ ],
+ "members": {
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "WrappingKeyCertificate": "CertificateType",
+ "WrappingSpec": "WrappingKeySpec"
+ }
+ },
+ "ExportKeyInput": {
+ "type": "structure",
+ "required": [
+ "KeyMaterial",
+ "ExportKeyIdentifier"
+ ],
+ "members": {
+ "KeyMaterial": "ExportKeyMaterial",
+ "ExportKeyIdentifier": "KeyArnOrKeyAliasType",
+ "ExportAttributes": "ExportAttributes"
+ }
+ },
+ "ExportKeyMaterial": {
+ "type": "structure",
+ "members": {
+ "Tr31KeyBlock": "ExportTr31KeyBlock",
+ "Tr34KeyBlock": "ExportTr34KeyBlock",
+ "KeyCryptogram": "ExportKeyCryptogram",
+ "DiffieHellmanTr31KeyBlock": "ExportDiffieHellmanTr31KeyBlock",
+ "As2805KeyCryptogram": "ExportAs2805KeyCryptogram"
+ }
+ },
+ "ExportTokenId": {
+ "type": "string",
+ "pattern": "(export-token-[0-9a-zA-Z]{16,64})?"
+ },
+ "ExportTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "WrappingKeyIdentifier"
+ ],
+ "members": {
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "KeyBlockHeaders": "KeyBlockHeaders"
+ }
+ },
+ "ExportTr34KeyBlock": {
+ "type": "structure",
+ "required": [
+ "CertificateAuthorityPublicKeyIdentifier",
+ "WrappingKeyCertificate",
+ "KeyBlockFormat"
+ ],
+ "members": {
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "WrappingKeyCertificate": "CertificateType",
+ "ExportToken": "ExportTokenId",
+ "SigningKeyIdentifier": "KeyArnOrKeyAliasType",
+ "SigningKeyCertificate": "CertificateType",
+ "KeyBlockFormat": "Tr34KeyBlockFormat",
+ "RandomNonce": "EvenHexLengthBetween16And32",
+ "KeyBlockHeaders": "KeyBlockHeaders"
+ }
+ },
"GetAliasInput": {
"type": "structure",
"required": [
@@ -110,6 +389,23 @@
"AliasName": "AliasName"
}
},
+ "GetCertificateSigningRequestInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "SigningAlgorithm",
+ "CertificateSubject"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "SigningAlgorithm": "SigningAlgorithmType",
+ "CertificateSubject": "CertificateSubjectType"
+ }
+ },
+ "GetDefaultKeyReplicationRegionsInput": {
+ "type": "structure",
+ "members": {}
+ },
"GetKeyInput": {
"type": "structure",
"required": [
@@ -119,6 +415,181 @@
"KeyIdentifier": "KeyArnOrKeyAliasType"
}
},
+ "GetMpaTeamAssociationInput": {
+ "type": "structure",
+ "required": [
+ "Action"
+ ],
+ "members": {
+ "Action": "MpaOperation"
+ }
+ },
+ "GetParametersForExportInput": {
+ "type": "structure",
+ "required": [
+ "KeyMaterialType",
+ "SigningKeyAlgorithm"
+ ],
+ "members": {
+ "KeyMaterialType": "KeyMaterialType",
+ "SigningKeyAlgorithm": "KeyAlgorithm",
+ "ReuseLastGeneratedToken": "Boolean"
+ }
+ },
+ "GetParametersForImportInput": {
+ "type": "structure",
+ "required": [
+ "KeyMaterialType",
+ "WrappingKeyAlgorithm"
+ ],
+ "members": {
+ "KeyMaterialType": "KeyMaterialType",
+ "WrappingKeyAlgorithm": "KeyAlgorithm",
+ "ReuseLastGeneratedToken": "Boolean"
+ }
+ },
+ "GetPublicKeyCertificateInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
+ "GetResourcePolicyInput": {
+ "type": "structure",
+ "required": [
+ "ResourceArn"
+ ],
+ "members": {
+ "ResourceArn": "ResourceArn"
+ }
+ },
+ "HexLength20Or24": {
+ "type": "string",
+ "min": 20,
+ "max": 24,
+ "pattern": "[0-9A-F]{20}$|^[0-9A-F]{24}"
+ },
+ "ImportAs2805KeyCryptogram": {
+ "type": "structure",
+ "required": [
+ "As2805KeyVariant",
+ "KeyModesOfUse",
+ "KeyAlgorithm",
+ "Exportable",
+ "WrappingKeyIdentifier",
+ "WrappedKeyCryptogram"
+ ],
+ "members": {
+ "As2805KeyVariant": "As2805KeyVariant",
+ "KeyModesOfUse": "KeyModesOfUse",
+ "KeyAlgorithm": "KeyAlgorithm",
+ "Exportable": "Boolean",
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "WrappedKeyCryptogram": "WrappedKeyCryptogram"
+ }
+ },
+ "ImportDiffieHellmanTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "PrivateKeyIdentifier",
+ "CertificateAuthorityPublicKeyIdentifier",
+ "PublicKeyCertificate",
+ "DeriveKeyAlgorithm",
+ "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm",
+ "DerivationData",
+ "WrappedKeyBlock"
+ ],
+ "members": {
+ "PrivateKeyIdentifier": "KeyArnOrKeyAliasType",
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "PublicKeyCertificate": "CertificateType",
+ "DeriveKeyAlgorithm": "SymmetricKeyAlgorithm",
+ "KeyDerivationFunction": "KeyDerivationFunction",
+ "KeyDerivationHashAlgorithm": "KeyDerivationHashAlgorithm",
+ "DerivationData": "DiffieHellmanDerivationData",
+ "WrappedKeyBlock": "Tr31WrappedKeyBlock"
+ }
+ },
+ "ImportKeyCryptogram": {
+ "type": "structure",
+ "required": [
+ "KeyAttributes",
+ "Exportable",
+ "WrappedKeyCryptogram",
+ "ImportToken"
+ ],
+ "members": {
+ "KeyAttributes": "KeyAttributes",
+ "Exportable": "Boolean",
+ "WrappedKeyCryptogram": "WrappedKeyCryptogram",
+ "ImportToken": "ImportTokenId",
+ "WrappingSpec": "WrappingKeySpec"
+ }
+ },
+ "ImportKeyInput": {
+ "type": "structure",
+ "required": [
+ "KeyMaterial"
+ ],
+ "members": {
+ "KeyMaterial": "ImportKeyMaterial",
+ "KeyCheckValueAlgorithm": "KeyCheckValueAlgorithm",
+ "Enabled": "Boolean",
+ "Tags": "Tags",
+ "ReplicationRegions": "Regions",
+ "RequesterComment": "MpaRequesterComment"
+ }
+ },
+ "ImportKeyMaterial": {
+ "type": "structure",
+ "members": {
+ "RootCertificatePublicKey": "RootCertificatePublicKey",
+ "TrustedCertificatePublicKey": "TrustedCertificatePublicKey",
+ "Tr31KeyBlock": "ImportTr31KeyBlock",
+ "Tr34KeyBlock": "ImportTr34KeyBlock",
+ "KeyCryptogram": "ImportKeyCryptogram",
+ "DiffieHellmanTr31KeyBlock": "ImportDiffieHellmanTr31KeyBlock",
+ "As2805KeyCryptogram": "ImportAs2805KeyCryptogram"
+ }
+ },
+ "ImportTokenId": {
+ "type": "string",
+ "pattern": "(import-token-[0-9a-zA-Z]{16,64})?"
+ },
+ "ImportTr31KeyBlock": {
+ "type": "structure",
+ "required": [
+ "WrappingKeyIdentifier",
+ "WrappedKeyBlock"
+ ],
+ "members": {
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "WrappedKeyBlock": "Tr31WrappedKeyBlock"
+ }
+ },
+ "ImportTr34KeyBlock": {
+ "type": "structure",
+ "required": [
+ "CertificateAuthorityPublicKeyIdentifier",
+ "SigningKeyCertificate",
+ "WrappedKeyBlock",
+ "KeyBlockFormat"
+ ],
+ "members": {
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType",
+ "SigningKeyCertificate": "CertificateType",
+ "ImportToken": "ImportTokenId",
+ "WrappingKeyIdentifier": "KeyArnOrKeyAliasType",
+ "WrappingKeyCertificate": "CertificateType",
+ "WrappedKeyBlock": "Tr34WrappedKeyBlock",
+ "KeyBlockFormat": "Tr34KeyBlockFormat",
+ "RandomNonce": "EvenHexLengthBetween16And32"
+ }
+ },
"KeyAlgorithm": {
"type": "string",
"enum": [
@@ -166,6 +637,15 @@
"KeyModesOfUse": "KeyModesOfUse"
}
},
+ "KeyBlockHeaders": {
+ "type": "structure",
+ "members": {
+ "KeyModesOfUse": "KeyModesOfUse",
+ "KeyExportability": "KeyExportability",
+ "KeyVersion": "KeyVersion",
+ "OptionalBlocks": "OptionalBlocks"
+ }
+ },
"KeyCheckValueAlgorithm": {
"type": "string",
"enum": [
@@ -184,6 +664,39 @@
"PUBLIC_KEY"
]
},
+ "KeyDerivationFunction": {
+ "type": "string",
+ "enum": [
+ "NIST_SP800",
+ "ANSI_X963"
+ ]
+ },
+ "KeyDerivationHashAlgorithm": {
+ "type": "string",
+ "enum": [
+ "SHA_256",
+ "SHA_384",
+ "SHA_512"
+ ]
+ },
+ "KeyExportability": {
+ "type": "string",
+ "enum": [
+ "EXPORTABLE",
+ "NON_EXPORTABLE",
+ "SENSITIVE"
+ ]
+ },
+ "KeyMaterialType": {
+ "type": "string",
+ "enum": [
+ "TR34_KEY_BLOCK",
+ "TR31_KEY_BLOCK",
+ "ROOT_PUBLIC_KEY_CERTIFICATE",
+ "TRUSTED_PUBLIC_KEY_CERTIFICATE",
+ "KEY_CRYPTOGRAM"
+ ]
+ },
"KeyModesOfUse": {
"type": "structure",
"members": {
@@ -236,6 +749,12 @@
"TR31_K2_TR34_ASYMMETRIC_KEY"
]
},
+ "KeyVersion": {
+ "type": "string",
+ "min": 2,
+ "max": 2,
+ "pattern": "[0-9A-Z]{2}+"
+ },
"ListAliasesInput": {
"type": "structure",
"members": {
@@ -268,14 +787,59 @@
"min": 1,
"max": 100
},
+ "MpaOperation": {
+ "type": "string",
+ "enum": [
+ "IMPORT_ROOT_PUBLIC_KEY_CERTIFICATE"
+ ]
+ },
+ "MpaRequesterComment": {
+ "type": "string",
+ "min": 0,
+ "max": 200
+ },
+ "MpaTeamArn": {
+ "type": "string",
+ "min": 20,
+ "max": 2048,
+ "pattern": "arn:aws(-[^:]+)?:mpa:[a-z0-9-]{1,20}:[0-9]{12}:approval-team/[a-zA-Z0-9._-]+"
+ },
"NextToken": {
"type": "string",
"min": 1,
"max": 8192
},
+ "OptionalBlockId": {
+ "type": "string",
+ "min": 2,
+ "max": 2,
+ "pattern": "[0-9A-Z]{2}+"
+ },
+ "OptionalBlockValue": {
+ "type": "string",
+ "min": 1,
+ "max": 108,
+ "pattern": "[0-9a-zA-Z]+"
+ },
+ "OptionalBlocks": {
+ "type": "map",
+ "key": "OptionalBlockId",
+ "value": "OptionalBlockValue"
+ },
"PrimitiveBoolean": {
"type": "boolean"
},
+ "PutResourcePolicyInput": {
+ "type": "structure",
+ "required": [
+ "ResourceArn",
+ "Policy"
+ ],
+ "members": {
+ "ResourceArn": "ResourceArn",
+ "Policy": "ResourcePolicy"
+ }
+ },
"Region": {
"type": "string",
"pattern": "[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+"
@@ -284,12 +848,96 @@
"type": "list",
"member": "Region"
},
+ "RemoveKeyReplicationRegionsInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier",
+ "ReplicationRegions"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType",
+ "ReplicationRegions": "Regions"
+ }
+ },
"ResourceArn": {
"type": "string",
"min": 70,
"max": 150,
"pattern": "arn:aws[a-z0-9-]*:payment-cryptography:[a-z]{2,4}(-[a-z]{1,16})+-[0-9]+:[0-9]{12}:key/[0-9a-zA-Z]{16,64}"
},
+ "ResourcePolicy": {
+ "type": "string",
+ "min": 1,
+ "max": 20480,
+ "pattern": "[\\u0009\\u000A\\u000D\\u0020-\\u00FF]+"
+ },
+ "RestoreKeyInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
+ "RootCertificatePublicKey": {
+ "type": "structure",
+ "required": [
+ "KeyAttributes",
+ "PublicKeyCertificate"
+ ],
+ "members": {
+ "KeyAttributes": "KeyAttributes",
+ "PublicKeyCertificate": "CertificateType"
+ }
+ },
+ "SharedInformation": {
+ "type": "string",
+ "min": 2,
+ "max": 2048,
+ "pattern": "(?:[0-9a-fA-F][0-9a-fA-F])+"
+ },
+ "SigningAlgorithmType": {
+ "type": "string",
+ "enum": [
+ "SHA224",
+ "SHA256",
+ "SHA384",
+ "SHA512"
+ ]
+ },
+ "StartKeyUsageInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
+ "StopKeyUsageInput": {
+ "type": "structure",
+ "required": [
+ "KeyIdentifier"
+ ],
+ "members": {
+ "KeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
+ "SymmetricKeyAlgorithm": {
+ "type": "string",
+ "enum": [
+ "TDES_2KEY",
+ "TDES_3KEY",
+ "AES_128",
+ "AES_192",
+ "AES_256",
+ "HMAC_SHA256",
+ "HMAC_SHA384",
+ "HMAC_SHA512",
+ "HMAC_SHA224"
+ ]
+ },
"Tag": {
"type": "structure",
"required": [
@@ -334,6 +982,37 @@
"max": 200,
"member": "Tag"
},
+ "Tr31WrappedKeyBlock": {
+ "type": "string",
+ "min": 56,
+ "max": 9984,
+ "pattern": "[0-9a-zA-Z]+"
+ },
+ "Tr34KeyBlockFormat": {
+ "type": "string",
+ "enum": [
+ "X9_TR34_2012"
+ ]
+ },
+ "Tr34WrappedKeyBlock": {
+ "type": "string",
+ "min": 2,
+ "max": 4096,
+ "pattern": "[0-9A-F]+"
+ },
+ "TrustedCertificatePublicKey": {
+ "type": "structure",
+ "required": [
+ "KeyAttributes",
+ "PublicKeyCertificate",
+ "CertificateAuthorityPublicKeyIdentifier"
+ ],
+ "members": {
+ "KeyAttributes": "KeyAttributes",
+ "PublicKeyCertificate": "CertificateType",
+ "CertificateAuthorityPublicKeyIdentifier": "KeyArnOrKeyAliasType"
+ }
+ },
"UntagResourceInput": {
"type": "structure",
"required": [
@@ -354,6 +1033,19 @@
"AliasName": "AliasName",
"KeyArn": "KeyArn"
}
+ },
+ "WrappedKeyCryptogram": {
+ "type": "string",
+ "min": 16,
+ "max": 4096,
+ "pattern": "[0-9A-F]+"
+ },
+ "WrappingKeySpec": {
+ "type": "string",
+ "enum": [
+ "RSA_OAEP_SHA_256",
+ "RSA_OAEP_SHA_512"
+ ]
}
}
}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java
index 1bd1ac8077..bdd098ee01 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyAuthCryptogramOperationsTest.java
@@ -146,6 +146,22 @@ class PaymentCryptographyAuthCryptogramOperationsTest {
"4111111111111111111", PSN)), HEX.formatHex(optionB));
}
+ @Test
+ void aRequestWithoutItsDerivationAttributesIsRefusedByTheModel() {
+ // The shape check settles the members the model requires, so it is the refusal that
+ // answers, and the message a caller sees is its own.
+ AwsException refused = assertThrows(AwsException.class,
+ () -> cryptogram.generate(PaymentCryptographyTestFixtures.request(Map.of(
+ "KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/"
+ + "0123456789abcdef",
+ "TransactionData", TRANSACTION_DATA,
+ "MajorKeyDerivationMode", "EMV_OPTION_A")), "us-east-1"));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("failed to satisfy constraint"), refused.getMessage());
+ assertTrue(refused.getMessage().contains("SessionKeyDerivationAttributes"), refused.getMessage());
+ }
+
@Test
void theEmv41DerivationIsRefusedRatherThanApproximated() {
PaymentCryptographyKey key = PaymentCryptographyTestFixtures.createKey(service, "TDES_2KEY", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "DeriveKey");
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
index 3d72c4a75c..8136534a18 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
@@ -65,6 +65,12 @@ class PaymentCryptographyIntegrationTest {
"KeyModesOfUse":{"Encrypt":true,"Decrypt":true}},
"Exportable":true}""";
+ private static final String CREATE_KEY_PAIR = """
+ {"KeyAttributes":{"KeyAlgorithm":"RSA_2048","KeyClass":"ASYMMETRIC_KEY_PAIR",
+ "KeyUsage":"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
+ "KeyModesOfUse":{"Sign":true,"Verify":true}},
+ "Exportable":true}""";
+
@Test
void aKeyIsCreatedAndReadBack() {
String arn = call("CreateKey", CREATE_KEY)
@@ -101,6 +107,276 @@ class PaymentCryptographyIntegrationTest {
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
}
+ @Test
+ void anInitialKeyLeavesUnderTheBaseKeyItIsDerivedFrom() {
+ // The export names the key that leaves and the attributes that say which key of it
+ // leaves: the initial key is derived from the base key and is not the base key.
+ // The base derivation key is a double-length Triple DES key, which is what the
+ // derivation is defined over.
+ String base = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_B0_BASE_DERIVATION_KEY\","
+ + "\"KeyModesOfUse\":{\"DeriveKey\":true}},"
+ + "\"Exportable\":true}")
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ String protection = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\","
+ + "\"KeyUsage\":\"TR31_K1_KEY_BLOCK_PROTECTION_KEY\","
+ + "\"KeyModesOfUse\":{\"Wrap\":true,\"Unwrap\":true}},"
+ + "\"Exportable\":true}")
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ call("ExportKey", """
+ {"ExportKeyIdentifier":"%s",
+ "ExportAttributes":{"ExportDukptInitialKey":
+ {"KeySerialNumber":"12345678900000000001"}},
+ "KeyMaterial":{"Tr31KeyBlock":{"WrappingKeyIdentifier":"%s"}}}
+ """.formatted(base, protection))
+ .then().statusCode(200)
+ .body("WrappedKey.WrappedKeyMaterialFormat", equalTo("TR31_KEY_BLOCK"))
+ .body("WrappedKey.WrappingKeyArn", equalTo(protection));
+ }
+
+ @Test
+ void theImportParametersAreServedOverTheWire() {
+ call("GetParametersForImport", """
+ {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"}
+ """)
+ .then().statusCode(200)
+ .body("ImportToken", matchesPattern("import-token-[0-9a-zA-Z]{16,64}"))
+ .body("WrappingKeyAlgorithm", equalTo("RSA_2048"))
+ .body("WrappingKeyCertificate", notNullValue())
+ .body("WrappingKeyCertificateChain", notNullValue())
+ .body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0));
+ }
+
+ @Test
+ void theParametersCanBeReusedOverTheWire() {
+ // A caller that asks for the last parameters gets them, token and certificate alike.
+ String first = call("GetParametersForImport", """
+ {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048"}
+ """)
+ .then().statusCode(200)
+ .extract().path("ImportToken");
+
+ call("GetParametersForImport", """
+ {"KeyMaterialType":"KEY_CRYPTOGRAM","WrappingKeyAlgorithm":"RSA_2048",
+ "ReuseLastGeneratedToken":true}
+ """)
+ .then().statusCode(200)
+ .body("ImportToken", equalTo(first));
+ }
+
+ @Test
+ void theExportParametersAreServedOverTheWire() {
+ call("GetParametersForExport", """
+ {"KeyMaterialType":"TR34_KEY_BLOCK","SigningKeyAlgorithm":"RSA_2048"}
+ """)
+ .then().statusCode(200)
+ .body("ExportToken", matchesPattern("export-token-[0-9a-zA-Z]{16,64}"))
+ .body("SigningKeyAlgorithm", equalTo("RSA_2048"))
+ .body("SigningKeyCertificate", notNullValue())
+ .body("SigningKeyCertificateChain", notNullValue())
+ .body("ParametersValidUntilTimestamp", greaterThanOrEqualTo(0));
+ }
+
+ @Test
+ void anImportedKeyCarriesTheEnabledFlagAndTheTags() {
+ // The import names the key's state and its tags, and the key comes back that way.
+ String wrapping = call("CreateKey", """
+ {"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY",
+ "KeyUsage":"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
+ "KeyModesOfUse":{"Wrap":true,"Unwrap":true}},
+ "Exportable":true}
+ """)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ String block = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn
+ + "\",\"KeyMaterial\":{\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\""
+ + wrapping + "\"}}}")
+ .then().statusCode(200)
+ .extract().path("WrappedKey.KeyMaterial");
+
+ String importedArn = call("ImportKey", "{\"KeyMaterial\":{\"Tr31KeyBlock\":{"
+ + "\"WrappingKeyIdentifier\":\"" + wrapping + "\",\"WrappedKeyBlock\":\"" + block
+ + "\"}},\"Enabled\":false,\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}")
+ .then().statusCode(200)
+ .body("Key.Enabled", equalTo(false))
+ .extract().path("Key.KeyArn");
+
+ // The key's answer carries no tags, so they are read the way they are read elsewhere.
+ call("ListTagsForResource", "{\"ResourceArn\":\"" + importedArn + "\"}")
+ .then().statusCode(200)
+ .body("Tags[0].Key", equalTo("Origin"))
+ .body("Tags[0].Value", equalTo("PRIMARY"));
+ }
+
+ @Test
+ void aRequestNamingTwoFormsIsRefused() {
+ // The union holds one form per request, and naming two is not naming one.
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ + "\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\"" + arn + "\"},"
+ + "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn
+ + "\",\"WrappingKeyCertificate\":\"x\"}}}")
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"));
+ }
+
+ @Test
+ void aRequestNamingAFormTheServiceDoesNotServeIsRefused() {
+ // The TR-34 form is one the model has and this service does not make.
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ + "\"Tr34KeyBlock\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn
+ + "\",\"WrappingKeyCertificate\":\"x\",\"KeyBlockFormat\":\"X9_TR34_2012\"}}}")
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", containsString("not a form the service exports"));
+ }
+
+ /**
+ * The shape check settles the members the model requires, so a request missing one is
+ * refused by it, before the operation does any work. The refusal a caller sees is
+ * therefore the shape check's, and the service does not repeat the check.
+ */
+ @Test
+ void theModelCheckRefusesAnExportWithoutAWrappingKeyCertificate() {
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ + "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\"}}}");
+
+ assertTheModelRefused(answer, "WrappingKeyCertificate");
+ }
+
+ @Test
+ void theModelCheckRefusesAnImportWithoutItsKeyAttributes() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
+ + "\"Exportable\":true,"
+ + "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\","
+ + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\"}}}");
+
+ assertTheModelRefused(answer, "KeyAttributes");
+ }
+
+ @Test
+ void theModelCheckRefusesAnImportWhoseKeyAttributesHaveNoUsage() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
+ + "\"Exportable\":true,"
+ + "\"WrappedKeyCryptogram\":\"" + "0".repeat(32) + "\","
+ + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\","
+ + "\"KeyAttributes\":{\"KeyClass\":\"SYMMETRIC_KEY\","
+ + "\"KeyAlgorithm\":\"AES_128\","
+ + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}}}}");
+
+ assertTheModelRefused(answer, "KeyUsage");
+ }
+
+ @Test
+ void theModelCheckRefusesAnImportOfAPublicKeyWithoutItsKeyAttributes() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"RootCertificatePublicKey\":{"
+ + "\"PublicKeyCertificate\":\"a certificate\"}}}");
+
+ assertTheModelRefused(answer, "KeyAttributes");
+ }
+
+ @Test
+ void theModelCheckRefusesAnExportWithoutItsCertificateAuthorityPublicKeyIdentifier() {
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"KeyMaterial\":{\"KeyCryptogram\":{\"WrappingKeyCertificate\":\"a certificate\"}}}");
+
+ assertTheModelRefused(answer, "CertificateAuthorityPublicKeyIdentifier");
+ }
+
+ @Test
+ void theModelCheckRefusesAnImportWhoseCryptogramIsNotHexadecimal() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"KeyCryptogram\":{"
+ + "\"Exportable\":true,"
+ + "\"WrappedKeyCryptogram\":\"not hexadecimal at all\","
+ + "\"ImportToken\":\"import-token-" + "0".repeat(24) + "\","
+ + "\"KeyAttributes\":" + keyAttributes() + "}}}");
+
+ assertTheModelRefused(answer, "WrappedKeyCryptogram");
+ }
+
+ @Test
+ void theModelCheckRefusesACryptogramWithAWrappingSpecItDoesNotName() {
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"KeyMaterial\":{\"KeyCryptogram\":{"
+ + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"WrappingKeyCertificate\":\"a certificate\","
+ + "\"WrappingSpec\":\"RSA_OAEP_SHA_1\"}}}");
+
+ assertTheModelRefused(answer, "WrappingSpec");
+ }
+
+ @Test
+ void theModelCheckRefusesAnAgreementWithADerivationFunctionItDoesNotName() {
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{"
+ + "\"PrivateKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"PublicKeyCertificate\":\"a certificate\","
+ + "\"DeriveKeyAlgorithm\":\"AES_128\","
+ + "\"KeyDerivationFunction\":\"NIST_SP800_X\","
+ + "\"KeyDerivationHashAlgorithm\":\"SHA_256\","
+ + "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}");
+
+ assertTheModelRefused(answer, "KeyDerivationFunction");
+ }
+
+ @Test
+ void theModelCheckRefusesAnAgreementWithADerivationHashItDoesNotName() {
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"KeyMaterial\":{\"DiffieHellmanTr31KeyBlock\":{"
+ + "\"PrivateKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"PublicKeyCertificate\":\"a certificate\","
+ + "\"DeriveKeyAlgorithm\":\"AES_128\","
+ + "\"KeyDerivationFunction\":\"NIST_SP800\","
+ + "\"KeyDerivationHashAlgorithm\":\"SHA_224\","
+ + "\"DerivationData\":{\"SharedInformation\":\"00112233\"}}}}");
+
+ assertTheModelRefused(answer, "KeyDerivationHashAlgorithm");
+ }
+
+ /** The ARN of a key the request may name. */
+ private static String keyArn() {
+ return call("CreateKey", CREATE_KEY).then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ }
+
+ /** The key attributes of a symmetric key, with every member the model requires. */
+ private static String keyAttributes() {
+ return "{\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyAlgorithm\":\"AES_128\","
+ + "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}}";
+ }
+
+ /**
+ * The refusal a caller sees when a request is missing a member the model requires: the
+ * shape check's, because the shape check runs before the operation does.
+ */
+ private static void assertTheModelRefused(Response answer, String member) {
+ answer.then().statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", containsString("failed to satisfy constraint"))
+ .body("message", containsString(member));
+ }
+
@Test
void aKeyThatAsksForACheckValueOfAnotherKindIsRefused() {
// The kind follows the algorithm, so a request that names another is refused
@@ -206,20 +482,68 @@ class PaymentCryptographyIntegrationTest {
.body("__type", containsString("UnknownOperationException"));
}
+ @Test
+ void anOperationTheServiceDoesNotServeIsRefusedWhateverItsBodySays() {
+ // The model names the operation and the service does not serve it, so it is refused
+ // as the unknown operation it is. The body it carries does not change that: a body
+ // that breaks the model's rules is not the answer to an operation that is not
+ // served at all.
+ call("RestoreKey", "{}")
+ .then().statusCode(400)
+ .body("__type", containsString("UnknownOperationException"));
+ call("RestoreKey", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:us-east-1:"
+ + "000000000000:key/abcdefghijklmnop\"}")
+ .then().statusCode(400)
+ .body("__type", containsString("UnknownOperationException"));
+ }
+
+ @Test
+ void theCertificateOfAKeyIsServedOverTheWire() {
+ // The certificate of an asymmetric key, with the chain that goes with it.
+ String arn = call("CreateKey", CREATE_KEY_PAIR)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + arn + "\"}")
+ .then().statusCode(200)
+ .body("KeyCertificate", notNullValue())
+ .body("KeyCertificateChain", notNullValue());
+ }
+
+ @Test
+ void theCertificateOfAKeyIsNotServedForABareKeyId() {
+ // The identifier of a key is its ARN, an alias ARN or an alias name, and the model's
+ // pattern is what settles it, the same as for the other operations that take one. A
+ // bare id names no key, so it is refused the way GetKey refuses it.
+ String arn = call("CreateKey", CREATE_KEY_PAIR).then().statusCode(200)
+ .extract().path("Key.KeyArn");
+ String id = arn.substring(arn.lastIndexOf('/') + 1);
+
+ call("GetPublicKeyCertificate", "{\"KeyIdentifier\":\"" + id + "\"}")
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
/**
* A key is created with the usage and the modes of use the reference
* requires, and a request without either of them is refused.
*/
@Test
void aKeyWithoutItsUsageOrItsModesIsRefused() {
- call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
- + "\"KeyModesOfUse\":{\"Encrypt\":true}},\"Exportable\":true}")
- .then().statusCode(400)
- .body("__type", containsString("ValidationException"));
- call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
- + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}")
- .then().statusCode(400)
- .body("__type", containsString("ValidationException"));
+ // The shape check settles the members the attributes must carry, so it is the refusal
+ // that answers, and the message a caller sees is its own.
+ assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyModesOfUse\":{\"Encrypt\":true}},"
+ + "\"Exportable\":true}"), "KeyUsage");
+ assertTheModelRefused(call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ + "\"KeyClass\":\"SYMMETRIC_KEY\","
+ + "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\"},\"Exportable\":true}"),
+ "KeyModesOfUse");
+ }
+
+ @Test
+ void aKeyWithoutItsAttributesIsRefused() {
+ assertTheModelRefused(call("CreateKey", "{\"Exportable\":true}"), "KeyAttributes");
}
/**
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java
new file mode 100644
index 0000000000..30550e09f7
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java
@@ -0,0 +1,964 @@
+package io.floci.aws.services.paymentcryptography;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.floci.aws.core.common.AwsException;
+import io.floci.aws.core.common.RegionResolver;
+import io.floci.aws.core.storage.InMemoryStorage;
+import io.floci.aws.services.acm.CertificateGenerator;
+import io.floci.aws.services.paymentcryptography.crypto.Certificates;
+import io.floci.aws.services.paymentcryptography.crypto.CertificatesTest;
+import io.floci.aws.services.paymentcryptography.crypto.RsaOaep;
+import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
+import io.floci.aws.testing.ManualClock;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import java.security.KeyPair;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The certificate-based half of the key exchange.
+ *
+ *
A key that leaves the service under a certificate is wrapped for the receiver, and the
+ * certificates the two sides exchange are the ones the service mints for the occasion. A key
+ * that comes back is checked against the authority that signed the certificate, and against
+ * the signature the sender made over it.
+ */
+class PaymentCryptographyKeyExchangeTest {
+
+ private PaymentCryptographyService service;
+
+ /** The key a key block is wrapped under. */
+ private PaymentCryptographyKey protection;
+
+ @BeforeEach
+ void setUp() {
+ service = new PaymentCryptographyService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"));
+ protection = service.createKey("us-east-1",
+ Map.of("KeyAlgorithm", "AES_256",
+ "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY",
+ "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true)),
+ Map.of("Wrap", true, "Unwrap", true), true, true, Map.of());
+ }
+
+
+ @Test
+ void theImportParametersCarryACertificateAndAToken() {
+ Map parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+
+ assertNotNull(parameters.get("ImportToken"));
+ assertNotNull(parameters.get("WrappingKeyCertificate"));
+ assertNotNull(parameters.get("WrappingKeyCertificateChain"));
+ assertEquals("RSA_2048", parameters.get("WrappingKeyAlgorithm"));
+ assertNotNull(parameters.get("ParametersValidUntilTimestamp"));
+ assertNotNull(Certificates
+ .parseCertificate((String) parameters.get("WrappingKeyCertificate")));
+ }
+
+ @Test
+ void theExportParametersCarryACertificateAndAToken() {
+ Map parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false);
+
+ assertNotNull(parameters.get("ExportToken"));
+ assertNotNull(parameters.get("SigningKeyCertificate"));
+ assertNotNull(parameters.get("SigningKeyCertificateChain"));
+ assertEquals("RSA_2048", parameters.get("SigningKeyAlgorithm"));
+ assertNotNull(parameters.get("ParametersValidUntilTimestamp"));
+ assertNotNull(Certificates
+ .parseCertificate((String) parameters.get("SigningKeyCertificate")));
+ }
+
+ @Test
+ void eachTokenIsNamedForTheOperationThatIssuedIt() {
+ String importToken = (String) service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false)
+ .get("ImportToken");
+ String exportToken = (String) service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048", false)
+ .get("ExportToken");
+
+ assertTrue(importToken.startsWith("import-token-"), importToken);
+ assertTrue(exportToken.startsWith("export-token-"), exportToken);
+ }
+
+ @Test
+ void aMaterialTypeThatTakesNoParametersIsRefused() {
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.parametersForImport("TR31_KEY_BLOCK", "RSA_2048", false));
+ AwsException refusedExport = assertThrows(AwsException.class,
+ () -> service.parametersForExport("KEY_CRYPTOGRAM", "RSA_2048", false));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertEquals("ValidationException", refusedExport.getErrorCode());
+ }
+
+ @Test
+ void anAlgorithmThatIsNotAKeyAlgorithmIsRefused() {
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.parametersForImport("TR34_KEY_BLOCK", "AES_256", false));
+ AwsException refusedExport = assertThrows(AwsException.class,
+ () -> service.parametersForExport("TR34_KEY_BLOCK", "AES_256", false));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertEquals("ValidationException", refusedExport.getErrorCode());
+ }
+
+
+
+
+ @Test
+ void theBlockCarriesTheHeadersTheRequestNames() {
+ // The optional blocks are in the clear and are authenticated with the cipher text, and
+ // the exportability and the version sit in the header.
+ Map material = new LinkedHashMap<>();
+ material.put("WrappingKeyIdentifier", protection.getKeyId());
+ material.put("KeyBlockHeaders", Map.of(
+ "KeyExportability", "NON_EXPORTABLE",
+ "KeyVersion", "01",
+ "OptionalBlocks", Map.of("AB", "0011")));
+
+ Map answer = service.exportKey("us-east-1",
+ createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(),
+ "Tr31KeyBlock", material, "", "");
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+
+ // The header carries the version and the exportability the request asked for.
+ assertEquals("01", block.substring(9, 11), "the version of the key");
+ assertEquals("N", block.substring(11, 12), "the exportability of the key");
+ // The optional block sits between the header and the cipher text, and its length is
+ // in hexadecimal and covers the whole block, the identifier and the length included.
+ assertEquals("AB", block.substring(16, 18), "the optional block's identifier");
+ assertEquals("08", block.substring(18, 20), "the optional block's length");
+ // The optional blocks take up a whole number of cipher blocks, so the block carries a
+ // padding block that fills the rest.
+ assertEquals("02", block.substring(12, 14), "the number of optional blocks");
+ assertEquals("PB080000", block.substring(24, 32), "the padding block");
+
+ // And the block still opens, so the optional blocks are authenticated with it.
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "WrappedKeyBlock", block), "", true, Map.of());
+ assertEquals("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", imported.getKeyUsage());
+ }
+
+ /**
+ * A key that leaves under a cryptogram comes back.
+ *
+ * The import decrypts what the caller brought under the private key the parameters
+ * issued, and that operation is blinded, so a wrong set of CRT values would decrypt to
+ * nothing and the key would not come back.
+ */
+ @Test
+ void aKeyThatLeavesUnderACryptogramComesBack() { Map importParameters = service.parametersForImport("KEY_CRYPTOGRAM",
+ "RSA_2048", false);
+
+ PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ PaymentCryptographyKey authority = createAuthority(
+ (String) importParameters.get("WrappingKeyCertificate"));
+
+ Map material = new LinkedHashMap<>();
+ material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate"));
+ material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
+ material.put("WrappingSpec", "RSA_OAEP_SHA_256");
+
+ Map answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram",
+ material, "", "");
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat"));
+
+ Map incoming = new LinkedHashMap<>();
+ incoming.put("ImportToken", importParameters.get("ImportToken"));
+ incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial"));
+ incoming.put("WrappingKeyIdentifier", authority.getKeyId());
+ incoming.put("WrappingSpec", "RSA_OAEP_SHA_256");
+ incoming.put("KeyAttributes", Map.of(
+ "KeyAlgorithm", "TDES_2KEY",
+ "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
+ "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)));
+
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming, "", true, Map.of());
+
+ assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
+ }
+
+
+
+ @Test
+ void aKeyLeavesUnderAKeyTheTwoPartiesAgreed() {
+ // The two parties agree a key with ECDH, and the key leaves in a block under it.
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
+ PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
+ Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
+ "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
+ // The counterparty's certificate is signed by the authority, which is what lets the
+ // service trust it.
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", authority.getPrivate(), "floci key-exchange CA");
+ Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
+
+ Map, ?> wrapped = (Map, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
+ "DiffieHellmanTr31KeyBlock", exchange.material(), "", "").get("WrappedKey");
+
+ assertEquals("TR31_KEY_BLOCK", wrapped.get("WrappedKeyMaterialFormat"));
+
+ // The two parties agree the key again, so the block opens under it.
+ Map incoming = new LinkedHashMap<>(exchange.material());
+ incoming.put("WrappedKeyBlock", wrapped.get("KeyMaterial"));
+ PaymentCryptographyKey imported = service.importKey("us-east-1",
+ "DiffieHellmanTr31KeyBlock", incoming, "", true, Map.of());
+
+ assertEquals(exchange.key().getKeyMaterialHex(), imported.getKeyMaterialHex());
+ assertEquals(exchange.key().getKeyUsage(), imported.getKeyUsage());
+ }
+
+ @Test
+ void aKeyLeavesUnderAKeyTheTwoPartiesAgreedCarriesTheHeadersTheRequestNames() {
+ // The block headers the request names travel with the block under the agreed key,
+ // the same as they do under a key the service holds.
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
+ PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
+ Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
+ "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", authority.getPrivate(), "floci key-exchange CA");
+ Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
+ Map material = new LinkedHashMap<>(exchange.material());
+ material.put("KeyBlockHeaders", Map.of(
+ "KeyExportability", "NON_EXPORTABLE",
+ "KeyVersion", "01",
+ "OptionalBlocks", Map.of("AB", "0011")));
+
+ Map, ?> wrapped = (Map, ?>) service.exportKey("us-east-1", exchange.key().getKeyId(),
+ "DiffieHellmanTr31KeyBlock", material, "", "").get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+
+ // The header carries the version and the exportability the request asked for, and
+ // the optional block sits between the header and the cipher text.
+ assertEquals("01", block.substring(9, 11), "the version of the key");
+ assertEquals("N", block.substring(11, 12), "the exportability of the key");
+ assertEquals("AB", block.substring(16, 18), "the optional block's identifier");
+ assertEquals("08", block.substring(18, 20), "the optional block's length");
+ }
+
+ @Test
+ void aCounterpartyCertificateTheAuthorityDidNotSignIsRefused() {
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair other = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair counterparty = PaymentCryptographyKeyPairs.ec(
+ PaymentCryptographyKeyAlgorithm.ECC_NIST_P256, random);
+ Certificates.Minted authorityCertificate = CertificatesTest.mint(authority.getPublic(),
+ "floci key-exchange CA", authority.getPrivate(), "floci key-exchange CA");
+ // Signed by somebody else, so the authority cannot vouch for it.
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", other.getPrivate(), "floci somebody else");
+ Exchange exchange = agreedExchange(authorityCertificate, counterpartyCertificate);
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", exchange.key().getKeyId(),
+ "DiffieHellmanTr31KeyBlock", exchange.material(), "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("not signed by the certificate authority"),
+ refused.getMessage());
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void anInitialKeyLeavesInsteadOfTheBaseKey(boolean baseMayLeave) {
+ // The initial key of the DUKPT derivation is derived from the base
+ // derivation key, and it is the derived key that leaves. The base key may not
+ // leave itself and still derive that initial key, which the export guide says
+ // the standards allow.
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "TDES_2KEY");
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
+ PaymentCryptographyKey base = service.createKey("us-east-1", attributes,
+ Map.of("DeriveKey", Boolean.TRUE), baseMayLeave, true, Map.of());
+
+ Map answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()), "12345678900000000001", "");
+
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+ // The header names the derived key: an initial derivation key of Triple DES, which
+ // the receiver may derive with and may export, but not as a plain working key.
+ assertEquals("B1", block.substring(5, 7), "the usage of the derived key");
+ assertEquals("T", block.substring(7, 8), "the algorithm of the derived key");
+ assertEquals("X", block.substring(8, 9), "the derived key is a derivable one");
+ assertEquals("S", block.substring(11, 12), "the derived key is a sensitive one");
+ // And the check value is the derived key's, not the base key's.
+ assertNotEquals(base.getKeyCheckValue(), wrapped.get("KeyCheckValue"));
+ }
+
+ @Test
+ void anInitialKeyCannotBeDerivedFromAnotherKey() {
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "TDES_2KEY");
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", "TR31_P0_PIN_ENCRYPTION_KEY");
+ PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()),
+ "12345678900000000001", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+
+ @Test
+ void anImportTokenWorksForEveryImportUntilItExpires() {
+ // A caller that asks for the parameters once may import several keys under them.
+ Map parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+ String token = (String) parameters.get("ImportToken");
+ // The cryptogram is built under the wrapping key the parameters carry, so it opens.
+ X509Certificate certificate =
+ Certificates.parseCertificate((String) parameters.get("WrappingKeyCertificate"));
+ String cryptogram = HexFormat.of().withUpperCase().formatHex(RsaOaep.encrypt(
+ certificate.getPublicKey(),
+ HexFormat.of().parseHex("00112233445566778899AABBCCDDEEFF"), "SHA-256"));
+
+ for (int i = 0; i < 2; i++) {
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram",
+ Map.of("ImportToken", token,
+ "WrappedKeyCryptogram", cryptogram,
+ "KeyAttributes", Map.of("KeyAlgorithm", "AES_128",
+ "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY",
+ "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true))), "", true, Map.of());
+ assertNotNull(imported, "the second import was refused");
+ }
+ }
+
+
+
+ @Test
+ void theExpiredTokensAreSwept() {
+ // A token that was issued and never quoted again would otherwise stay for the life
+ // of the process, and it holds a private key. The clock moves past the token's life,
+ // so the token is expired and the next issue sweeps it.
+ ManualClock clock = new ManualClock(Instant.parse("2026-01-01T00:00:00Z"));
+ PaymentCryptographyService timed = new PaymentCryptographyService(
+ new InMemoryStorage<>(),
+ new InMemoryStorage<>(),
+ new RegionResolver("us-east-1", "000000000000"),
+ new SecureRandom(),
+ new PaymentCryptographyRequestContext(),
+ new CertificateGenerator(),
+ clock);
+ timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+ clock.advance(Duration.ofDays(31));
+ timed.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+
+ assertEquals(1, timed.issuedTokenCount(),
+ "the token that expired was not swept");
+ }
+
+ @Test
+ void thePrivateKeyIsNotWrittenToTheStore() throws Exception {
+ // The store is a file in the working directory, and a private key in clear in it is
+ // a secret on disk.
+ PaymentCryptographyKey pair = createKeyPair("RSA_2048");
+
+ String written = new ObjectMapper().writeValueAsString(pair);
+
+ assertFalse(written.contains(pair.getKeyPrivateKeyBase64()),
+ "the private key was written to the store");
+ assertFalse(written.contains("keyPrivateKeyBase64"),
+ "the private key was written to the store");
+ }
+
+ @Test
+ void aFormTheServiceDoesNotKnowIsRefused() {
+ PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Nonsense", Map.of(), "", ""));
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ /** A symmetric key of the given algorithm and usage. */
+ private PaymentCryptographyKey createKey(String algorithm, String usage) {
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", algorithm);
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", usage);
+ return service.createKey("us-east-1", attributes,
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+ }
+
+ /** A key pair of the given algorithm. */
+ private PaymentCryptographyKey createKeyPair(String algorithm) {
+ return createKeyPair(algorithm, "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
+ }
+
+ /** A key pair of the given algorithm, for the given usage. */
+ private PaymentCryptographyKey createKeyPair(String algorithm, String usage) {
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", algorithm);
+ attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR");
+ attributes.put("KeyUsage", usage);
+ // The modes are the ones the purpose allows: a key agreement key derives, a signing
+ // key signs and verifies.
+ Map modes = "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT".equals(usage)
+ ? Map.of("DeriveKey", true)
+ : Map.of("Sign", true, "Verify", true);
+ return service.createKey("us-east-1", attributes, modes, true, true, Map.of());
+ }
+
+ /**
+ * The authority of the exchange: the public half of the certificate the receiver brings.
+ *
+ * A certificate that the service minted for the import is signed by the key it names,
+ * so the key that holds its public half is the authority that can vouch for it.
+ */
+ private PaymentCryptographyKey createAuthority(String certificate) {
+ return createAuthority(certificate, true);
+ }
+
+ /** An authority that vouches for a certificate, enabled or not. */
+ private PaymentCryptographyKey createAuthority(String certificate, boolean enabled) {
+ return service.importKey("us-east-1", "TrustedCertificatePublicKey", Map.of(
+ "PublicKeyCertificate", certificate,
+ "KeyAttributes", authorityAttributes()), "", enabled, Map.of());
+ }
+
+ /** The attributes an authority carries: a public key that may verify. */
+ private static Map authorityAttributes() {
+ return Map.of(
+ "KeyAlgorithm", "RSA_2048",
+ "KeyClass", "PUBLIC_KEY",
+ "KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
+ "KeyModesOfUse", Map.of("Verify", Boolean.TRUE));
+ }
+
+ /**
+ * A key exchange under a key the two parties agreed with ECDH.
+ *
+ * The service trusts the certificate the counterparty brings because the authority
+ * signed it, so the helper imports the authority, makes the agreement key and builds the
+ * material of the export.
+ *
+ * @param authorityCertificate the certificate of the authority that vouches for the
+ * counterparty
+ * @param counterpartyCertificate the certificate the counterparty brings
+ * @return the material of the export, and the key that leaves under it
+ */
+ private Exchange agreedExchange(Certificates.Minted authorityCertificate,
+ Certificates.Minted counterpartyCertificate) {
+ PaymentCryptographyKey authority = createAuthority(authorityCertificate.pem());
+ PaymentCryptographyKey agreement = createKeyPair("ECC_NIST_P256",
+ "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT");
+ Map material = new LinkedHashMap<>();
+ material.put("PrivateKeyIdentifier", agreement.getKeyId());
+ material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
+ material.put("PublicKeyCertificate", counterpartyCertificate.pem());
+ material.put("DeriveKeyAlgorithm", "AES_128");
+ material.put("KeyDerivationFunction", "ANSI_X963");
+ material.put("KeyDerivationHashAlgorithm", "SHA_256");
+ material.put("DerivationData", Map.of(
+ "SharedInformation", "00112233445566778899AABBCCDDEEFF"));
+ return new Exchange(material,
+ createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
+ }
+
+ /** The material of a key exchange, and the key that leaves under it. */
+ private record Exchange(Map material, PaymentCryptographyKey key) {
+ }
+
+
+ @Test
+ void anAuthorityThatMayNotVerifyIsRefused() {
+ // The authority vouches for the other party's certificate, so it has to be allowed to
+ // verify.
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ // The cryptogram is wrapped under the receiver's certificate, and a certificate over
+ // a 3072-bit modulus is as strong as the key it wraps.
+ KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
+ Instant now = Instant.now();
+ Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA");
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(), "floci counterparty", authority.getPrivate(), "floci CA");
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "RSA_2048");
+ attributes.put("KeyClass", "PUBLIC_KEY");
+ attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
+ attributes.put("KeyModesOfUse", Map.of("Encrypt", Boolean.TRUE));
+ PaymentCryptographyKey ca = service.importKey("us-east-1", "TrustedCertificatePublicKey",
+ Map.of("PublicKeyCertificate", caCertificate.pem(), "KeyAttributes", attributes),
+ "", true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", createKey("AES_128",
+ "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram",
+ Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
+ "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("Verify"), refused.getMessage());
+ }
+
+ @Test
+ void anExpiredCertificateIsRefused() {
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ // The cryptogram is wrapped under the receiver's certificate, and a certificate over
+ // a 3072-bit modulus is as strong as the key it wraps.
+ KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
+ Instant now = Instant.now();
+ Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA", authority.getPrivate(), "floci CA");
+ // The counterparty's certificate has expired, so it protects nothing.
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", authority.getPrivate(), "floci CA",
+ now.minusSeconds(7200), now.minusSeconds(3600));
+ PaymentCryptographyKey ca = createAuthority(caCertificate.pem());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", createKey("AES_128",
+ "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(), "KeyCryptogram",
+ Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
+ "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("validity window"), refused.getMessage());
+ }
+
+ @Test
+ void aCertificateThatDoesNotParseIsRefused() {
+ // The text is not a certificate, so it is refused rather than stored as one.
+ AwsException refused = assertThrows(AwsException.class,
+ () -> createAuthority("not a certificate at all"));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("not a certificate"), refused.getMessage());
+ }
+
+ @Test
+ void aDisabledKeyDoesNotLeave() {
+ // A disabled key does no work, so it may not be exported.
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
+ "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)),
+ Map.of("Encrypt", true, "Decrypt", true), true, false, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("disabled"), refused.getMessage());
+ }
+
+ @Test
+ void anImportedKeyGetsEveryModeTheBlockStandsFor() {
+ // The mode of use character of the block says what the key may be used for, and
+ // both spellings of a direction stand for it. A block that says B gives the key all
+ // four of Encrypt, Decrypt, Wrap and Unwrap, whichever use the key has.
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ String block = blockOf(key);
+ assertEquals("B", block.substring(8, 9), "the mode of use of the block");
+
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
+ "", true, Map.of());
+
+ Map modes = imported.getKeyModesOfUse();
+ assertEquals(Boolean.TRUE, modes.get("Encrypt"), "the imported key may encrypt");
+ assertEquals(Boolean.TRUE, modes.get("Decrypt"), "the imported key may decrypt");
+ assertEquals(Boolean.TRUE, modes.get("Wrap"), "the imported key may wrap");
+ assertEquals(Boolean.TRUE, modes.get("Unwrap"), "the imported key may unwrap");
+ }
+
+ @Test
+ void anExportMayNotGiveAKeyAPermissionItDoesNotHave() {
+ // A key that may only encrypt is refused an export that says it may decrypt: the
+ // modes of use a request names may only narrow the ones the key has.
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ Map.of("KeyAlgorithm", "AES_128", "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
+ "KeyModesOfUse", Map.of("Encrypt", true)),
+ Map.of("Encrypt", true), true, true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "KeyBlockHeaders", Map.of("KeyModesOfUse",
+ Map.of("Encrypt", true, "Decrypt", true))),
+ "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("Decrypt"), refused.getMessage());
+ }
+
+ @Test
+ void anExportMayNotLoosenTheExportability() {
+ // The exportability says what the receiver may do with the key once it has it, and
+ // the model states SENSITIVE as the loosest of the three: it lets the receiver
+ // export under a key block, a TR-34 block or a cryptogram, where EXPORTABLE lets it
+ // export under a key block or a TR-34 block only. So an exportable key may not
+ // leave as SENSITIVE, because that is looser than what the key has.
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "KeyBlockHeaders", Map.of("KeyExportability", "SENSITIVE")),
+ "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("looser"), refused.getMessage());
+ }
+
+ @Test
+ void anExportMayTightenTheExportability() {
+ // The other way round: the initial key of the DUKPT derivation is sensitive, and
+ // EXPORTABLE is stricter than that, so it may leave as one.
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "TDES_2KEY");
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
+ PaymentCryptographyKey base = service.createKey("us-east-1", attributes,
+ Map.of("DeriveKey", Boolean.TRUE), true, true, Map.of());
+
+ Map answer = service.exportKey("us-east-1", base.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "KeyBlockHeaders", Map.of("KeyExportability", "EXPORTABLE")),
+ "12345678900000000001", "");
+ String block = (String) ((Map, ?>) answer.get("WrappedKey")).get("KeyMaterial");
+
+ assertEquals("E", block.substring(11, 12), "the exportability of the derived key");
+ }
+
+ @Test
+ void aDisabledAuthorityDoesNotVouchForACertificate() {
+ // The authority does work when it vouches for a certificate, and a disabled key does
+ // no work, so a disabled authority is refused.
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(2048, random);
+ Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA",
+ authority.getPrivate(), "floci CA");
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", authority.getPrivate(), "floci CA");
+ PaymentCryptographyKey ca = createAuthority(caCertificate.pem(), false);
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.importKey("us-east-1", "TrustedCertificatePublicKey",
+ Map.of("PublicKeyCertificate", counterpartyCertificate.pem(),
+ "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId(),
+ "KeyAttributes", authorityAttributes()),
+ "", true, Map.of()));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("disabled"), refused.getMessage());
+ }
+
+ @Test
+ void anImportedKeySaysItCameFromOutsideTheService() {
+ // A key that came in says its origin is EXTERNAL, and a key the service made says
+ // it is AWS_PAYMENT_CRYPTOGRAPHY.
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "WrappedKeyBlock", blockOf(createKey("AES_128",
+ "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"))),
+ "", true, Map.of());
+
+ assertEquals("EXTERNAL", imported.getKeyOrigin(), "the origin of an imported key");
+ assertEquals("AWS_PAYMENT_CRYPTOGRAPHY", protection.getKeyOrigin(),
+ "the origin of a key the service made");
+ }
+
+ @Test
+ void aCryptogramCarriesNoCheckValue() {
+ // A key block carries the check value of the key it carries, and a cryptogram
+ // carries no key block at all, so it carries no check value either.
+ SecureRandom random = new SecureRandom();
+ KeyPair authority = PaymentCryptographyKeyPairs.rsa(2048, random);
+ KeyPair counterparty = PaymentCryptographyKeyPairs.rsa(3072, random);
+ Certificates.Minted caCertificate = CertificatesTest.mint(authority.getPublic(), "floci CA",
+ authority.getPrivate(), "floci CA");
+ Certificates.Minted counterpartyCertificate = CertificatesTest.mint(counterparty.getPublic(),
+ "floci counterparty", authority.getPrivate(), "floci CA");
+ PaymentCryptographyKey ca = createAuthority(caCertificate.pem());
+
+ Map answer = service.exportKey("us-east-1",
+ createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY").getKeyId(),
+ "KeyCryptogram",
+ Map.of("WrappingKeyCertificate", counterpartyCertificate.pem(),
+ "CertificateAuthorityPublicKeyIdentifier", ca.getKeyId()), "", "");
+
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat"));
+ assertFalse(wrapped.containsKey("KeyCheckValue"), "the cryptogram carries a check value");
+ assertFalse(wrapped.containsKey("KeyCheckValueAlgorithm"),
+ "the cryptogram carries a check value algorithm");
+ }
+
+ /** The key block a key leaves under the protection key of the test. */
+ private String blockOf(PaymentCryptographyKey key) {
+ Map answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "");
+ return (String) ((Map, ?>) answer.get("WrappedKey")).get("KeyMaterial");
+ }
+
+ @Test
+ void aDataEncryptionKeyMayNotWrapAnExport() {
+ // The wrapping key of a key block is a key encryption key, and a data encryption key
+ // is not one.
+ PaymentCryptographyKey data = service.createKey("us-east-1",
+ Map.of("KeyAlgorithm", "AES_256", "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
+ "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)),
+ Map.of("Encrypt", true, "Decrypt", true), true, true, Map.of());
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", data.getKeyId()), "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("not a key encryption key"), refused.getMessage());
+ }
+
+ @Test
+ void anImportedKeyThatMayNotLeaveStaysThatWay() {
+ // The exportability is a member of the form, beside the attributes and not inside
+ // them.
+ Map importParameters = service.parametersForImport("KEY_CRYPTOGRAM",
+ "RSA_2048", false);
+ PaymentCryptographyKey key = createKey("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ PaymentCryptographyKey authority = createAuthority(
+ (String) importParameters.get("WrappingKeyCertificate"));
+ Map material = new LinkedHashMap<>();
+ material.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate"));
+ material.put("CertificateAuthorityPublicKeyIdentifier", authority.getKeyId());
+ material.put("WrappingSpec", "RSA_OAEP_SHA_256");
+ Map answer = service.exportKey("us-east-1", key.getKeyId(), "KeyCryptogram",
+ material, "", "");
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+
+ Map incoming = new LinkedHashMap<>();
+ incoming.put("ImportToken", importParameters.get("ImportToken"));
+ incoming.put("WrappedKeyCryptogram", wrapped.get("KeyMaterial"));
+ incoming.put("WrappingKeyIdentifier", authority.getKeyId());
+ incoming.put("WrappingSpec", "RSA_OAEP_SHA_256");
+ incoming.put("Exportable", Boolean.FALSE);
+ incoming.put("KeyAttributes", Map.of(
+ "KeyAlgorithm", "TDES_2KEY",
+ "KeyClass", "SYMMETRIC_KEY",
+ "KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
+ "KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)));
+
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "KeyCryptogram", incoming,
+ "", true, Map.of());
+
+ assertFalse(imported.isExportable(), "the key was imported as one that may leave");
+ }
+
+ @Test
+ void aKeyOfAnotherPurposeMayNotAgree() {
+ // The key that agrees has to be a key agreement key.
+ PaymentCryptographyKey signing = createKeyPair("ECC_NIST_P256");
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock",
+ Map.of("PrivateKeyIdentifier", signing.getKeyId(),
+ "CertificateAuthorityPublicKeyIdentifier", signing.getKeyId(),
+ "PublicKeyCertificate", "not a certificate",
+ "DeriveKeyAlgorithm", "AES_128",
+ "KeyDerivationFunction", "ANSI_X963",
+ "KeyDerivationHashAlgorithm", "SHA_256",
+ "DerivationData", Map.of(
+ "SharedInformation", "00112233445566778899AABBCCDDEEFF")),
+ "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("key agreement"), refused.getMessage());
+ }
+
+ @Test
+ void aKeyThatIsNotACurveKeyIsRefused() {
+ // An RSA key cannot take part in an agreement, and it is refused rather than read as
+ // a curve key.
+ PaymentCryptographyKey rsa = createKeyPair("RSA_2048");
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "DiffieHellmanTr31KeyBlock",
+ Map.of("PrivateKeyIdentifier", rsa.getKeyId(),
+ "CertificateAuthorityPublicKeyIdentifier", rsa.getKeyId(),
+ "PublicKeyCertificate", "not a certificate",
+ "DeriveKeyAlgorithm", "AES_128",
+ "KeyDerivationFunction", "ANSI_X963",
+ "KeyDerivationHashAlgorithm", "SHA_256",
+ "DerivationData", Map.of(
+ "SharedInformation", "00112233445566778899AABBCCDDEEFF")),
+ "", ""));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ @Test
+ void anExportWithAnotherCheckValueAlgorithmIsRefused() {
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "ANSI_X9_24"));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage());
+ }
+
+ @Test
+ void anImportWithAnotherCheckValueAlgorithmIsRefused() {
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ Map answer = service.exportKey("us-east-1", key.getKeyId(), "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId()), "", "");
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(),
+ "WrappedKeyBlock", block),
+ "ANSI_X9_24", true, Map.of()));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("check value algorithm"), refused.getMessage());
+ }
+
+ @Test
+ void theParametersCanBeReused() {
+ // A caller that asks for the last parameters gets them, token and certificate alike.
+ Map first = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+ Map again = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", true);
+ Map fresh = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048", false);
+
+ assertEquals(first.get("ImportToken"), again.get("ImportToken"));
+ assertEquals(first.get("WrappingKeyCertificate"), again.get("WrappingKeyCertificate"));
+ assertNotEquals(first.get("ImportToken"), fresh.get("ImportToken"));
+ }
+
+ @Test
+ void theExportParametersOutliveTheirCertificate() {
+ // The parameters are good until the certificate they carry is not.
+ Map parameters = service.parametersForExport("TR34_KEY_BLOCK", "RSA_2048",
+ false);
+ String certificate = (String) parameters.get("SigningKeyCertificate");
+ long validUntil = ((Number) parameters.get("ParametersValidUntilTimestamp")).longValue();
+ X509Certificate parsed = Certificates.parseCertificate(certificate);
+
+ assertTrue(parsed.getNotAfter().toInstant().getEpochSecond() >= validUntil,
+ "the certificate expires before the parameters do");
+ }
+
+ @Test
+ void aSensitiveKeyMayLeaveTheServiceAgain() {
+ // The exportability of a block says whether the key that comes in may leave again.
+ // A sensitive one may: it is only under a trusted key that it may not be worked with.
+ //
+ // The block is made here rather than exported, because the service writes the
+ // exportability of the block it makes itself: a key it exports is exportable, and
+ // the only key it exports as sensitive is the initial DUKPT key, whose usage the
+ // model has no name for. A counterparty's block may carry the sensitive one all the
+ // same.
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyKeyRules.material(
+ createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY")),
+ PaymentCryptographyKeyRules.material(protection),
+ true, "A", "D0", "B", "S");
+
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
+ "", true, Map.of());
+
+ assertTrue(imported.isExportable(), "the sensitive key may not leave the service again");
+ }
+
+ @Test
+ void aKeyThatIsNotExportableDoesNotComeBackExportable() {
+ // The exportability of a block says whether the key that comes in may leave again.
+ Map material = new LinkedHashMap<>();
+ material.put("WrappingKeyIdentifier", protection.getKeyId());
+ material.put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE"));
+
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ Map, ?> wrapped = (Map, ?>) service.exportKey("us-east-1", key.getKeyId(),
+ "Tr31KeyBlock", material, "", "").get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+
+ PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", protection.getKeyId(), "WrappedKeyBlock", block),
+ "", true, Map.of());
+
+ assertFalse(imported.isExportable(), "the key that may not leave came back exportable");
+ }
+
+ @Test
+ void theModesOfUseTheRequestNamesAreReadTheWayTheKeyHasThem() {
+ // A key encryption key wraps and unwraps rather than encrypting and decrypting, so
+ // the modes the request names for one are read that way too.
+ Map material = new LinkedHashMap<>();
+ material.put("WrappingKeyIdentifier", protection.getKeyId());
+ material.put("KeyBlockHeaders", Map.of(
+ "KeyModesOfUse", Map.of("Wrap", true, "Unwrap", true)));
+
+ PaymentCryptographyKey key = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
+ Map, ?> wrapped = (Map, ?>) service.exportKey("us-east-1", key.getKeyId(),
+ "Tr31KeyBlock", material, "", "").get("WrappedKey");
+ String block = (String) wrapped.get("KeyMaterial");
+
+ assertEquals("B", block.substring(8, 9), "the mode of use of the key");
+ }
+
+ @Test
+ void theCertificateOfAKeyCarriesItsChain() {
+ // The certificate the service mints is signed by the service, so the chain is the
+ // certificate itself.
+ PaymentCryptographyKey key = createKeyPair("RSA_2048");
+
+ Map answer = service.publicKeyCertificate(key);
+
+ assertNotNull(answer.get("KeyCertificate"), "the certificate is missing");
+ assertNotNull(answer.get("KeyCertificateChain"), "the chain of the certificate is missing");
+ X509Certificate parsed = Certificates.parseCertificate(
+ (String) answer.get("KeyCertificate"));
+ long validity = parsed.getNotAfter().toInstant().getEpochSecond()
+ - parsed.getNotBefore().toInstant().getEpochSecond();
+ // The certificate is good for ninety days, and it starts an hour early so that a
+ // clock a little behind the service's still accepts it.
+ assertEquals(90L * 24 * 3600 + 3600, validity,
+ "the certificate is not valid for ninety days");
+ }
+
+}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
index 0b957ea63a..3c68430ffc 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
@@ -61,6 +61,23 @@ class PaymentCryptographyServiceTest {
return service.createKey(region, attributes, modes, true, true, Map.of());
}
+ /**
+ * The key a key block is wrapped under.
+ *
+ * A key block is wrapped under a key encryption key, and not under a data encryption
+ * key: the usages keep the two apart.
+ */
+ private PaymentCryptographyKey createWrappingKey(String region) {
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "AES_256");
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY");
+ Map modes = new LinkedHashMap<>();
+ modes.put("Wrap", Boolean.TRUE);
+ modes.put("Unwrap", Boolean.TRUE);
+ return service.createKey(region, attributes, modes, true, true, Map.of());
+ }
+
@Test
void aCreatedKeyIsInItsRegionAndCarriesMaterial() {
PaymentCryptographyKey key = createKey("us-east-1");
@@ -540,4 +557,226 @@ class PaymentCryptographyServiceTest {
service.find("alias", List.of("alias/team/card-key"), "us-east-1"));
assertEquals(Optional.empty(), service.find("approval-team", List.of("whatever"), "us-east-1"));
}
+
+ @Test
+ void aKeyLeavesTheServiceAndComesBack() {
+ PaymentCryptographyKey protection = createWrappingKey("us-east-1");
+ PaymentCryptographyKey key = createKey("us-east-1");
+
+ Map answer = exportTr31Answer("us-east-1", key.getKeyId(),
+ protection.getKeyId());
+ Map, ?> wrapped = (Map, ?>) answer.get("WrappedKey");
+ String export = (String) wrapped.get("KeyMaterial");
+
+ assertEquals(protection.getArn(), wrapped.get("WrappingKeyArn"));
+ assertEquals(key.getKeyCheckValue(), wrapped.get("KeyCheckValue"));
+ assertTrue(export.length() > 32, "the block is only its header");
+
+ PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
+
+ assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
+ assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue());
+ assertEquals(key.getKeyUsage(), imported.getKeyUsage());
+ assertTrue(imported.isExportable(), "the block said the key is exportable");
+ }
+
+ @Test
+ void aKeyLeavesUnderATdesProtectionKeyAsATypeBBlock() {
+ // The block type follows the protection key's family: a TDES key gives a type B block,
+ // an AES one a type D block. That is the rule the emulator follows.
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("TDES_2KEY", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ attributes("TDES_2KEY", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
+
+ assertTrue(export.startsWith("B"), "a TDES protection key gives a type B block");
+ assertEquals("T", export.substring(7, 8), "the block carries a TDES key");
+
+ PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
+
+ assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
+ assertEquals(key.getKeyCheckValue(), imported.getKeyCheckValue());
+ }
+
+ @Test
+ void aKeyLeavesUnderAnAesProtectionKeyAsATypeDBlock() {
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
+
+ assertTrue(export.startsWith("D"), "an AES protection key gives a type D block");
+ assertEquals("A", export.substring(7, 8), "the block carries an AES key");
+ }
+
+ @Test
+ void aKeyUnderAWeakerProtectionKeyIsRefused() {
+ // The wrapping key has to be at least as strong as the key it protects, or the
+ // protection buys nothing. The strengths are the ones the standards count, so a
+ // two-key TDES key is 80 bits and an AES-128 one is 128.
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("AES_128", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ assertTrue(refused.getMessage().contains("at least as strong"), refused.getMessage());
+ }
+
+ @Test
+ void aKeyUnderAStrongerProtectionKeyIsAllowed() {
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ attributes("AES_128", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
+
+ assertTrue(export.startsWith("D"), "an AES protection key gives a type D block");
+ }
+
+ @Test
+ void aKeyOfEveryUsageTheServiceMakesLeavesAsItsOwnUsage() {
+ // A key block carries the usage of the key it carries, so every usage the service
+ // makes has to have a code. A usage without one could not leave the service at all,
+ // and the counterparty could not tell what it had.
+ //
+ // The asymmetric usage is not in the list: a key pair has no material a key block
+ // could carry, so it leaves in a TR-34 block, which this service does not write.
+ List usages = List.of(
+ new String[] {"TR31_B0_BASE_DERIVATION_KEY", "AES_256"},
+ new String[] {"TR31_C0_CARD_VERIFICATION_KEY", "AES_256"},
+ new String[] {"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "AES_256"},
+ new String[] {"TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS", "AES_256"},
+ new String[] {"TR31_E1_EMV_MKEY_CONFIDENTIALITY", "AES_256"},
+ new String[] {"TR31_E2_EMV_MKEY_INTEGRITY", "AES_256"},
+ new String[] {"TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS", "AES_256"},
+ new String[] {"TR31_E5_EMV_MKEY_CARD_PERSONALIZATION", "AES_256"},
+ new String[] {"TR31_E6_EMV_MKEY_OTHER", "AES_256"},
+ new String[] {"TR31_K0_KEY_ENCRYPTION_KEY", "AES_256"},
+ new String[] {"TR31_K1_KEY_BLOCK_PROTECTION_KEY", "AES_256"},
+ // The ISO 9797 MACs are defined over Triple DES.
+ new String[] {"TR31_M0_ISO_16609_MAC_KEY", "TDES_2KEY"},
+ new String[] {"TR31_M1_ISO_9797_1_MAC_KEY", "TDES_2KEY"},
+ new String[] {"TR31_M3_ISO_9797_3_MAC_KEY", "TDES_2KEY"},
+ new String[] {"TR31_M6_ISO_9797_5_CMAC_KEY", "AES_256"},
+ new String[] {"TR31_M7_HMAC_KEY", "AES_256"},
+ new String[] {"TR31_P0_PIN_ENCRYPTION_KEY", "AES_256"},
+ new String[] {"TR31_P1_PIN_GENERATION_KEY", "AES_256"},
+ new String[] {"TR31_V1_IBM3624_PIN_VERIFICATION_KEY", "AES_256"},
+ new String[] {"TR31_V2_VISA_PIN_VERIFICATION_KEY", "AES_256"});
+
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+
+ for (String[] usage : usages) {
+ PaymentCryptographyKey key = service.createKey("us-east-1",
+ attributes(usage[1], usage[0]),
+ Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
+
+ String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
+
+ PaymentCryptographyKey imported = importTr31("us-east-1", protection.getKeyId(), export);
+
+ assertEquals(usage[0], imported.getKeyUsage(), usage[0] + " did not survive the round trip");
+ }
+ }
+
+ @Test
+ void anAsymmetricKeyDoesNotLeaveInAKeyBlock() {
+ // The asymmetric usage is a key pair, and a key pair has no material a key block
+ // could carry. It leaves in a TR-34 block, which this service does not write.
+ PaymentCryptographyKey protection = service.createKey("us-east-1",
+ attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
+ Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE), true, true, Map.of());
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "RSA_2048");
+ attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR");
+ attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
+ PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
+ Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE), true, true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ @Test
+ void aKeyThatIsNotExportableDoesNotLeaveTheService() {
+ PaymentCryptographyKey protection = createKey("us-east-1");
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", "AES_256");
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+ PaymentCryptographyKey key = service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> exportTr31("us-east-1", key.getKeyId(), protection.getKeyId()));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ @Test
+ void aBlockThatIsNotTheKeysDoesNotOpen() {
+ PaymentCryptographyKey protection = createWrappingKey("us-east-1");
+ PaymentCryptographyKey other = createWrappingKey("us-east-1");
+ PaymentCryptographyKey key = createKey("us-east-1");
+ String export = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> importTr31("us-east-1", other.getKeyId(), export));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ /**
+ * The TR-31 key block a key leaves the service in.
+ */
+ private String exportTr31(String region, String keyId, String wrappingKeyId) {
+ return (String) ((Map, ?>) exportTr31Answer(region, keyId, wrappingKeyId)
+ .get("WrappedKey")).get("KeyMaterial");
+ }
+
+ /**
+ * The whole answer of an export, which carries the block and what wrapped it.
+ */
+ private Map exportTr31Answer(String region, String keyId, String wrappingKeyId) {
+ return service.exportKey(region, keyId, "Tr31KeyBlock",
+ Map.of("WrappingKeyIdentifier", wrappingKeyId), "", "");
+ }
+
+ /**
+ * The key that comes into the service out of a TR-31 key block.
+ */
+ private PaymentCryptographyKey importTr31(String region, String wrappingKeyId, String block) {
+ return service.importKey(region, "Tr31KeyBlock", Map.of(
+ "WrappingKeyIdentifier", wrappingKeyId,
+ "WrappedKeyBlock", block), "", true, Map.of());
+ }
+
+ /** The attributes of a key with that algorithm and usage. */
+ private static Map attributes(String algorithm, String usage) {
+ Map attributes = new LinkedHashMap<>();
+ attributes.put("KeyAlgorithm", algorithm);
+ attributes.put("KeyClass", "SYMMETRIC_KEY");
+ attributes.put("KeyUsage", usage);
+ return attributes;
+ }
}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java
new file mode 100644
index 0000000000..cb852b7503
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTr31Test.java
@@ -0,0 +1,295 @@
+package io.floci.aws.services.paymentcryptography;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.HexFormat;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The TR-31 key block, against the vectors the standard's examples give.
+ *
+ * The values here are the ones a key block must have, checked against an
+ * independent implementation of the same formats. The block type follows the family of the
+ * key that protects it: a type B block under a TDES key and a type D one under an AES key, and
+ * the algorithm byte says which family the key the block carries belongs to.
+ *
+ *
Every vector here was computed by the emulator itself, so a block made here and a block
+ * made there are the same bytes and a block made under one kind of protection key does not open
+ * under another.
+ */
+class PaymentCryptographyTr31Test {
+
+ /** The hexadecimal the blocks are written in. */
+ private static final HexFormat HEX = HexFormat.of().withUpperCase();
+
+ /** A two-key TDES key block protection key, sixteen bytes. */
+ private static final String TDES_2KEY_KEK = "0123456789ABCDEFFEDCBA9876543210";
+
+ /** A three-key TDES key block protection key, twenty-four bytes. */
+ private static final String TDES_3KEY_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210";
+
+ /** An AES-128 key block protection key, sixteen bytes. */
+ private static final String AES_128_KEK = "0123456789ABCDEFFEDCBA9876543210";
+
+ /** An AES-192 key block protection key, twenty-four bytes. */
+ private static final String AES_192_KEK = "0123456789ABCDEFFEDCBA9876543210FEDCBA9876543210";
+
+ /** An AES-256 key block protection key, thirty-two bytes. */
+ private static final String AES_256_KEK =
+ "0123456789ABCDEFFEDCBA9876543210FEDCBA98765432100011223344556677";
+
+ /** The key a block carries. */
+ private static final String CLEAR_KEY = "00112233445566778899AABBCCDDEEFF";
+
+ @Test
+ void aTypeBBlockUnderATwoKeyTdesKeyIsTheOneTheEmulatorMakes() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
+ false, "T", "D0", "B", "E");
+
+ assertEquals("B0080D0TB00E000026E528E7FBDBA2578329DDD6F427055C2D51AF1AF42ED5829C79F8ADD31152C8",
+ block);
+ assertEquals("D0", PaymentCryptographyTr31.usageOf(block));
+ assertEquals("B", PaymentCryptographyTr31.modeOf(block));
+ assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block));
+ }
+
+ @Test
+ void aTypeBBlockUnderAThreeKeyTdesKeyIsTheOneTheEmulatorMakes() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(TDES_3KEY_KEK),
+ false, "T", "D0", "B", "E");
+
+ assertEquals("B0080D0TB00E000001FF74012D3ABDE92191B91AA598383A0FD7CB744A9E4AFE9D34A369AD6552C3",
+ block);
+ }
+
+ @Test
+ void aTypeDBlockUnderAnAes128KeyIsTheOneTheEmulatorMakes() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK),
+ true, "A", "D0", "B", "E");
+
+ assertEquals("D0112D0AB00E00002BF9E2CB83E27A26C8790C18CAC198C415E9E78520142D81320789CFD5B9C09DEF03F7569177D33FD1BE0A1DAB4D33AB",
+ block);
+ }
+
+ @Test
+ void aTypeDBlockUnderAnAes192KeyIsTheOneTheEmulatorMakes() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_192_KEK),
+ true, "A", "D0", "B", "E");
+
+ assertEquals("D0112D0AB00E00003FF1AB040D384A3F1827C5EE54DC7CFA43635B0186A3A63A57E77958737CEA57B972DFE983F559525768746563BC6FF7",
+ block);
+ assertEquals("D0", PaymentCryptographyTr31.usageOf(block));
+ assertEquals("B", PaymentCryptographyTr31.modeOf(block));
+ assertEquals("E", PaymentCryptographyTr31.exportabilityOf(block));
+ }
+
+ @Test
+ void aTypeDBlockUnderAnAes256KeyIsTheOneTheEmulatorMakes() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_256_KEK),
+ true, "A", "D0", "B", "E");
+
+ assertEquals("D0112D0AB00E00003E9F4789A8798032CEC87CBA5960E1D7F4512292784F56164C0A62AA2F184D2151167F8F8013169102F89530D9B0C647",
+ block);
+ }
+
+ @Test
+ void aBlockOpensUnderTheKeyThatMadeIt() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
+ false, "T", "D0", "B", "E");
+
+ assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK)));
+ }
+
+ @Test
+ void aTypeDBlockOpensUnderTheAesKeyThatMadeIt() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_192_KEK),
+ true, "A", "D0", "B", "E");
+
+ assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyTr31.unwrap(block, PaymentCryptographyCrypto.fromHex(AES_192_KEK)));
+ }
+
+ @Test
+ void aBlockDoesNotOpenUnderAnotherKey() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(TDES_2KEY_KEK),
+ false, "T", "D0", "B", "E");
+
+ try {
+ PaymentCryptographyTr31.unwrap(block,
+ PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEF"));
+ throw new AssertionError("the block opened under the wrong key");
+ } catch (IllegalArgumentException expected) {
+ assertEquals("the key block did not authenticate under the key", expected.getMessage());
+ }
+ }
+
+ @Test
+ void aTypeDBlockDoesNotOpenUnderAnotherKeyOfTheSameLength() {
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_192_KEK),
+ true, "A", "D0", "B", "E");
+
+ try {
+ PaymentCryptographyTr31.unwrap(block,
+ PaymentCryptographyCrypto.fromHex("FEDCBA98765432100123456789ABCDEFFEDCBA9876543210"));
+ throw new AssertionError("the block opened under another key");
+ } catch (IllegalArgumentException expected) {
+ assertEquals("the key block did not authenticate under the key", expected.getMessage());
+ }
+ }
+
+ @Test
+ void aBlockWithOptionalBlocksIsImported() {
+ // An optional block sits between the header and the cipher text in the clear, and it
+ // is authenticated with it, so the cipher text starts after it.
+ // The identifier, the length over two characters and the value. The length covers
+ // the whole block, the identifier and the length included, and it is in hexadecimal.
+ String block = blockWithOptionalBlock("00" + "0C" + "61626364");
+
+ byte[] key = PaymentCryptographyTr31.unwrap(block,
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK));
+
+ assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key);
+ }
+
+ @Test
+ void anOptionalBlockWithALengthInHexadecimalIsRead() {
+ // The length of an optional block is in hexadecimal, so a length of "0E" is fourteen
+ // characters and not a number at all.
+ String block = blockWithOptionalBlock("TT" + "0E" + "0123456789");
+
+ byte[] key = PaymentCryptographyTr31.unwrap(block,
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK));
+
+ assertArrayEquals(PaymentCryptographyCrypto.fromHex(CLEAR_KEY), key);
+ }
+
+ @Test
+ void theOptionalBlockTheReferenceGivesIsWrittenAsItGivesIt() {
+ // The reference gives the base derivation key identifier of a DUKPT key as "BI" with
+ // the value "00ABCDEFABCD", and its length is written as "10": the whole block is
+ // sixteen characters, the identifier and the length included.
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
+ "A", "D0", "B", "E", "00",
+ List.of(new String[] {"BI", "00ABCDEFABCD"}));
+
+ assertEquals("BI1000ABCDEFABCD", block.substring(16, 32),
+ "the optional block was not written as the standard says");
+ }
+
+ @Test
+ void aBlockIsPaddedSoThatItsOptionalBlocksStayAligned() {
+ // The optional blocks take up a whole number of cipher blocks, so a block whose
+ // optional blocks are not aligned gets a padding block that makes them so. The
+ // optional block here is twenty-four characters and a cipher block is sixteen, so
+ // the padding block carries four characters of filler.
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
+ "A", "D0", "B", "E", "00",
+ List.of(new String[] {"KS", "00604B120F9292800000"}));
+
+ // The optional block and the padding block between the header and the cipher text.
+ String optional = block.substring(16, 16 + 32);
+ assertEquals("KS1800604B120F9292800000", optional.substring(0, 24),
+ "the optional block was not written as the standard says");
+ assertEquals("PB080000", optional.substring(24), "the padding block was not added");
+ assertEquals(2, Integer.parseInt(block.substring(12, 14)),
+ "the padding block was not counted");
+ }
+
+ @Test
+ void aBlockWhoseOptionalBlocksAreAlignedGetsNoPaddingBlock() {
+ // Optional blocks that already fill whole cipher blocks are left alone, because a
+ // padding block would break the alignment. Twelve characters of data make the
+ // optional block sixteen characters long, which is one cipher block.
+ String block = PaymentCryptographyTr31.wrap(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY),
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK), true,
+ "A", "D0", "B", "E", "00",
+ List.of(new String[] {"KS", "00604B120F92"}));
+
+ assertEquals(1, Integer.parseInt(block.substring(12, 14)),
+ "a padding block was added to aligned optional blocks");
+ }
+
+ @Test
+ void aBlockWhoseKeyIsNotAWholeNumberOfBytesIsRefused() {
+ // The length the block declares is in bits, and a key is a whole number of bytes.
+ String block = blockWithLength("0081");
+
+ IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
+ () -> PaymentCryptographyTr31.unwrap(block,
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK)));
+
+ assertTrue(refused.getMessage().contains("whole number of bytes"), refused.getMessage());
+ }
+
+ /**
+ * A type D block with an optional block in the clear.
+ *
+ * The optional block is its identifier over two characters, its length over four and
+ * then its value. The header says how many of them there are.
+ */
+ private String blockWithOptionalBlock(String optional) {
+ byte[] lengthEncoded = PaymentCryptographyTr31.lengthEncode(
+ PaymentCryptographyCrypto.fromHex(CLEAR_KEY), 16);
+ byte[][] derived = PaymentCryptographyTr31.deriveKeys(
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK), true);
+ int blockLength = 16 + optional.length() + lengthEncoded.length * 2 + 32;
+ String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E"
+ + "01" + "00";
+ byte[] mac = PaymentCryptographyTr31.computeMac(header + optional, lengthEncoded,
+ derived[1], true);
+ byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded);
+ return header + optional + HEX.formatHex(cipherText) + HEX.formatHex(mac);
+ }
+
+ /**
+ * A type D block whose length field says the given bits.
+ *
+ *
The length is over the key the block carries, and the rest of the block is built the
+ * way the emulator builds one.
+ */
+ private String blockWithLength(String length) {
+ byte[] clearKey = PaymentCryptographyCrypto.fromHex(CLEAR_KEY);
+ byte[] lengthEncoded = new byte[32];
+ lengthEncoded[0] = (byte) ((Integer.parseInt(length, 16) >> 8) & 0xff);
+ lengthEncoded[1] = (byte) (Integer.parseInt(length, 16) & 0xff);
+ System.arraycopy(clearKey, 0, lengthEncoded, 2, clearKey.length);
+ byte[][] derived = PaymentCryptographyTr31.deriveKeys(
+ PaymentCryptographyCrypto.fromHex(AES_128_KEK), true);
+ int blockLength = 16 + lengthEncoded.length * 2 + 32;
+ String header = "D" + String.format("%04d", blockLength) + "D0" + "A" + "B" + "00" + "E"
+ + "00" + "00";
+ byte[] mac = PaymentCryptographyTr31.computeMac(header, lengthEncoded, derived[1], true);
+ byte[] cipherText = PaymentCryptographyCrypto.aesCbcEncrypt(derived[0], mac, lengthEncoded);
+ return header + HEX.formatHex(cipherText) + HEX.formatHex(mac);
+ }
+
+}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java
new file mode 100644
index 0000000000..44b3524e25
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/crypto/CertificatesTest.java
@@ -0,0 +1,100 @@
+package io.floci.aws.services.paymentcryptography.crypto;
+
+import io.floci.aws.services.acm.CertificateGenerator;
+import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber;
+import org.bouncycastle.asn1.x500.X500Name;
+import org.junit.jupiter.api.Test;
+
+import java.math.BigInteger;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import java.time.Instant;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+/**
+ * The certificates the key exchange hands out and reads.
+ *
+ *
The identifier a TR-34 block names its recipient with is the certificate's own issuer
+ * and serial number, so the two are read back from the certificate the service minted and
+ * compared with what the identifier carries.
+ */
+public class CertificatesTest {
+
+ private static final String CN = "floci key-exchange";
+
+ @Test
+ void theIdentifierOfACertificateIsItsIssuerAndItsSerial() throws Exception {
+ KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+ Instant now = Instant.now();
+ Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN);
+
+ byte[] identifier = Certificates.certificateId(certificate.der());
+
+ assertNotNull(identifier);
+ IssuerAndSerialNumber parsed = IssuerAndSerialNumber.getInstance(identifier);
+ X509Certificate certificateParsed = Certificates.parseCertificate(certificate.pem());
+ assertEquals(certificateParsed.getSerialNumber(),
+ parsed.getCertificateSerialNumber().getValue());
+ assertEquals(certificateParsed.getIssuerX500Principal().getName(),
+ parsed.getName().toString());
+ }
+
+ @Test
+ void theIdentifierOfACertificateThatDoesNotParseIsRefused() {
+ try {
+ Certificates.certificateId(new byte[] {0x30, 0x03, 0x02, 0x01, 0x05});
+ } catch (RuntimeException refused) {
+ assertEquals(true, refused.getMessage().contains("does not parse"));
+ return;
+ }
+ throw new AssertionError("a certificate that does not parse was accepted");
+ }
+
+ @Test
+ void theSerialOfTheIdentifierIsTheCertificatesOwn() throws Exception {
+ KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
+ Instant now = Instant.now();
+ Certificates.Minted certificate = mint(keyPair.getPublic(), CN, keyPair.getPrivate(), CN);
+
+ BigInteger serial = IssuerAndSerialNumber
+ .getInstance(Certificates.certificateId(certificate.der()))
+ .getCertificateSerialNumber().getValue();
+
+ assertEquals(Certificates.parseCertificate(certificate.pem()).getSerialNumber(), serial);
+ }
+
+ /**
+ * A certificate over a key pair, signed by an issuer.
+ *
+ *
The service mints its certificates through ACM's generator, and a test that needs a
+ * certificate of its own mints it the same way.
+ */
+ public static Certificates.Minted mint(PublicKey subjectKey, String subjectName,
+ PrivateKey issuerKey, String issuerName) {
+ return mint(subjectKey, subjectName, issuerKey, issuerName,
+ Instant.now().minusSeconds(3600), Instant.now().plusSeconds(86400));
+ }
+
+ /** A certificate over a key pair, signed by an issuer, with the given validity window. */
+ public static Certificates.Minted mint(PublicKey subjectKey, String subjectName,
+ PrivateKey issuerKey, String issuerName,
+ Instant notBefore, Instant notAfter) {
+ CertificateGenerator generator = new CertificateGenerator();
+ try {
+ X509Certificate certificate = generator.signCertificate(
+ new X500Name("CN=" + subjectName), subjectKey,
+ new X500Name("CN=" + issuerName), issuerKey,
+ List.of(), false, null, notBefore, notAfter);
+ byte[] der = certificate.getEncoded();
+ return new Certificates.Minted(der, Certificates.toPem(der));
+ } catch (Exception e) {
+ throw new IllegalStateException("cannot mint a certificate", e);
+ }
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java
index d758c15a67..669f4bc03f 100644
--- a/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/stepfunctions/StepFunctionsAwsSdkTaskIntegrationTest.java
@@ -148,7 +148,7 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
@Test
@Order(4)
- void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() {
+ void startExecutionReusingAnExecutionNameFailsWithTheSdkExceptionName() throws Exception {
String smArn = createStateMachine("aws-sdk-start-execution-named", """
{
"QueryLanguage": "JSONata",
@@ -164,8 +164,16 @@ class StepFunctionsAwsSdkTaskIntegrationTest {
}
""".replace("CHILD_ARN", quickChildArn));
- assertEquals("SUCCEEDED", waitForTerminalState(startExecution(smArn, "{}"))
- .jsonPath().getString("status"));
+ Response first = waitForTerminalState(startExecution(smArn, "{}"));
+ assertEquals("SUCCEEDED", first.jsonPath().getString("status"));
+
+ // The name is taken while the child's execution runs, and a start with that name and
+ // the same input then returns that execution again, so the second start would
+ // succeed. The name is a conflict once the child's execution is closed, so the test
+ // waits for that.
+ String childArn = mapper.readTree(first.jsonPath().getString("output"))
+ .path("ExecutionArn").asText();
+ waitForTerminalState(childArn);
Response describe = waitForTerminalState(startExecution(smArn, "{}"));
assertEquals("FAILED", describe.jsonPath().getString("status"));
diff --git a/tools/aws/regen_payment_cryptography_data_shapes.py b/tools/aws/regen_payment_cryptography_data_shapes.py
index f7d8a45633..5522d9645f 100644
--- a/tools/aws/regen_payment_cryptography_data_shapes.py
+++ b/tools/aws/regen_payment_cryptography_data_shapes.py
@@ -23,18 +23,12 @@ import request_shapes
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-data-request-shapes.json"
MODEL = Path("payment-cryptography-data/2022-02-03")
-OPERATIONS = (
- "EncryptData", "DecryptData", "ReEncryptData",
- "GenerateMac", "VerifyMac",
- "GeneratePinData", "VerifyPinData", "TranslatePinData", "GenerateMacEmvPinChange",
- "GenerateCardValidationData", "VerifyCardValidationData",
- "GenerateAuthRequestCryptogram", "VerifyAuthRequestCryptogram",
-)
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
- description=__doc__, operations=OPERATIONS,
+ description=__doc__,
+ constraints=True,
prepare=request_shapes.widen_partition_and_region)
diff --git a/tools/aws/regen_payment_cryptography_shapes.py b/tools/aws/regen_payment_cryptography_shapes.py
index 28baa2f77d..8e5f2917c0 100644
--- a/tools/aws/regen_payment_cryptography_shapes.py
+++ b/tools/aws/regen_payment_cryptography_shapes.py
@@ -20,16 +20,12 @@ import request_shapes
OUTPUT = request_shapes.REPO_ROOT / "src/main/resources/aws/payment-cryptography-request-shapes.json"
MODEL = Path("payment-cryptography/2021-09-14")
-OPERATIONS = (
- "CreateKey", "GetKey", "ListKeys", "DeleteKey",
- "CreateAlias", "GetAlias", "ListAliases", "UpdateAlias", "DeleteAlias",
- "TagResource", "UntagResource", "ListTagsForResource",
-)
def main(argv: list[str] | None = None) -> int:
return request_shapes.main(argv, script=__file__, model=MODEL, output=OUTPUT,
- description=__doc__, operations=OPERATIONS,
+ description=__doc__,
+ constraints=True,
prepare=request_shapes.widen_partition_and_region)
diff --git a/tools/aws/request_shapes.py b/tools/aws/request_shapes.py
index 5896d55be6..0052ca326e 100644
--- a/tools/aws/request_shapes.py
+++ b/tools/aws/request_shapes.py
@@ -152,7 +152,8 @@ def generator_name(script: str) -> str:
return path.relative_to(REPO_ROOT).as_posix() if path.is_relative_to(REPO_ROOT) else path.name
-def main(argv: list[str] | None, *, script: str, model: Path, output: Path, description: str,
+def main(argv: list[str] | None, *, script: str, model: Path, output: Path,
+ description: str | None = None,
outputs: bool = False, required: bool = False, operations: tuple[str, ...] | None = None,
constraints: bool = False,
prepare: Callable[[dict], dict] | None = None) -> int:
diff --git a/tools/aws/test_request_shapes.py b/tools/aws/test_request_shapes.py
index 39989553ed..4f1f7d937c 100644
--- a/tools/aws/test_request_shapes.py
+++ b/tools/aws/test_request_shapes.py
@@ -26,6 +26,7 @@ import regen_ecr_shapes
import regen_ecs_shapes
import regen_emr_serverless_shapes
import regen_iam_shapes
+import regen_payment_cryptography_data_shapes
import regen_payment_cryptography_shapes
import regen_logs_delivery_shapes
import regen_resource_groups_shapes
@@ -400,6 +401,30 @@ def test_each_constraints_script_runs_the_shared_main_with_its_operations(script
})]
+@pytest.mark.parametrize("script, model, output", [
+ (regen_payment_cryptography_shapes, "payment-cryptography/2021-09-14",
+ "payment-cryptography-request-shapes.json"),
+ (regen_payment_cryptography_data_shapes, "payment-cryptography-data/2022-02-03",
+ "payment-cryptography-data-request-shapes.json"),
+])
+def test_each_payment_cryptography_script_runs_the_shared_main_with_every_operation(script, model, output,
+ monkeypatch):
+ # The generator names no operation, so it asks the driver for the model's whole set: an
+ # operation the service serves later is covered without anyone adding it to a list.
+ calls = []
+ monkeypatch.setattr(r, "main", lambda argv, **kwargs: calls.append((argv, kwargs)) or 0)
+
+ assert script.main(["--check"]) == 0
+ assert calls == [(["--check"], {
+ "script": script.__file__,
+ "model": Path(model),
+ "output": r.REPO_ROOT / "src/main/resources/aws" / output,
+ "description": script.__doc__ or "",
+ "constraints": True,
+ "prepare": r.widen_partition_and_region,
+ })]
+
+
def vendored(script) -> tuple[str, ...]:
"""The operations a generator's file carries, which is `OPERATIONS` unless it names more."""
return getattr(script, "VENDORED", None) or script.OPERATIONS
@@ -407,7 +432,6 @@ def vendored(script) -> tuple[str, ...]:
@pytest.mark.parametrize("script", [
regen_apigateway_documentation_shapes, regen_ecr_shapes, regen_iam_shapes, regen_logs_delivery_shapes,
- regen_payment_cryptography_shapes,
regen_resource_groups_shapes, regen_sts_shapes,
regen_securityhub_shapes,
regen_rekognition_shapes,
@@ -416,8 +440,52 @@ def vendored(script) -> tuple[str, ...]:
def test_each_vendored_constraints_file_carries_its_operations_and_resolves_its_shapes(script):
doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))
+ # A generator that names no operation carries every one the model names, so the
+ # operations are only compared for one that names them.
if hasattr(script, "OPERATIONS") or hasattr(script, "VENDORED"):
assert sorted(doc["operations"]) == sorted(vendored(script))
+ assert_shapes_resolve(doc)
+
+
+@pytest.mark.parametrize("script", [
+ regen_payment_cryptography_shapes, regen_payment_cryptography_data_shapes,
+])
+def test_each_payment_cryptography_file_carries_every_operation_the_model_names(script):
+ # The generator names no operation, so the file carries every operation the model names:
+ # an operation the service serves later is checked without anyone adding it to a list.
+ pytest.importorskip("botocore")
+ try:
+ data, _ = r.resolve_botocore_data(None)
+ except SystemExit:
+ pytest.skip("the botocore data cannot be read here")
+ model = r.load_model(data, script.MODEL)
+
+ doc = json.loads(script.OUTPUT.read_text(encoding="utf-8"))
+
+ # An operation the model names without an input has no request to constrain.
+ named = {name for name, operation in model["operations"].items() if "input" in operation}
+ assert sorted(doc["operations"]) == sorted(named)
+ assert_shapes_resolve(doc)
+
+
+def test_main_leaves_out_an_operation_without_an_input(tmp_path, monkeypatch):
+ # An operation the model names without an input has no request to constrain, and the
+ # generator that asks for every operation leaves it out.
+ model = {"operations": {"Put": {"input": {"shape": "PutRequest"}}, "Nothing": {}},
+ "shapes": {"PutRequest": {"type": "structure", "members": {}}}}
+ output = tmp_path / "shapes.json"
+ monkeypatch.setattr(r, "resolve_botocore_data", lambda explicit: (tmp_path, "botocore test"))
+ monkeypatch.setattr(r, "load_model", lambda data, path: model)
+
+ assert r.main(["--output", str(output)], script=__file__, model=Path("x"), output=output,
+ description="test", constraints=True) == 0
+
+ doc = json.loads(output.read_text())
+ assert doc["operations"] == {"Put": "PutRequest"}
+
+
+def assert_shapes_resolve(doc: dict) -> None:
+ """Every operation's shape is in the file, and every shape's members resolve to shapes in it."""
for operation, shape in doc["operations"].items():
assert shape in doc["shapes"], operation
for name, shape in doc["shapes"].items():
@@ -499,8 +567,11 @@ def test_ecr_shapes_name_the_ecr_model_and_its_registry_setting_actions():
def test_payment_cryptography_shapes_name_its_model_and_its_control_plane_actions():
assert regen_payment_cryptography_shapes.MODEL == Path("payment-cryptography/2021-09-14")
assert regen_payment_cryptography_shapes.OUTPUT.name == "payment-cryptography-request-shapes.json"
- assert "TagResource" in regen_payment_cryptography_shapes.OPERATIONS
- assert "UpdateAlias" in regen_payment_cryptography_shapes.OPERATIONS
+ # The generator names no operation, so the file carries the model's whole set.
+ assert not hasattr(regen_payment_cryptography_shapes, "OPERATIONS")
+ operations = json.loads(regen_payment_cryptography_shapes.OUTPUT.read_text(encoding="utf-8"))["operations"]
+ assert "TagResource" in operations
+ assert "UpdateAlias" in operations
def test_payment_cryptography_shapes_widen_the_partition_the_model_writes():