diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats index 796d374097..c0f72681bc 100644 --- a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-key-exchange.bats @@ -9,10 +9,11 @@ setup() { load 'test_helper/common-setup' WRAPPING_ARN="" KEY_ARN="" + CREATED_ARNS="" } teardown() { - for key in "$WRAPPING_ARN" "$KEY_ARN"; do + for key in "$WRAPPING_ARN" "$KEY_ARN" $CREATED_ARNS; do if [ -n "$key" ]; then aws_cmd payment-cryptography delete-key --key-identifier "$key" \ --delete-key-in-days 7 >/dev/null 2>&1 || true @@ -36,6 +37,29 @@ create_key() { --query 'Key.KeyArn' --output text } +# The key that leaves the service in a TR-34 block. The block is wrapped under an RSA key, +# and the wrapping key has to be at least as strong as the key it protects, so the key is +# a Triple DES one. +create_tdes_key() { + aws_cmd payment-cryptography create-key \ + --key-attributes 'KeyAlgorithm=TDES_2KEY,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}' \ + --exportable \ + --query 'Key.KeyArn' --output text +} + +# The public half of a certificate, held by the service as the authority of the party it +# belongs to. The certificate is self-signed, so it comes in as a root certificate's key. +import_authority() { + local certificate="$1" + local algorithm="$2" + local arn + arn=$(aws_cmd payment-cryptography import-key \ + --key-material "RootCertificatePublicKey={KeyAttributes={KeyAlgorithm=$algorithm,KeyClass=PUBLIC_KEY,KeyUsage=TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE,KeyModesOfUse={Verify=true}},PublicKeyCertificate=$certificate}" \ + --query 'Key.KeyArn' --output text) + CREATED_ARNS="$CREATED_ARNS $arn" + echo "$arn" +} + @test "Payment Cryptography key exchange: the import parameters carry a token and a certificate" { run aws_cmd payment-cryptography get-parameters-for-import \ --key-material-type KEY_CRYPTOGRAM \ @@ -120,12 +144,59 @@ create_key() { CERTIFICATE=$(json_get "$output" '.WrappingKeyCertificate') [ -n "$CERTIFICATE" ] - # The TR-34 form is not one this service makes, so the request names the forms it does. + # Every form the model's union holds is one the service serves now, so the client names + # the forms it can ask for. run aws_cmd payment-cryptography export-key \ --export-key-identifier "$KEY_ARN" \ - --key-material "Tr34KeyBlock={CertificateAuthorityPublicKeyIdentifier=$KEY_ARN,WrappingKeyCertificate=$CERTIFICATE,KeyBlockFormat=X9_TR34_2012}" + --key-material "Nonsense={}" assert_failure - [[ "$output" == *"ValidationException"* ]] - # The refusal names the forms the service does serve. - [[ "$output" == *"Tr31KeyBlock, KeyCryptogram, DiffieHellmanTr31KeyBlock"* ]] + [[ "$output" == *"Tr31KeyBlock, Tr34KeyBlock, KeyCryptogram, DiffieHellmanTr31KeyBlock, As2805KeyCryptogram"* ]] +} + +@test "Payment Cryptography key exchange: a key leaves under a TR-34 block and comes back" { + # The parameters of the import name the certificate the block is wrapped under, and the + # parameters of the export name the certificate the block is signed with. + run aws_cmd payment-cryptography get-parameters-for-import \ + --key-material-type TR34_KEY_BLOCK \ + --wrapping-key-algorithm RSA_3072 + assert_success + IMPORT_TOKEN=$(json_get "$output" '.ImportToken') + WRAPPING_CERTIFICATE=$(json_get "$output" '.WrappingKeyCertificate') + [ -n "$IMPORT_TOKEN" ] + [ -n "$WRAPPING_CERTIFICATE" ] + + # The receiver's authority: the public half of the certificate the block is wrapped + # under. + RECEIVER_ARN=$(import_authority "$WRAPPING_CERTIFICATE" RSA_3072) + [ -n "$RECEIVER_ARN" ] + + run aws_cmd payment-cryptography get-parameters-for-export \ + --key-material-type TR34_KEY_BLOCK \ + --signing-key-algorithm RSA_2048 + assert_success + EXPORT_TOKEN=$(json_get "$output" '.ExportToken') + SIGNING_CERTIFICATE=$(json_get "$output" '.SigningKeyCertificate') + [ -n "$EXPORT_TOKEN" ] + [ -n "$SIGNING_CERTIFICATE" ] + + # The sender's authority: the public half of the certificate the block is signed with. + SENDER_ARN=$(import_authority "$SIGNING_CERTIFICATE" RSA_2048) + [ -n "$SENDER_ARN" ] + + KEY_ARN=$(create_tdes_key) + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography export-key \ + --export-key-identifier "$KEY_ARN" \ + --key-material "Tr34KeyBlock={CertificateAuthorityPublicKeyIdentifier=$RECEIVER_ARN,WrappingKeyCertificate=$WRAPPING_CERTIFICATE,ExportToken=$EXPORT_TOKEN,KeyBlockFormat=X9_TR34_2012,RandomNonce=A1B2C3D4E5F60718}" + assert_success + [ "$(json_get "$output" '.WrappedKey.WrappedKeyMaterialFormat')" = "TR34_KEY_BLOCK" ] + BLOCK=$(json_get "$output" '.WrappedKey.KeyMaterial') + [ -n "$BLOCK" ] + + run aws_cmd payment-cryptography import-key \ + --key-material "Tr34KeyBlock={CertificateAuthorityPublicKeyIdentifier=$SENDER_ARN,SigningKeyCertificate=$SIGNING_CERTIFICATE,ImportToken=$IMPORT_TOKEN,WrappedKeyBlock=$BLOCK,KeyBlockFormat=X9_TR34_2012,RandomNonce=A1B2C3D4E5F60718}" + assert_success + [ -n "$(json_get "$output" '.Key.KeyArn')" ] + [ "$(json_get "$output" '.Key.KeyAttributes.KeyUsage')" = "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY" ] } diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java index 8abed2196a..a2dd970136 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java @@ -28,6 +28,7 @@ import software.amazon.awssdk.services.paymentcryptography.model.KeyState; import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; import software.amazon.awssdk.services.paymentcryptography.model.ListKeysResponse; import software.amazon.awssdk.services.paymentcryptography.model.Tag; +import software.amazon.awssdk.services.paymentcryptography.model.Tr34KeyBlockFormat; import software.amazon.awssdk.services.paymentcryptography.model.WrappedKeyMaterialFormat; import java.io.ByteArrayInputStream; @@ -594,4 +595,66 @@ class PaymentCryptographyTest { new JcaContentSignerBuilder("SHA256withRSA").build(issuer.getPrivate()))); } + @Test + void anExportSigningKeyThatIsNotRsa2048IsRefused() { + // The block is signed with the key the export parameters issue, and the block's + // signature is an RSA one, so a signing key that is not an RSA_2048 one cannot + // sign it. + assertThatThrownBy(() -> client.getParametersForExport(r -> r + .keyMaterialType(KeyMaterialType.TR34_KEY_BLOCK) + .signingKeyAlgorithm(KeyAlgorithm.ECC_NIST_P256))) + .isInstanceOf(AwsServiceException.class) + .satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails() + .errorCode()).isEqualTo("ValidationException")); + } + + @Test + void aKeyLeavesTheServiceAndComesBackThroughATr34KeyBlock() { + // The parameters of the import name the certificate the block is wrapped under, and + // the parameters of the export name the certificate the block is signed with. + GetParametersForImportResponse importParameters = client.getParametersForImport(r -> r + .keyMaterialType(KeyMaterialType.TR34_KEY_BLOCK) + .wrappingKeyAlgorithm(KeyAlgorithm.RSA_2048)); + GetParametersForExportResponse exportParameters = client.getParametersForExport(r -> r + .keyMaterialType(KeyMaterialType.TR34_KEY_BLOCK) + .signingKeyAlgorithm(KeyAlgorithm.RSA_2048)); + + // Each certificate is the authority of the party it belongs to. + Key receiver = importPublicKey(importParameters.wrappingKeyCertificate()); + Key sender = importPublicKey(exportParameters.signingKeyCertificate()); + + Key key = createTdesKey(); + + ExportKeyResponse exported = client.exportKey(r -> r + .exportKeyIdentifier(key.keyArn()) + .keyMaterial(m -> m.tr34KeyBlock(b -> b + .certificateAuthorityPublicKeyIdentifier(receiver.keyArn()) + .wrappingKeyCertificate(importParameters.wrappingKeyCertificate()) + .exportToken(exportParameters.exportToken()) + .keyBlockFormat(Tr34KeyBlockFormat.X9_TR34_2012) + .randomNonce("A1B2C3D4E5F60718")))); + + assertThat(exported.wrappedKey().wrappedKeyMaterialFormat()) + .isEqualTo(WrappedKeyMaterialFormat.TR34_KEY_BLOCK); + assertThat(exported.wrappedKey().keyMaterial()).isNotBlank(); + + ImportKeyResponse imported = client.importKey(r -> r + .keyMaterial(m -> m.tr34KeyBlock(b -> b + .certificateAuthorityPublicKeyIdentifier(sender.keyArn()) + .signingKeyCertificate(exportParameters.signingKeyCertificate()) + .importToken(importParameters.importToken()) + .wrappedKeyBlock(exported.wrappedKey().keyMaterial()) + .keyBlockFormat(Tr34KeyBlockFormat.X9_TR34_2012) + .randomNonce("A1B2C3D4E5F60718")))); + + assertThat(imported.key().keyArn()).isNotBlank(); + assertThat(imported.key().keyAttributes().keyUsage()) + .isEqualTo(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY); + // The key that comes back is the key that left, so its check value is the one the + // exported key had. + assertThat(imported.key().keyCheckValue()).isEqualTo(key.keyCheckValue()); + // The key came into the service, so the cleanup has to take it away again. + keyArns.add(imported.key().keyArn()); + } + } diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index 77d60c1f13..e0ab284a94 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -74,9 +74,10 @@ and `NextToken`, and answer with one page and the token that asks for the next. - **The key exchange:** `ExportKey` and `ImportKey` take the form of the key material the request names, one form per request. A key leaves under a TR-31 block the service wraps - with a key it holds, under an RSA-OAEP cryptogram the receiver's certificate protects, or - under a key the two parties agreed with ECDH; it comes back under the same protections, and - a public key comes back under the certificate that carries it. A key that is not exportable + with a key it holds, under an RSA-OAEP cryptogram the receiver's certificate protects, under + a TR-34 key block the service signs and wraps for the receiver, or under a key the two + parties agreed with ECDH; it comes back under the same protections, and a public key comes + back under the certificate that carries it. A key that is not exportable does not leave, a key pair has no material a key block could carry, and a counterparty's certificate that the named authority did not sign is refused. An export may name an initial DUKPT key by its serial number, and the derived key leaves instead of the base derivation @@ -96,9 +97,40 @@ is capped by the curve's strength, so P-256 carries no AES-192. - **The check value of an export:** a key block carries the check value of the key it carries, and a cryptogram carries none, because it carries no key block at all. -- **The TR-34 and the AS2805 forms are not made.** A request that asks for one of them is - refused with the error that says so, rather than answered with something of another kind, - and the refusal names the forms the service serves. +- **The TR-34 key block:** a key leaves under a TR-31 block the service signs with its signing + key and wraps for the receiver under the receiver's certificate, in the `X9_TR34_2012` + format, and comes back the same way. The block carries the TR-31 header in the clear, the + nonce the two passes agree on, and the digest of the envelope it wraps, all under the + signature of the signing certificate, which has to chain to the named authority and be + inside its validity window. The block names its recipient by the receiver's certificate, + so the receiver can tell which of its keys the block is for. A block whose signature does + not verify, whose digest does not match, whose nonce is not the one the request quotes, + or that carries no header to say what it holds is refused. +- **The cipher of a TR-34 block:** the key block is enciphered with the cipher the key needs, + as the reference does, so a key is never protected by something weaker than itself: a + Triple DES key under Triple DES and an AES key under AES-128. The key a block may carry is + therefore the one the guide's matrix allows for a receiver's certificate, which is a Triple + DES key or an AES-128 key, and an AES-128 key needs a receiver whose certificate is + RSA-3072 or RSA-4096. +- **The signing key of a TR-34 block:** the service signs the block with the key the export + parameters issued, so the export has to name the export token they issued, and a request + that names its own signing key is refused. The signing key is an RSA one, because the + block's signature is an RSA signature, so `GetParametersForExport` takes `RSA_2048` and + refuses the other algorithms. +- **The token of a TR-34 block:** the import has to name the import token the import + parameters issued, and a request that names none, or that names a wrapping key instead, + is refused with the reason rather than with a key that is not found. +- **The headers a TR-34 export names:** a request may narrow the modes of use and the + exportability of the key, and the header the block carries says so, the same as it does + for a TR-31 block. A TR-34 block's header names the key and carries nothing else, so a + request that names optional blocks is refused. +- **The nonce of a TR-34 block:** the nonce binds the block to the exchange, and it is + optional in the model, so a block made without one is read without the freshness it + carries. A request that names no nonce expects a block that carries none, so a block that + carries one may not come in under a request that names none. +- **The AS2805 form is not made.** A request that asks for it is refused with the error that + says so, rather than answered with something of another kind, and the refusal names the + forms the service serves. - **The block headers a request names:** an export may name the modes of use, the exportability, the version and the optional blocks of the TR-31 block it produces, and the block carries them. An optional block is written with its length in hexadecimal, and diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java index 13aa65061d..449fb400ec 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchange.java @@ -6,6 +6,7 @@ import io.floci.aws.services.paymentcryptography.crypto.Certificates; import io.floci.aws.services.paymentcryptography.crypto.ConcatKdf; import io.floci.aws.services.paymentcryptography.crypto.Ecdh; import io.floci.aws.services.paymentcryptography.crypto.RsaOaep; +import io.floci.aws.services.paymentcryptography.crypto.Tr34; import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey; import org.bouncycastle.asn1.x500.X500Name; @@ -48,8 +49,6 @@ import java.util.concurrent.ConcurrentHashMap; * receiver under their certificate. *
The import takes the same forms and two more: a root or trusted public key may arrive
@@ -65,22 +64,28 @@ final class PaymentCryptographyKeyExchange {
static final List A TR-34 block carries the header in the clear beside the encrypted key block, so the
+ * receiver knows what the key is before it opens the block. The header uses the layout
+ * the TR-31 standard fixes: the type is always {@code D} (the reference does not use
+ * the type to name the cipher in a TR-34 block), and the rest names the key the block
+ * carries.
+ *
+ * The length field is the placeholder the reference writes, because it is ignored in a
+ * TR-34 block: what the block carries is the key, not a block of a length the receiver
+ * would have to compute.
+ *
+ * @param key the key under export
+ * @return the sixteen-character header, followed by the optional blocks it carries
+ */
+ private static String tr31Header(PaymentCryptographyKey key, Map A TR-34 block is a PKCS#7 SignedData whose content is an EnvelopedData:
+ *
+ * The shape is the one the service's own reference sample writes and the one the service
+ * reads: an {@code X9_TR34_2012} key block.
+ *
+ * The ASN.1 is BouncyCastle's and the cryptography is the JDK's; no tag and no length is
+ * written by hand here.
+ */
+public final class Tr34 {
+
+ /** The signed data content type: 1.2.840.113549.1.7.2. */
+ private static final ASN1ObjectIdentifier OID_SIGNED_DATA =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.7.2");
+
+ /** The enveloped data content type: 1.2.840.113549.1.7.3. */
+ private static final ASN1ObjectIdentifier OID_ENVELOPED_DATA =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.7.3");
+
+ /** The data content type: 1.2.840.113549.1.7.1. */
+ private static final ASN1ObjectIdentifier OID_DATA =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.7.1");
+
+ /** The content type attribute: 1.2.840.113549.1.9.3. */
+ private static final ASN1ObjectIdentifier OID_CONTENT_TYPE =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.9.3");
+
+ /** The message digest attribute: 1.2.840.113549.1.9.4. */
+ private static final ASN1ObjectIdentifier OID_MESSAGE_DIGEST =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.9.4");
+
+ /** The two-pass nonce attribute: 1.2.840.113549.1.9.25.3. */
+ private static final ASN1ObjectIdentifier OID_RANDOM_NONCE =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.9.25.3");
+
+ /** The RSA encryption algorithm: 1.2.840.113549.1.1.1. */
+ private static final ASN1ObjectIdentifier OID_RSA_ENCRYPTION =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.1.1");
+
+ /** The RSAES-OAEP key transport algorithm: 1.2.840.113549.1.1.7. */
+ private static final ASN1ObjectIdentifier OID_RSAES_OAEP =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.1.7");
+
+ /** The MGF1 key transport algorithm: 1.2.840.113549.1.1.8. */
+ private static final ASN1ObjectIdentifier OID_MGF1 =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.1.8");
+
+ /** The P source algorithm: 1.2.840.113549.1.1.9. */
+ private static final ASN1ObjectIdentifier OID_P_SPECIFIED =
+ new ASN1ObjectIdentifier("1.2.840.113549.1.1.9");
+
+ /** The SHA-256 digest algorithm: 2.16.840.1.101.3.4.2.1. */
+ private static final ASN1ObjectIdentifier OID_SHA256 =
+ new ASN1ObjectIdentifier("2.16.840.1.101.3.4.2.1");
+
+ /** The Triple DES in CBC mode content encryption: 1.2.840.113549.3.7. */
+ private static final ASN1ObjectIdentifier OID_DES_EDE3_CBC =
+ new ASN1ObjectIdentifier("1.2.840.113549.3.7");
+
+ /** The AES-128 in CBC mode content encryption: 2.16.840.1.101.3.4.1.2. */
+ private static final ASN1ObjectIdentifier OID_AES_128_CBC =
+ new ASN1ObjectIdentifier("2.16.840.1.101.3.4.1.2");
+
+ /**
+ * The order the signed attributes are written in.
+ *
+ * A signed attribute set has no order of its own, but the bytes a signature covers do.
+ * The reference writes the attributes in this order, so that is the order this writes
+ * them in, and the order a block that arrives is read back in.
+ */
+ private static final List This is the mirror of {@link #recoverAndVerify}: what that recovers, this produces.
+ *
+ * @param clearKey the key under export
+ * @param tr31Header the key's TR-31 header, in the clear
+ * @param nonce the random nonce the two passes agree on, or null
+ * @param signingKey the service's signing key
+ * @param wrappingKey the receiver's public key, which the ephemeral key is wrapped under
+ * @return the TR-34 block, as the bytes of a PKCS#7 SignedData
+ */
+ public static byte[] build(byte[] clearKey, String tr31Header, byte[] nonce,
+ PrivateKey signingKey, PublicKey wrappingKey) {
+ return build(clearKey, tr31Header, nonce, signingKey, wrappingKey, null, null);
+ }
+
+ /**
+ * Build a TR-34 key block, naming the receiver by its certificate.
+ *
+ * @param receiverCertDer the receiver's certificate in DER. Its issuer and serial number
+ * name the recipient, the way the service's own sample does.
+ * @see #build(byte[], String, byte[], PrivateKey, PublicKey)
+ */
+ public static byte[] build(byte[] clearKey, String tr31Header, byte[] nonce,
+ PrivateKey signingKey, PublicKey wrappingKey,
+ byte[] receiverCertDer) {
+ return build(clearKey, tr31Header, nonce, signingKey, wrappingKey, receiverCertDer, null);
+ }
+
+ /**
+ * Build a TR-34 key block, naming both parties by their certificates.
+ *
+ * The recipient is named by the receiver's certificate, and the signer by the signing
+ * certificate, both as an issuer and a serial number. That is how the service's own sample
+ * writes a block, so a block built here is shaped like one a real host produces.
+ *
+ * @param receiverCertDer the receiver's certificate in DER, or null to leave the recipient
+ * unnamed
+ * @param signerCertDer the signing certificate in DER, or null to leave the signer unnamed
+ * @see #build(byte[], String, byte[], PrivateKey, PublicKey)
+ */
+ public static byte[] build(byte[] clearKey, String tr31Header, byte[] nonce,
+ PrivateKey signingKey, PublicKey wrappingKey,
+ byte[] receiverCertDer, byte[] signerCertDer) {
+ return build(clearKey, tr31Header, nonce, signingKey, wrappingKey, receiverCertDer,
+ signerCertDer, false);
+ }
+
+ /**
+ * Build a TR-34 key block, whose key block is enciphered with the key's own cipher.
+ *
+ * The content encryption follows the key the block carries, as the reference does: a
+ * Triple DES key is enciphered with Triple DES and an AES key with AES-128, so that the
+ * key is never protected by a cipher weaker than itself.
+ *
+ * @param clearKey the key the block carries
+ * @param tr31Header the TR-31 header that names the key
+ * @param nonce the two-pass nonce, or null for a one-pass block, which carries no nonce
+ * attribute
+ * @param signingKey the signing key of the host
+ * @param wrappingKey the receiver's public key
+ * @param receiverCertDer the receiver's certificate in DER, or null to leave the recipient
+ * unnamed
+ * @param signerCertDer the signing certificate in DER, or null to leave the signer unnamed
+ * @param aes whether the key the block carries is an AES one
+ * @return the block
+ */
+ public static byte[] build(byte[] clearKey, String tr31Header, byte[] nonce,
+ PrivateKey signingKey, PublicKey wrappingKey,
+ byte[] receiverCertDer, byte[] signerCertDer, boolean aes) {
+ byte[] header = tr31Header.getBytes(StandardCharsets.US_ASCII);
+
+ // The key block: [version, the host's identifier, the key, the header attribute].
+ ASN1EncodableVector keyBlock = new ASN1EncodableVector();
+ keyBlock.add(new ASN1Integer(1));
+ keyBlock.add(certificateId(signerCertDer));
+ keyBlock.add(new DEROctetString(clearKey));
+ keyBlock.add(attribute(OID_DATA, new DEROctetString(header)));
+
+ // An ephemeral key enciphers the block, and the receiver's public key wraps the
+ // ephemeral key. The cipher is the one the key the block carries needs, so that the
+ // key is not protected by something weaker than itself.
+ SecureRandom random = new SecureRandom();
+ byte[] ephemeral = new byte[aes ? EPHEMERAL_AES_KEY_SIZE : EPHEMERAL_TDES_KEY_SIZE];
+ random.nextBytes(ephemeral);
+ byte[] iv = new byte[aes ? AES_BLOCK_SIZE : TDES_BLOCK_SIZE];
+ random.nextBytes(iv);
+ byte[] padded = pad(encoded(new DERSequence(keyBlock)), aes ? AES_BLOCK_SIZE : TDES_BLOCK_SIZE);
+ byte[] encryptedBlock = aes
+ ? Ciphers.aesCbcEncrypt(padded, ephemeral, iv)
+ : Ciphers.tdesCbcEncrypt(padded, Ciphers.widenTdesKey(ephemeral), iv);
+ byte[] encryptedEphemeral = RsaOaep.encrypt(wrappingKey, ephemeral, "SHA-256");
+
+ // The recipient information: the receiver's certificate identifier, the algorithm the
+ // ephemeral key was wrapped under, and the wrapped key itself.
+ ASN1EncodableVector recipientInfo = new ASN1EncodableVector();
+ recipientInfo.add(new ASN1Integer(0));
+ recipientInfo.add(certificateId(receiverCertDer));
+ recipientInfo.add(keyTransport());
+ recipientInfo.add(new DEROctetString(encryptedEphemeral));
+
+ // The encrypted content: the algorithm, the vector it was encrypted under, and the
+ // encrypted block.
+ ASN1EncodableVector contentEncryption = new ASN1EncodableVector();
+ contentEncryption.add(aes ? OID_AES_128_CBC : OID_DES_EDE3_CBC);
+ contentEncryption.add(new DEROctetString(iv));
+ contentEncryption.add(new DERTaggedObject(false, 0, new DEROctetString(encryptedBlock)));
+
+ ASN1EncodableVector encryptedContentInfo = new ASN1EncodableVector();
+ encryptedContentInfo.add(OID_DATA);
+ encryptedContentInfo.add(new DERSequence(contentEncryption));
+
+ // The envelope is three elements, not a SEQUENCE: the version, the recipients and the
+ // encrypted content. That is the shape the reference writes and the shape the reader
+ // takes.
+ byte[] envelope = concat(encoded(new ASN1Integer(0)),
+ encoded(new DERSet(new DERSequence(recipientInfo))),
+ encoded(new DERSequence(encryptedContentInfo)));
+
+ // The signed attributes: what the signature covers. The header travels in the clear,
+ // so a block cannot carry one header outside and another inside.
+ ASN1EncodableVector attributes = new ASN1EncodableVector();
+ attributes.add(attribute(OID_CONTENT_TYPE, OID_ENVELOPED_DATA));
+ // A block with a nonce is a two-pass block, and one without is a one-pass block,
+ // which carries no nonce attribute at all.
+ if (nonce != null) {
+ attributes.add(attribute(OID_RANDOM_NONCE, new DEROctetString(nonce)));
+ }
+ attributes.add(attribute(OID_DATA, new DEROctetString(header)));
+ attributes.add(attribute(OID_MESSAGE_DIGEST, new DEROctetString(digest(envelope))));
+
+ byte[] signature = sign(signingKey, signedAttributes(attributes));
+
+ // The signer: the host's identifier, the digest algorithm, the attributes, the
+ // signature algorithm and the signature.
+ ASN1EncodableVector signerInfo = new ASN1EncodableVector();
+ signerInfo.add(new ASN1Integer(1));
+ signerInfo.add(certificateId(signerCertDer));
+ signerInfo.add(new AlgorithmIdentifier(OID_SHA256));
+ signerInfo.add(new DERTaggedObject(false, 0, new DERSequence(attributes)));
+ signerInfo.add(new AlgorithmIdentifier(OID_RSA_ENCRYPTION, DERNull.INSTANCE));
+ signerInfo.add(new DEROctetString(signature));
+
+ ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
+ digestAlgorithms.add(new AlgorithmIdentifier(OID_SHA256));
+
+ ASN1EncodableVector contentInfo = new ASN1EncodableVector();
+ contentInfo.add(OID_ENVELOPED_DATA);
+ contentInfo.add(new DERTaggedObject(true, 0, new DEROctetString(envelope)));
+
+ ASN1EncodableVector signerInfos = new ASN1EncodableVector();
+ signerInfos.add(new DERSequence(signerInfo));
+
+ ASN1EncodableVector signedData = new ASN1EncodableVector();
+ signedData.add(new ASN1Integer(1));
+ signedData.add(new DERSet(digestAlgorithms));
+ signedData.add(new DERSequence(contentInfo));
+ signedData.add(new DERSet(signerInfos));
+
+ ASN1EncodableVector payload = new ASN1EncodableVector();
+ payload.add(OID_SIGNED_DATA);
+ payload.add(new DERTaggedObject(true, 0, new DERSequence(signedData)));
+ return encoded(new DERSequence(payload));
+ }
+
+ /**
+ * Recover and verify a TR-34 key block.
+ *
+ * The checks are, in order: the signing certificate has to chain to the registered
+ * authority, the signature over the signed attributes has to verify, the digest the
+ * attributes carry has to be the digest of the envelope, the nonce has to be the one the
+ * request quotes, the ephemeral key has to unwrap under the import key, and the header in
+ * the clear has to be the one inside the block.
+ *
+ * @param payloadHex the block, in hexadecimal
+ * @param importPrivateKey the private key the import token holds
+ * @param signingCertPem the certificate of the host that signed the block
+ * @param caPublicKey the registered authority's public key, or null to skip the chain check
+ * @param randomNonceHex the nonce supplied alongside the payload, or null to skip that check
+ * @return the clear key and the header it carried
+ * @throws IllegalArgumentException describing the first check that failed
+ */
+ public static Recovered recoverAndVerify(String payloadHex, PrivateKey importPrivateKey,
+ String signingCertPem, PublicKey caPublicKey,
+ String randomNonceHex) {
+ byte[] der = HEX.parseHex(payloadHex.trim());
+ ASN1Sequence contentInfo = ASN1Sequence.getInstance(der);
+ ASN1ObjectIdentifier contentType = ASN1ObjectIdentifier.getInstance(contentInfo.getObjectAt(0));
+ if (!OID_SIGNED_DATA.equals(contentType)) {
+ throw new IllegalArgumentException("the payload is not a signed TR-34 block");
+ }
+ ASN1Sequence signedData = ASN1Sequence.getInstance(
+ ASN1TaggedObject.getInstance(contentInfo.getObjectAt(1)), true);
+
+ // [version, digest algorithms, content info, signer infos]
+ ASN1Sequence encap = ASN1Sequence.getInstance(signedData.getObjectAt(2));
+ ASN1ObjectIdentifier encapType = ASN1ObjectIdentifier.getInstance(encap.getObjectAt(0));
+ if (!OID_ENVELOPED_DATA.equals(encapType)) {
+ throw new IllegalArgumentException("the TR-34 block does not carry an enveloped key");
+ }
+ byte[] envelope = ASN1OctetString.getInstance(
+ ASN1TaggedObject.getInstance(encap.getObjectAt(1)), true).getOctets();
+
+ ASN1Set signerInfos = ASN1Set.getInstance(signedData.getObjectAt(3));
+ ASN1Sequence signerInfo = ASN1Sequence.getInstance(signerInfos.getObjectAt(0));
+ // [version, signer id, digest algorithm, signed attributes, signature algorithm,
+ // signature]
+ ASN1Set signedAttributes = ASN1Set.getInstance(
+ ASN1TaggedObject.getInstance(signerInfo.getObjectAt(3)), false);
+ byte[] signature = ASN1OctetString.getInstance(signerInfo.getObjectAt(5)).getOctets();
+
+ // The envelope is three elements, not a SEQUENCE.
+ ASN1Integer envelopeVersion;
+ ASN1Set recipientInfos;
+ ASN1Sequence encryptedContentInfo;
+ try (ASN1InputStream stream = new ASN1InputStream(envelope)) {
+ envelopeVersion = ASN1Integer.getInstance(stream.readObject());
+ recipientInfos = ASN1Set.getInstance(stream.readObject());
+ encryptedContentInfo = ASN1Sequence.getInstance(stream.readObject());
+ } catch (IOException | IllegalArgumentException e) {
+ throw new IllegalArgumentException("the TR-34 envelope does not parse: "
+ + e.getMessage(), e);
+ }
+ if (envelopeVersion.intValueExact() != 0) {
+ throw new IllegalArgumentException("the TR-34 envelope is of version "
+ + envelopeVersion.intValueExact() + ", which this service does not read");
+ }
+
+ ASN1Sequence recipientInfo = ASN1Sequence.getInstance(recipientInfos.getObjectAt(0));
+ byte[] encryptedEphemeral = ASN1OctetString.getInstance(recipientInfo.getObjectAt(3))
+ .getOctets();
+
+ ASN1Sequence contentEncryption = ASN1Sequence.getInstance(encryptedContentInfo.getObjectAt(1));
+ ASN1ObjectIdentifier encryption = ASN1ObjectIdentifier.getInstance(
+ contentEncryption.getObjectAt(0));
+ boolean aes = OID_AES_128_CBC.equals(encryption);
+ if (!aes && !OID_DES_EDE3_CBC.equals(encryption)) {
+ throw new IllegalArgumentException("content encryption is neither 3DES-CBC nor "
+ + "AES-128-CBC (this service imports the two the reference writes)");
+ }
+ byte[] iv = ASN1OctetString.getInstance(contentEncryption.getObjectAt(1)).getOctets();
+ byte[] encryptedBlock = ASN1OctetString.getInstance(
+ ASN1TaggedObject.getInstance(contentEncryption.getObjectAt(2)), false).getOctets();
+
+ // The signing certificate has to chain to the registered authority, and it has to be
+ // inside its validity window: a certificate that has expired, or that is not valid
+ // yet, is not a certificate the authority vouches for now, so its key does not
+ // authenticate a block.
+ X509Certificate signingCertificate = Certificates.parseCertificate(signingCertPem);
+ try {
+ signingCertificate.checkValidity();
+ } catch (GeneralSecurityException e) {
+ throw new IllegalArgumentException("the signing certificate is outside its validity "
+ + "window: " + e.getMessage());
+ }
+ if (caPublicKey != null) {
+ try {
+ signingCertificate.verify(caPublicKey);
+ } catch (GeneralSecurityException e) {
+ throw new IllegalArgumentException("SigningKeyCertificate does not chain to the "
+ + "registered CertificateAuthorityPublicKeyIdentifier", e);
+ }
+ }
+
+ // The signature has to verify over the signed attributes.
+ if (!verifies(signedAttributes, signature, signingCertificate.getPublicKey())) {
+ throw new IllegalArgumentException("TR-34 authentication-data signature did not verify "
+ + "under the KDH certificate");
+ }
+
+ // The digest the attributes carry has to be the digest of the envelope.
+ byte[] digestAttribute = attributeValue(signedAttributes, OID_MESSAGE_DIGEST);
+ if (digestAttribute == null || !MessageDigest.isEqual(digestAttribute, digest(envelope))) {
+ throw new IllegalArgumentException("signed message-digest does not match the envelope "
+ + "(tamper or wrong content)");
+ }
+
+ // The two-pass nonce has to be the one the request quotes. A request that quotes
+ // none expects a block that carries none, so a block that carries one may not come
+ // in under a request that names no nonce. A block that carries no nonce attribute
+ // is a one-pass block, and it carries an empty one.
+ String quoted = randomNonceHex == null ? "" : randomNonceHex;
+ byte[] nonceAttribute = attributeValue(signedAttributes, OID_RANDOM_NONCE);
+ String carried = nonceAttribute == null ? "" : HEX_UPPER.formatHex(nonceAttribute);
+ if (!carried.equalsIgnoreCase(quoted)) {
+ throw new IllegalArgumentException(
+ "RandomNonce does not match the nonce in the signed payload");
+ }
+
+ // Recover the ephemeral key and read the block.
+ byte[] ephemeral;
+ try {
+ ephemeral = RsaOaep.decrypt(importPrivateKey, encryptedEphemeral, "SHA-256");
+ } catch (RuntimeException e) {
+ throw new IllegalArgumentException("ephemeral key did not unwrap under the import-token "
+ + "key (wrong token)", e);
+ }
+ byte[] clearBlock = aes
+ ? Ciphers.aesCbcDecrypt(encryptedBlock, ephemeral, iv)
+ : Ciphers.tdesCbcDecrypt(encryptedBlock, Ciphers.widenTdesKey(ephemeral), iv);
+
+ Recovered recovered = readKeyBlock(clearBlock);
+
+ // The header in the clear has to be the one inside the encrypted block, so a block
+ // cannot carry one header outside and another inside.
+ byte[] clearHeader = attributeValue(signedAttributes, OID_DATA);
+ if (clearHeader != null && clearHeader.length > 0) {
+ String inClear = new String(clearHeader, StandardCharsets.US_ASCII);
+ if (!inClear.equals(recovered.header)) {
+ throw new IllegalArgumentException("the key block header in the clear is '"
+ + inClear + "' but the one inside the encrypted block is '"
+ + recovered.header + "'");
+ }
+ }
+ return recovered;
+ }
+
+ /**
+ * The bytes a PKCS#7 signature covers: the signed attributes as a DER set.
+ *
+ * The attributes are a set, and a set's encoding sorts its elements, but the
+ * signature was made over the bytes the signer wrote, which are the attributes in the
+ * order it wrote them. BouncyCastle's set sorts and its BER set has no definite length,
+ * so the encoding is built as the sequence of the attributes and re-tagged as the set
+ * it is: the two differ in that one tag byte.
+ *
+ * @param attributes the attributes, in the order they are written in
+ * @return the bytes a signature over the attributes is made over
+ */
+ private static byte[] signedAttributes(ASN1EncodableVector attributes) {
+ byte[] encoded = encoded(new DERSequence(attributes));
+ // The set's tag, where the sequence's tag was.
+ encoded[0] = 0x31;
+ return encoded;
+ }
+
+ /**
+ * Whether the signature verifies over the signed attributes.
+ *
+ * The attributes are a set, and a set has no order, but the bytes a signature covers
+ * do. BouncyCastle sorts a set when it reads one, so the order the signer used is gone
+ * by the time the attributes are parsed. The signature is therefore tried over both
+ * orders the set can be written in: the one the reference writes, and the sorted one a
+ * strictly DER encoder would write. Both carry the same attributes, so a block that
+ * verifies under either is authentic.
+ */
+ private static boolean verifies(ASN1Set signedAttributes, byte[] signature, PublicKey key) {
+ for (ASN1EncodableVector ordering : orderings(signedAttributes)) {
+ if (verifySignature(signedAttributes(ordering), signature, key)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /** The orders the signed attributes can be written in. */
+ private static List BouncyCastle declares the checked exception on the encoding, but an encoding that
+ * fails here would be a fault in this class rather than in anything the caller sent.
+ *
+ * @param value the value to encode
+ * @return the encoded bytes
+ */
+ private static byte[] encoded(ASN1Encodable value) {
+ try {
+ return value.toASN1Primitive().getEncoded();
+ } catch (IOException e) {
+ throw new IllegalStateException("the TR-34 structure could not be encoded: "
+ + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * The value the given bytes hold.
+ *
+ * @param der the encoded bytes
+ * @return the parsed value
+ */
+ private static ASN1Encodable decoded(byte[] der) {
+ try {
+ return ASN1Primitive.fromByteArray(der);
+ } catch (IOException e) {
+ throw new IllegalStateException("the TR-34 structure could not be parsed: "
+ + e.getMessage(), e);
+ }
+ }
+
+ /** The given byte arrays, one after the other. */
+ private static byte[] concat(byte[]... parts) { int length = 0;
+ for (byte[] part : parts) {
+ length += part.length;
+ }
+ byte[] out = new byte[length];
+ int offset = 0;
+ for (byte[] part : parts) {
+ System.arraycopy(part, 0, out, offset, part.length);
+ offset += part.length;
+ }
+ return out;
+ }
+}
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 a9d7616225..cc7a7418d9 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
@@ -231,15 +231,31 @@ class PaymentCryptographyIntegrationTest {
}
@Test
- void aRequestNamingAFormTheServiceDoesNotServeIsRefused() {
- // The TR-34 form is one the model has and this service does not make.
+ void theTr34FormIsServed() {
+ // The TR-34 form is one the service makes now, so a request that names one is
+ // refused for what it is missing and not for naming an unserved form.
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\"}}}")
+ + "\"Tr34KeyBlock\":{\"WrappingKeyCertificate\":\"x\","
+ + "\"KeyBlockFormat\":\"X9_TR34_2012\"}}}")
+ .then().statusCode(400)
+ .body("__type", equalTo("ValidationException"))
+ .body("message", containsString("CertificateAuthorityPublicKeyIdentifier"));
+ }
+
+ @Test
+ void aRequestNamingAFormTheServiceDoesNotServeIsRefused() {
+ // The AS2805 form is one the model has and this service does not make yet.
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ + "\"As2805KeyCryptogram\":{\"As2805KeyVariant\":"
+ + "\"PIN_ENCRYPTION_KEY_VARIANT_28\",\"WrappingKeyIdentifier\":\"" + arn + "\"}}}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("not a form the service exports"));
@@ -370,6 +386,48 @@ class PaymentCryptographyIntegrationTest {
* 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.
*/
+ @Test
+ void theModelCheckRefusesATr34ExportWithoutItsWrappingKeyCertificate() {
+ String arn = call("CreateKey", CREATE_KEY)
+ .then().statusCode(200)
+ .extract().path("Key.KeyArn");
+
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ + "\"Tr34KeyBlock\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\","
+ + "\"KeyBlockFormat\":\"X9_TR34_2012\"}}}");
+
+ assertTheModelRefused(answer, "WrappingKeyCertificate");
+ }
+
+ @Test
+ void theModelCheckRefusesATr34ExportWithoutItsCertificateAuthority() {
+ Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"KeyMaterial\":{\"Tr34KeyBlock\":{\"WrappingKeyCertificate\":\"x\","
+ + "\"KeyBlockFormat\":\"X9_TR34_2012\"}}}");
+
+ assertTheModelRefused(answer, "CertificateAuthorityPublicKeyIdentifier");
+ }
+
+ @Test
+ void theModelCheckRefusesATr34ImportWithoutItsSigningKeyCertificate() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"Tr34KeyBlock\":{"
+ + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"WrappedKeyBlock\":\"" + "0".repeat(64) + "\","
+ + "\"KeyBlockFormat\":\"X9_TR34_2012\"}}}");
+
+ assertTheModelRefused(answer, "SigningKeyCertificate");
+ }
+
+ @Test
+ void theModelCheckRefusesATr34ImportWithoutItsWrappedKeyBlock() {
+ Response answer = call("ImportKey", "{\"KeyMaterial\":{\"Tr34KeyBlock\":{"
+ + "\"CertificateAuthorityPublicKeyIdentifier\":\"" + keyArn() + "\","
+ + "\"SigningKeyCertificate\":\"x\","
+ + "\"KeyBlockFormat\":\"X9_TR34_2012\"}}}");
+
+ assertTheModelRefused(answer, "WrappedKeyBlock");
+ }
+
private static void assertTheModelRefused(Response answer, String member) {
answer.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java
index 52e1893534..b31683225c 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyExchangeTest.java
@@ -7,7 +7,9 @@ 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.PaymentCryptographyTr34RoundTripTest;
import io.floci.aws.services.paymentcryptography.crypto.RsaOaep;
+import io.floci.aws.services.paymentcryptography.crypto.Tr34;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import io.floci.aws.testing.ManualClock;
import org.junit.jupiter.api.BeforeEach;
@@ -414,6 +416,431 @@ class PaymentCryptographyKeyExchangeTest {
() -> service.exportKey("us-east-1", key.getKeyId(), "Nonsense", Map.of(), "", ""));
assertEquals("ValidationException", refused.getErrorCode());
}
+ /**
+ * The exchange a TR-34 block goes through.
+ *
+ * The parameters, the two authorities and the material of the export and of the
+ * import are built here, so that a change to the TR-34 request is made in one place
+ * and not in every test that makes a block.
+ *
+ * @param wrappingAlgorithm the algorithm of the receiver's key
+ */
+ private Tr34Exchange tr34Exchange(String wrappingAlgorithm) {
+ Map The service signs the blocks it makes, so a block that carries something the
+ * service would never write is put to it by a caller that signs its own.
+ *
+ * @param importParameters the import parameters, whose certificate the block is wrapped under
+ * @param header the TR-31 header the block carries
+ * @param clearKey the key the block carries
+ * @param aes whether the key is an AES one
+ * @return the block, the authority that vouches for its signature and the certificate
+ */
+ /**
+ * A TR-34 block the test builds and signs itself.
+ *
+ * The service signs the blocks it makes, so a block that carries something the
+ * service would never write is put to it by a caller that signs its own.
+ *
+ * @param exchange the exchange the block travels through
+ * @param header the TR-31 header the block carries
+ * @param clearKey the key the block carries
+ * @param aes whether the key is an AES one
+ * @return the block, the authority that vouches for its signature and the certificate
+ */
+ private Crafted craftedBlock(Tr34Exchange exchange, String header, byte[] clearKey,
+ boolean aes) throws Exception {
+ SecureRandom random = new SecureRandom();
+ KeyPair signer = PaymentCryptographyKeyPairs.rsa(2048, random);
+ Certificates.Minted certificate = CertificatesTest.mint(signer.getPublic(), "floci sender",
+ signer.getPrivate(), "floci sender");
+ PaymentCryptographyKey authority = createAuthority(certificate.pem());
+ X509Certificate wrapping = Certificates.parseCertificate(
+ (String) exchange.importParameters().get("WrappingKeyCertificate"));
+ byte[] block = Tr34.build(clearKey, header,
+ HexFormat.of().parseHex("A1B2C3D4E5F60718"), signer.getPrivate(),
+ wrapping.getPublicKey(), null, certificate.der(), aes);
+ return new Crafted(HexFormat.of().withUpperCase().formatHex(block), authority,
+ certificate.pem());
+ }
+
+ @Test
+ void aBlockThatWasSignedByAnotherAuthorityDoesNotOpen() {
+ Tr34Exchange exchange = tr34Exchange();
+ PaymentCryptographyKey key = createKey("TDES_2KEY",
+ "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
+
+ Map The two are the mirror of each other: what the builder produces, the verifier recovers.
+ * A block that one makes and the other cannot read is a block the service would reject.
+ */
+public class PaymentCryptographyTr34RoundTripTest {
+
+ /** The hexadecimal the block is written in. */
+ private static final HexFormat HEX = HexFormat.of();
+
+ /** The hexadecimal the block is written in, in the capitals the service uses. */
+ private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase();
+
+ @Test
+ void buildsWhatTheVerifierRecovers() throws Exception {
+ // The key receiving device: its key pair and its certificate.
+ KeyPair krd = rsaKeyPair();
+ // The key distribution host: the service's signing key and its certificate.
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] clear = HEX.parseHex("404142434445464748494A4B4C4D4E4F");
+ String header = "B0010P0TB00E0000";
+ byte[] nonce = HEX.parseHex("0102030405060708");
+
+ byte[] block = Tr34.build(clear, header, nonce, kdh.getPrivate(), krd.getPublic());
+ assertNotNull(block, "the block was not built");
+
+ Tr34.Recovered recovered = Tr34.recoverAndVerify(HEX_UPPER.formatHex(block),
+ krd.getPrivate(), kdhCertificate.pem(), null, HEX_UPPER.formatHex(nonce));
+
+ assertEquals(HEX_UPPER.formatHex(clear), recovered.keyHex);
+ assertEquals(header, recovered.header);
+ }
+
+ @Test
+ void carriesTheHeader() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "B0010P0TB00E0000", null, kdh.getPrivate(), krd.getPublic());
+
+ Tr34.Recovered recovered = Tr34.recoverAndVerify(HEX_UPPER.formatHex(block),
+ krd.getPrivate(), kdhCertificate.pem(), null, null);
+
+ assertEquals("B0010P0TB00E0000", recovered.header);
+ }
+
+ @Test
+ void namesBothPartiesByTheirCertificates() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted krdCertificate = CertificatesTest.mint(krd.getPublic(), "krd",
+ krd.getPrivate(), "krd");
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "B0010P0TB00E0000", null, kdh.getPrivate(), krd.getPublic(),
+ krdCertificate.der(), kdhCertificate.der());
+
+ Tr34.Recovered recovered = Tr34.recoverAndVerify(HEX_UPPER.formatHex(block),
+ krd.getPrivate(), kdhCertificate.pem(), null, null);
+
+ assertEquals(HEX_UPPER.formatHex(HEX.parseHex("404142434445464748494A4B4C4D4E4F")),
+ recovered.keyHex);
+ // The block names its recipient by the certificate's own issuer and serial number,
+ // so the receiver can tell which of its keys the block is for.
+ assertEquals(HexFormat.of().formatHex(Certificates.certificateId(krdCertificate.der())),
+ HexFormat.of().formatHex(recipientId(block)),
+ "the recipient the block names");
+ }
+
+ @Test
+ void refusesASigningCertificateThatHasExpired() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Instant past = Instant.now().minusSeconds(7200);
+ Instant expired = Instant.now().minusSeconds(3600);
+ Certificates.Minted expiredCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh", past, expired);
+
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "B0010P0TB00E0000", null, kdh.getPrivate(), krd.getPublic());
+
+ IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
+ () -> Tr34.recoverAndVerify(HEX_UPPER.formatHex(block), krd.getPrivate(),
+ expiredCertificate.pem(), null, null));
+ assertTrue(refused.getMessage().contains("validity window"), refused.getMessage());
+ }
+
+ @Test
+ void refusesASigningCertificateThatIsNotYetValid() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Instant future = Instant.now().plusSeconds(3600);
+ Instant later = Instant.now().plusSeconds(7200);
+ Certificates.Minted earlyCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh", future, later);
+
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "B0010P0TB00E0000", null, kdh.getPrivate(), krd.getPublic());
+
+ IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
+ () -> Tr34.recoverAndVerify(HEX_UPPER.formatHex(block), krd.getPrivate(),
+ earlyCertificate.pem(), null, null));
+ assertTrue(refused.getMessage().contains("validity window"), refused.getMessage());
+ }
+
+ @Test
+ void refusesABlockThatCarriesNoHeader() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ // The block is signed correctly, but its key block names no key: the header that
+ // says what the block carries is empty.
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "", null, kdh.getPrivate(), krd.getPublic());
+
+ IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
+ () -> Tr34.recoverAndVerify(HEX_UPPER.formatHex(block), krd.getPrivate(),
+ kdhCertificate.pem(), null, null));
+ assertTrue(refused.getMessage().contains("no TR-31 header"), refused.getMessage());
+ }
+
+ /**
+ * The header a block carries in the clear.
+ *
+ * The header travels in the clear beside the encrypted key block, so a reader sees
+ * what the block carries without opening it.
+ *
+ * @param block the block
+ * @return the header
+ */
+ public static String clearHeader(byte[] block) throws IOException {
+ ASN1Sequence contentInfo = ASN1Sequence.getInstance(block);
+ ASN1Sequence signedData = ASN1Sequence.getInstance(
+ ASN1TaggedObject.getInstance(contentInfo.getObjectAt(1)), true);
+ ASN1Set signerInfos = ASN1Set.getInstance(signedData.getObjectAt(3));
+ ASN1Sequence signerInfo = ASN1Sequence.getInstance(signerInfos.getObjectAt(0));
+ ASN1Set attributes = ASN1Set.getInstance(
+ ASN1TaggedObject.getInstance(signerInfo.getObjectAt(3)), false);
+ for (ASN1Encodable element : attributes) {
+ ASN1Sequence attribute = ASN1Sequence.getInstance(element);
+ if (!"1.2.840.113549.1.7.1".equals(
+ ASN1ObjectIdentifier.getInstance(attribute.getObjectAt(0)).getId())) {
+ continue;
+ }
+ ASN1Set values = ASN1Set.getInstance(attribute.getObjectAt(1));
+ return new String(ASN1OctetString.getInstance(values.getObjectAt(0)).getOctets(),
+ StandardCharsets.US_ASCII);
+ }
+ throw new IllegalStateException("the block carries no header in the clear");
+ }
+
+ /** The recipient identifier a block carries: the receiver's certificate identifier. */
+ private static byte[] recipientId(byte[] block) throws IOException {
+ ASN1Sequence contentInfo = ASN1Sequence.getInstance(block);
+ ASN1Sequence signedData = ASN1Sequence.getInstance(
+ ASN1TaggedObject.getInstance(contentInfo.getObjectAt(1)), true);
+ ASN1Sequence encap = ASN1Sequence.getInstance(signedData.getObjectAt(2));
+ byte[] envelope = ASN1OctetString.getInstance(
+ ASN1TaggedObject.getInstance(encap.getObjectAt(1)), true).getOctets();
+ try (ASN1InputStream stream = new ASN1InputStream(envelope)) {
+ stream.readObject();
+ ASN1Set recipients = ASN1Set.getInstance(stream.readObject());
+ ASN1Sequence recipient = ASN1Sequence.getInstance(recipients.getObjectAt(0));
+ // The identifier is the issuer and serial number of the receiver's certificate.
+ return ASN1Sequence.getInstance(recipient.getObjectAt(1)).getEncoded();
+ }
+ }
+
+ @Test
+ void anAesKeyIsEncipheredWithAes() throws Exception {
+ // The key block is enciphered with the cipher the key needs, so an AES key is not
+ // protected by something weaker than itself.
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] clear = HEX.parseHex("000102030405060708090A0B0C0D0E0F");
+ String header = "D9999D0AB00E0000";
+ byte[] nonce = HEX.parseHex("0102030405060708");
+
+ byte[] block = Tr34.build(clear, header, nonce, kdh.getPrivate(), krd.getPublic(),
+ null, kdhCertificate.der(), true);
+
+ // The content encryption is the AES one: 2.16.840.1.101.3.4.1.2.
+ assertTrue(HEX_UPPER.formatHex(block).contains("608648016503040102"),
+ "the block does not name the AES content encryption");
+
+ Tr34.Recovered recovered = Tr34.recoverAndVerify(HEX_UPPER.formatHex(block),
+ krd.getPrivate(), kdhCertificate.pem(), null, HEX_UPPER.formatHex(nonce));
+
+ assertEquals(HEX_UPPER.formatHex(clear), recovered.keyHex);
+ assertEquals(header, recovered.header);
+ }
+
+ @Test
+ void aKeyBlockIsReadWhateverFollowsIt() throws Exception {
+ // The bytes the cipher needed follow the key block, and a block whose plaintext was
+ // already a whole number of cipher blocks carries none of them, so the sequence is
+ // read from the front and the bytes after it are left alone.
+ ASN1EncodableVector elements = new ASN1EncodableVector();
+ elements.add(new ASN1Integer(1));
+ elements.add(new DERSequence(new ASN1Integer(0)));
+ elements.add(new DEROctetString(new byte[16]));
+ elements.add(new DERSequence(new ASN1ObjectIdentifier("1.2.840.113549.1.7.1"),
+ new DERSet(new DEROctetString(
+ "B0010P0TB00E0000".getBytes(StandardCharsets.US_ASCII)))));
+ byte[] keyBlock = new DERSequence(elements).getEncoded();
+
+ Tr34.Recovered recovered = Tr34.readKeyBlock(keyBlock);
+
+ assertEquals("B0010P0TB00E0000", recovered.header);
+ assertEquals(HEX_UPPER.formatHex(new byte[16]), recovered.keyHex);
+ }
+
+ @Test
+ void aOnePassBlockIsReadWithoutANonce() throws Exception {
+ // A block with no nonce is a one-pass block, and it carries no nonce attribute at
+ // all, which reads as an empty one.
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] clear = HEX.parseHex("404142434445464748494A4B4C4D4E4F");
+ String header = "B0010P0TB00E0000";
+
+ byte[] block = Tr34.build(clear, header, null, kdh.getPrivate(), krd.getPublic(),
+ null, kdhCertificate.der());
+
+ Tr34.Recovered recovered = Tr34.recoverAndVerify(HEX_UPPER.formatHex(block),
+ krd.getPrivate(), kdhCertificate.pem(), null, null);
+
+ assertEquals(HEX_UPPER.formatHex(clear), recovered.keyHex);
+ assertEquals(header, recovered.header);
+ }
+
+ @Test
+ void refusesATamperedBlock() throws Exception {
+ KeyPair krd = rsaKeyPair();
+ KeyPair kdh = rsaKeyPair();
+ Certificates.Minted kdhCertificate = CertificatesTest.mint(kdh.getPublic(), "kdh",
+ kdh.getPrivate(), "kdh");
+
+ byte[] block = Tr34.build(HEX.parseHex("404142434445464748494A4B4C4D4E4F"),
+ "B0010P0TB00E0000", null, kdh.getPrivate(), krd.getPublic());
+ block[block.length - 1] ^= 0x01;
+
+ try {
+ Tr34.recoverAndVerify(HEX_UPPER.formatHex(block), krd.getPrivate(), kdhCertificate.pem(),
+ null, null);
+ Assertions.fail("a tampered block was accepted");
+ } catch (RuntimeException expected) {
+ // The signature or the digest catches it.
+ }
+ }
+
+ /** An RSA key pair, for the device that receives the key. */
+ private static KeyPair rsaKeyPair() throws Exception {
+ KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
+ generator.initialize(2048);
+ return generator.generateKeyPair();
+ }
+}
+ *
+ *
+ *