feat(paymentcryptography): the TR-34 key block (#8136)

* feat(paymentcryptography): the TR-34 key block
* fix(paymentcryptography): the rules a TR-34 key block has to follow
* docs(paymentcryptography): what a TR-34 key block is
* test(paymentcryptography): the TR-34 round trip shows the key that came back
* test(paymentcryptography): one exchange for the TR-34 tests
* fix(paymentcryptography): the nonce and the token a TR-34 import names
* docs(paymentcryptography): the nonce and the token a TR-34 import names
* fix(paymentcryptography): a TR-34 key block is read whatever follows it
* fix(paymentcryptography): a TR-34 header carries the optional blocks
* chore(paymentcryptography): the imports of the round-trip test in order
* fix(paymentcryptography): the TR-34 header is the reference's header
* fix(paymentcryptography): the TR-34 header, stale comments
* fix(paymentcryptography): the TR-34 comments match the code
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-13 23:10:35 -04:00
1 parent 8185a340c4
commit 4cd8ab991e
10 files changed
+1928 -31

No files matched your search

@@ -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" ]
}
@@ -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());
}
}
+38 -6
View File
@@ -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
@@ -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.
* <li>{@code DiffieHellmanTr31KeyBlock}: a TR-31 key block under a key the two parties
* agreed with ECDH.
* <li>{@code As2805KeyCryptogram}: the key material under a key encryption key, bound to
* its purpose by the AS2805 variant.
* </ul>
*
* <p>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<String> EXPORT_FORMS = List.of(
"Tr31KeyBlock",
"KeyCryptogram",
"Tr34KeyBlock",
"DiffieHellmanTr31KeyBlock");
/** The forms the import takes, in the order the service lists them. */
static final List<String> IMPORT_FORMS = List.of(
"Tr31KeyBlock",
"KeyCryptogram",
"Tr34KeyBlock",
"RootCertificatePublicKey",
"TrustedCertificatePublicKey",
"DiffieHellmanTr31KeyBlock");
/** The key material types that take import parameters. */
private static final List<String> IMPORT_PARAMETER_TYPES = List.of("KEY_CRYPTOGRAM");
private static final List<String> IMPORT_PARAMETER_TYPES =
List.of("KEY_CRYPTOGRAM", "TR34_KEY_BLOCK");
/** The key material types that take export parameters. */
private static final List<String> EXPORT_PARAMETER_TYPES = List.of("TR34_KEY_BLOCK");
/** The material type an export token is issued for. */
private static final String EXPORT_MATERIAL_TYPE = "TR34_KEY_BLOCK";
/** The prefix an import token's name carries, as the model states it. */
private static final String IMPORT_TOKEN_PREFIX = "import-token-";
@@ -226,6 +231,7 @@ final class PaymentCryptographyKeyExchange {
return switch (form) {
case "Tr31KeyBlock" -> exportTr31(region, key, clear, material);
case "KeyCryptogram" -> exportCryptogram(region, key, clear, material);
case "Tr34KeyBlock" -> exportTr34(region, key, clear, material);
case "DiffieHellmanTr31KeyBlock" -> exportEcdh(region, key, clear, material);
default -> throw validation("KeyMaterial." + form + " is not a form the service exports ("
+ String.join(", ", EXPORT_FORMS) + ")");
@@ -338,6 +344,7 @@ final class PaymentCryptographyKeyExchange {
return switch (form) {
case "Tr31KeyBlock" -> importTr31(region, material);
case "KeyCryptogram" -> importCryptogram(material);
case "Tr34KeyBlock" -> importTr34(region, material);
case "RootCertificatePublicKey" -> importPublicKey(region, material, "");
case "TrustedCertificatePublicKey" -> importPublicKey(region, material,
text(material, "CertificateAuthorityPublicKeyIdentifier"));
@@ -746,6 +753,47 @@ final class PaymentCryptographyKeyExchange {
return PaymentCryptographyKeyRules.material(key);
}
/**
* The TR-31 header a key leaves the service in, in the clear.
*
* <p>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.
*
* <p>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<String, Object> headers) {
// The usage code and the exportability are the ones the TR-31 block carries, so a
// key that leaves under a TR-34 block is named the same way as one that leaves
// under a TR-31 block. The usage code of a key, and not of its usage name, is what
// the initial derivation key has a code of its own for.
String usage = PaymentCryptographyService.usageCode(key);
String algorithm = PaymentCryptographyService.algorithmByte(key);
// The modes of use and the exportability the request names may only narrow the ones
// the key has, the same as they do in a TR-31 block.
String mode = modeCode(key, headers);
String exportability = exportabilityCode(key, headers);
String version = versionCode(headers);
List<String[]> blocks = optionalBlocks(headers);
// The version is the request's KeyVersion, 00 when it names none, as
// ExportTr34KeyBlock allows. The optional blocks follow the header, each its
// identifier over two characters, its length over two and then its value, the way a
// TR-31 block carries them, and the padding block that keeps the header a whole
// number of cipher blocks is the last of them.
List<String[]> padded = PaymentCryptographyTr31.withPadding(blocks,
"A".equals(algorithm) ? 16 : 8);
String header = PaymentCryptographyTr31.header16("D", usage, mode, exportability,
9999, algorithm, version, padded.size());
return header + PaymentCryptographyTr31.optionalBlocks(padded);
}
/** The modes of use the attributes name, as the service reads them. */
private static Map<String, Boolean> modesOf(Map<String, Object> attributes) {
Map<String, Boolean> modes = new LinkedHashMap<>();
@@ -1043,7 +1091,7 @@ final class PaymentCryptographyKeyExchange {
Map<String, Object> parametersForImport(String materialType, String algorithm, boolean reuse) {
if (!IMPORT_PARAMETER_TYPES.contains(materialType)) {
throw validation("KeyMaterialType '" + materialType + "' does not take import "
+ "parameters here (KEY_CRYPTOGRAM)");
+ "parameters here (" + String.join(", ", IMPORT_PARAMETER_TYPES) + ")");
}
String wrappingAlgorithm = algorithm.isEmpty() ? "RSA_2048" : algorithm;
Integer bits = RSA_BITS.get(wrappingAlgorithm);
@@ -1102,9 +1150,13 @@ final class PaymentCryptographyKeyExchange {
+ "parameters here (" + String.join(", ", EXPORT_PARAMETER_TYPES) + ")");
}
PaymentCryptographyKeyAlgorithm signing = PaymentCryptographyKeyAlgorithm.from(algorithm);
if (signing == null || signing.symmetric()) {
if (signing != PaymentCryptographyKeyAlgorithm.RSA_2048) {
// The TR-34 block is signed with the key these parameters issue, and the block's
// signature is an RSA one, so a signing key that is not an RSA key cannot sign
// it. The model says the same: RSA_2048 is the only signing key algorithm
// allowed.
throw validation("SigningKeyAlgorithm '" + algorithm + "' not supported "
+ "(RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384, ECC_NIST_P521)");
+ "(RSA_2048): a TR-34 key block is signed with RSA_2048");
}
String last = materialType + "/" + algorithm;
Issued previous = lastExportParameters.get(last);
@@ -1112,9 +1164,7 @@ final class PaymentCryptographyKeyExchange {
return exportParameters(previous);
}
long now = clock.millis();
KeyPair pair = signing.rsa
? PaymentCryptographyKeyPairs.rsa(signing.bytes * 8, random)
: PaymentCryptographyKeyPairs.ec(signing, random);
KeyPair pair = PaymentCryptographyKeyPairs.rsa(signing.bytes * 8, random);
// The certificate lives as long as the token, so the parameters never hand out a
// certificate that has expired.
Certificates.Minted certificate = mintSelfSigned(pair, "floci key-export KRD",
@@ -1173,4 +1223,133 @@ final class PaymentCryptographyKeyExchange {
null, Base64.getEncoder().encodeToString(publicKey.getEncoded()), null,
certificatePem(certText), "PUBLIC_KEY");
}
/** A TR-34 key block: the key signed by the service and wrapped for the receiver. */
private Exported exportTr34(String region, PaymentCryptographyKey key, byte[] clear,
Map<String, Object> material) {
// The shape check settles the members the model requires and the values it names,
// so the authority, the certificate and the format are there.
String caIdentifier = text(material, "CertificateAuthorityPublicKeyIdentifier");
PaymentCryptographyKey caKey = usableKey(caIdentifier, region);
String certText = text(material, "WrappingKeyCertificate");
X509Certificate receiver = verifiedCertificate(certText, caKey,
"the wrapping key certificate");
PublicKey wrappingKey = receiver.getPublicKey();
int modulusBits = modulusBitsOf(wrappingKey);
String tooWeak = PaymentCryptographyKeyStrength.refusal(
PaymentCryptographyKeyStrength.rsaBitsOf(modulusBits),
PaymentCryptographyKeyStrength.bitsOf(key.getKeyAlgorithm()),
"RSA_" + modulusBits, key.getKeyAlgorithm());
if (tooWeak != null) {
throw validation(tooWeak);
}
String token = text(material, "ExportToken");
if (token.isEmpty()) {
// The service signs the block with the key the export parameters issued, so the
// request has to name the token they issued. A request that names its own
// signing key is refused rather than answered with a key that is not found.
throw validation("a TR-34 key block is signed with the key the export parameters "
+ "issued, so the request must name the export token they issued; this "
+ "service does not sign a block with a key the request names");
}
Issued signing = take(exportTokens, token, EXPORT_MATERIAL_TYPE);
if (signing == null) {
throw notFound(token);
}
String nonce = text(material, "RandomNonce");
if (!nonce.isEmpty() && !isHex(nonce)) {
throw validation("KeyMaterial.Tr34KeyBlock.RandomNonce must be hexadecimal");
}
// The headers the request names are the ones the block carries, the optional
// blocks among them.
Map<String, Object> headers = object(material, "KeyBlockHeaders");
String header = tr31Header(key, headers);
// The block names its recipient: the receiver's certificate identifier is the
// issuer and serial number of the certificate the request brought. And the key
// block is enciphered with the cipher the key needs, so that the key is not
// protected by something weaker than itself.
byte[] block = Tr34.build(clear, header, nonce.isEmpty() ? null : HEX.parseHex(nonce),
signing.privateKey, wrappingKey, Certificates.toDer(receiver),
signing.certificateDer, PaymentCryptographyService.isAes(key));
return new Exported(HEX_UPPER.formatHex(block), "TR34_KEY_BLOCK", null);
}
/** A key out of a TR-34 key block. */
private Imported importTr34(String region, Map<String, Object> material) {
String token = text(material, "ImportToken");
if (token.isEmpty()) {
// The service imports a block under the token the import parameters issued, so a
// request that names none is refused with the reason, not with a key that is
// not found. The wrapping key the request may name is the receiver's own, and
// it is the token that names the key the block is wrapped under.
throw validation("a TR-34 key block is imported under the token the import "
+ "parameters issued, so the request must name the import token they "
+ "issued; this service does not import a block under a wrapping key the "
+ "request names");
}
Issued issued = take(importTokens, token, "TR34_KEY_BLOCK");
if (issued == null) {
throw notFound(token);
}
// The shape check settles the members the model requires and the values it names,
// so the block, the signing certificate, the authority and the format are there.
String block = text(material, "WrappedKeyBlock");
String signingCertificate = text(material, "SigningKeyCertificate");
// The service requires the authority: the signing certificate has to chain to it.
String caIdentifier = text(material, "CertificateAuthorityPublicKeyIdentifier");
PaymentCryptographyKey caKey = usableKey(caIdentifier, region);
PublicKey caPublicKey = publicKeyOf(caKey);
if (caPublicKey == null) {
throw validation("CertificateAuthorityPublicKeyIdentifier does not reference a "
+ "public-key certificate");
}
requireVerify(caKey, "verifying a certificate");
// The nonce is what binds the block to this exchange: the importer chooses it and
// the exporter signs it. It is optional in the model, and a block without one is
// read without the freshness it carries.
String nonce = text(material, "RandomNonce");
if (!nonce.isEmpty() && !isHex(nonce)) {
throw validation("KeyMaterial.Tr34KeyBlock.RandomNonce must be hexadecimal");
}
Tr34.Recovered recovered;
try {
recovered = Tr34.recoverAndVerify(block, issued.privateKey, signingCertificate,
caPublicKey, nonce.isEmpty() ? null : nonce);
} catch (RuntimeException e) {
throw validation("the TR-34 key block did not open: " + e.getMessage());
}
// The header the block carried in the clear names the key: its usage, its mode and
// its algorithm. The header a TR-34 block carries is a TR-31 header, so it is read
// the way a TR-31 one is.
String usageCode = PaymentCryptographyTr31.usageOf(recovered.header);
String mode = PaymentCryptographyTr31.modeOf(recovered.header);
String exportability = PaymentCryptographyTr31.exportabilityOf(recovered.header);
if (!"E".equals(exportability) && !"N".equals(exportability) && !"S".equals(exportability)) {
// The exportability is one of three characters, and a header that carries any
// other one says nothing the service can read.
throw validation("the TR-34 key block's header carries the exportability '"
+ exportability + "', which is not one of E, N or S");
}
String usage = PaymentCryptographyService.usageName(usageCode);
byte[] clear = HEX.parseHex(recovered.keyHex);
String algorithm = PaymentCryptographyService.algorithmOf(recovered.header, clear.length);
// The import token's own key protects the key that comes in, so it has to be at
// least as strong as it, the same rule the export enforces.
Integer bits = RSA_BITS.get(issued.algorithm);
String tooWeak = PaymentCryptographyKeyStrength.refusal(
PaymentCryptographyKeyStrength.rsaBitsOf(bits == null ? 0 : bits),
PaymentCryptographyKeyStrength.bitsOf(algorithm),
"RSA_" + bits, algorithm);
if (tooWeak != null) {
throw validation(tooWeak);
}
return new Imported(algorithm, usage,
PaymentCryptographyService.modesFor(mode),
exportableOnImport(exportability), clear, null, null, null, "SYMMETRIC_KEY");
}
}
@@ -108,7 +108,7 @@ final class PaymentCryptographyTr31 {
* @param blockSize the cipher block size in characters
* @return the blocks, with the padding block appended when one is needed
*/
private static List<String[]> withPadding(List<String[]> blocks, int blockSize) {
static List<String[]> withPadding(List<String[]> blocks, int blockSize) {
int total = 0;
for (String[] block : blocks) {
total += block[0].length() + 2 + block[1].length();
@@ -196,7 +196,7 @@ final class PaymentCryptographyTr31 {
* @param blocks the optional blocks, each its identifier and its value
* @return the optional blocks, as the characters of the key block
*/
private static String optionalBlocks(List<String[]> blocks) {
static String optionalBlocks(List<String[]> blocks) {
StringBuilder out = new StringBuilder();
for (String[] block : blocks) {
String id = block[0];
@@ -301,9 +301,9 @@ final class PaymentCryptographyTr31 {
*
* @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) {
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
@@ -553,7 +553,7 @@ final class PaymentCryptographyTr31 {
* @param radix the radix the field is written in
* @return the number, in two characters
*/
private static String two(int value, int radix) {
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);
@@ -11,6 +11,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
@@ -105,6 +106,20 @@ public final class Certificates {
}
}
/**
* The certificate in DER.
*
* @param certificate the certificate
* @return the certificate in DER
*/
public static byte[] toDer(X509Certificate certificate) {
try {
return certificate.getEncoded();
} catch (CertificateEncodingException e) {
throw new IllegalArgumentException("the certificate does not encode: " + e.getMessage());
}
}
/**
* Wrap DER as a PEM document.
*
@@ -0,0 +1,748 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* TR-34 (2012) key blocks: the form a key leaves the service in when it is wrapped for a
* receiving device, and the form it comes back in.
*
* <p>A TR-34 block is a PKCS#7 SignedData whose content is an EnvelopedData:
*
* <ul>
* <li>the key block is encrypted under an ephemeral key, whose cipher follows the key it
* protects;
* <li>that ephemeral key is wrapped under the receiving device's public key with RSA-OAEP;
* <li>the envelope is signed by the service's signing key, over the signed attributes that
* carry the content type, the two-pass nonce, the TR-31 header and the envelope digest.
* </ul>
*
* <p>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.
*
* <p>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.
*
* <p>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<ASN1ObjectIdentifier> ATTRIBUTE_ORDER = List.of(
OID_CONTENT_TYPE, OID_RANDOM_NONCE, OID_DATA, OID_MESSAGE_DIGEST);
/** 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 reference uses. */
private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase();
/** The block size of the Triple DES cipher the key block may be encrypted under. */
private static final int TDES_BLOCK_SIZE = 8;
/** The block size of the AES cipher the key block may be encrypted under. */
private static final int AES_BLOCK_SIZE = 16;
/** The size of the ephemeral Triple DES key. */
private static final int EPHEMERAL_TDES_KEY_SIZE = 24;
/** The size of the ephemeral AES-128 key. */
private static final int EPHEMERAL_AES_KEY_SIZE = 16;
/** The length of the TR-31 header a block carries, in characters. */
private static final int HEADER_LENGTH = 16;
private Tr34() {
}
/** The recovered clear key and the TR-31 header it carried. */
public static final class Recovered {
/** The clear key, in hexadecimal. */
public final String keyHex;
/** The TR-31 header the block carried, in the clear. */
public final String header;
Recovered(String keyHex, String header) {
this.keyHex = keyHex;
this.header = header;
}
}
/**
* Build a TR-34 key block: the key encrypted under an ephemeral key, the ephemeral key
* wrapped under the receiver's public key, and the whole envelope signed with the
* service's signing key.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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<ASN1EncodableVector> orderings(ASN1Set signedAttributes) {
Map<ASN1ObjectIdentifier, ASN1Encodable> byOid = new LinkedHashMap<>();
for (int i = 0; i < signedAttributes.size(); i++) {
ASN1Sequence attribute = ASN1Sequence.getInstance(signedAttributes.getObjectAt(i));
byOid.put(attributeOid(attribute), attribute);
}
ASN1EncodableVector canonical = new ASN1EncodableVector();
for (ASN1ObjectIdentifier oid : ATTRIBUTE_ORDER) {
ASN1Encodable attribute = byOid.remove(oid);
if (attribute != null) {
canonical.add(attribute);
}
}
for (ASN1Encodable attribute : byOid.values()) {
canonical.add(attribute);
}
ASN1EncodableVector sorted = new ASN1EncodableVector();
for (int i = 0; i < signedAttributes.size(); i++) {
sorted.add(signedAttributes.getObjectAt(i));
}
return List.of(canonical, sorted);
}
/** Whether a signature verifies over the given bytes. */
private static boolean verifySignature(byte[] data, byte[] signature, PublicKey key) {
try {
Signature verifier = Signature.getInstance("SHA256withRSA");
verifier.initVerify(key);
verifier.update(data);
return verifier.verify(signature);
} catch (GeneralSecurityException e) {
return false;
}
}
/** The signature over the given bytes, under the given key. */
private static byte[] sign(PrivateKey key, byte[] data) {
try {
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(key);
signer.update(data);
return signer.sign();
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("the TR-34 payload could not be signed: "
+ e.getMessage(), e);
}
}
/** The identifier of the party a certificate belongs to, as an issuer and a serial number. */
private static ASN1Encodable certificateId(byte[] certificateDer) {
if (certificateDer == null) {
// No certificate to name: the identifier is left empty.
return new DERSequence();
}
return decoded(Certificates.certificateId(certificateDer));
}
/** The algorithm the ephemeral key is wrapped under: RSAES-OAEP over SHA-256. */
private static ASN1Encodable keyTransport() {
ASN1EncodableVector hash = new ASN1EncodableVector();
hash.add(OID_SHA256);
hash.add(DERNull.INSTANCE);
ASN1EncodableVector maskGenHash = new ASN1EncodableVector();
maskGenHash.add(OID_SHA256);
ASN1EncodableVector maskGen = new ASN1EncodableVector();
maskGen.add(OID_MGF1);
maskGen.add(new DERSequence(maskGenHash));
ASN1EncodableVector pSource = new ASN1EncodableVector();
pSource.add(OID_P_SPECIFIED);
pSource.add(new DEROctetString(new byte[0]));
ASN1EncodableVector parameters = new ASN1EncodableVector();
parameters.add(new DERSequence(hash));
parameters.add(new DERSequence(maskGen));
parameters.add(new DERSequence(pSource));
return new AlgorithmIdentifier(OID_RSAES_OAEP, new DERSequence(parameters));
}
/** One signed attribute: its type and the set of values it carries. */
private static ASN1Sequence attribute(ASN1ObjectIdentifier oid, ASN1Encodable value) {
ASN1EncodableVector values = new ASN1EncodableVector();
values.add(value);
ASN1EncodableVector attribute = new ASN1EncodableVector();
attribute.add(oid);
attribute.add(new DERSet(values));
return new DERSequence(attribute);
}
/** The type of a signed attribute. */
private static ASN1ObjectIdentifier attributeOid(ASN1Sequence attribute) {
return ASN1ObjectIdentifier.getInstance(attribute.getObjectAt(0));
}
/** The value a signed attribute carries, or null when it carries none. */
private static byte[] attributeValue(ASN1Set attributes, ASN1ObjectIdentifier oid) {
ASN1Sequence attribute = null;
for (int i = 0; i < attributes.size(); i++) {
ASN1Sequence candidate = ASN1Sequence.getInstance(attributes.getObjectAt(i));
if (oid.equals(attributeOid(candidate))) {
attribute = candidate;
break;
}
}
if (attribute == null) {
return null;
}
ASN1Set values = ASN1Set.getInstance(attribute.getObjectAt(1));
if (values.size() == 0) {
return null;
}
ASN1Encodable value = values.getObjectAt(0);
if (value instanceof ASN1OctetString octets) {
return octets.getOctets();
}
return encoded(value.toASN1Primitive());
}
/** The decrypted key block: the clear symmetric key and its TR-31 header. */
static Recovered readKeyBlock(byte[] clearBlock) {
// The key block is a sequence, and the bytes the cipher needed follow it. 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.
// The signature covers the digest of the envelope, so they are authenticated either
// way.
ASN1Sequence keyBlock;
try (ASN1InputStream stream = new ASN1InputStream(clearBlock)) {
keyBlock = ASN1Sequence.getInstance(stream.readObject());
} catch (IOException e) {
throw new IllegalArgumentException("the key block does not parse: " + e.getMessage(), e);
}
byte[] key = null;
String header = "";
for (int i = 0; i < keyBlock.size(); i++) {
ASN1Encodable element = keyBlock.getObjectAt(i);
if (element instanceof ASN1OctetString octets) {
key = octets.getOctets();
continue;
}
// The header attribute is the sequence that carries the data type and the header.
if (element instanceof ASN1Sequence sequence && sequence.size() == 2
&& sequence.getObjectAt(0) instanceof ASN1ObjectIdentifier) {
ASN1Set values = ASN1Set.getInstance(sequence.getObjectAt(1));
if (values.size() > 0) {
header = new String(
ASN1OctetString.getInstance(values.getObjectAt(0)).getOctets(),
StandardCharsets.US_ASCII);
}
}
}
if (key == null) {
throw new IllegalArgumentException("symmetric key octet string not found in key block");
}
if (header.length() < HEADER_LENGTH) {
// The header names the key the block carries, so a block without one says
// nothing about what it carries. It is refused here rather than read, because
// the readers of a header index into it and an empty one has nothing to index.
throw new IllegalArgumentException("the key block carries no TR-31 header, or one of "
+ "fewer than " + HEADER_LENGTH + " characters");
}
return new Recovered(HEX_UPPER.formatHex(key), header);
}
/** The PKCS#7 padding of a block. */
private static byte[] pad(byte[] buffer, int blockSize) {
int pad = blockSize - (buffer.length % blockSize);
byte[] out = Arrays.copyOf(buffer, buffer.length + pad);
for (int i = buffer.length; i < out.length; i++) {
out[i] = (byte) pad;
}
return out;
}
/** The SHA-256 digest of the given bytes. */
private static byte[] digest(byte[] data) {
try {
return MessageDigest.getInstance("SHA-256").digest(data);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("SHA-256 is not available", e);
}
}
/**
* The DER encoding of a value.
*
* <p>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;
}
}
@@ -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"))
@@ -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.
*
* <p>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<String, Object> exportParameters = service.parametersForExport("TR34_KEY_BLOCK",
"RSA_2048", false);
Map<String, Object> importParameters = service.parametersForImport("TR34_KEY_BLOCK",
wrappingAlgorithm, false);
// The receiver's authority vouches for the certificate the key is wrapped under; the
// sender's authority vouches for the certificate the block was signed with.
PaymentCryptographyKey receiver = createAuthority(
(String) importParameters.get("WrappingKeyCertificate"));
PaymentCryptographyKey sender = createAuthority(
(String) exportParameters.get("SigningKeyCertificate"));
Map<String, Object> exportMaterial = new LinkedHashMap<>();
exportMaterial.put("ExportToken", exportParameters.get("ExportToken"));
exportMaterial.put("WrappingKeyCertificate", importParameters.get("WrappingKeyCertificate"));
exportMaterial.put("CertificateAuthorityPublicKeyIdentifier", receiver.getKeyId());
exportMaterial.put("KeyBlockFormat", "X9_TR34_2012");
exportMaterial.put("RandomNonce", "A1B2C3D4E5F60718");
return new Tr34Exchange(exportParameters, importParameters, exportMaterial, receiver, sender);
}
/** The exchange a TR-34 block goes through, under the receiver's RSA-2048 key. */
private Tr34Exchange tr34Exchange() {
return tr34Exchange("RSA_2048");
}
/** The parameters, the authorities and the material of a TR-34 exchange. */
private record Tr34Exchange(Map<String, Object> exportParameters,
Map<String, Object> importParameters,
Map<String, Object> exportMaterial,
PaymentCryptographyKey receiver,
PaymentCryptographyKey sender) {
/** The material of a TR-34 import, for the block an export made. */
Map<String, Object> importMaterial(String block) {
Map<String, Object> incoming = new LinkedHashMap<>();
incoming.put("ImportToken", importParameters.get("ImportToken"));
incoming.put("SigningKeyCertificate", exportParameters.get("SigningKeyCertificate"));
incoming.put("WrappedKeyBlock", block);
incoming.put("CertificateAuthorityPublicKeyIdentifier", sender.getKeyId());
incoming.put("KeyBlockFormat", "X9_TR34_2012");
incoming.put("RandomNonce", "A1B2C3D4E5F60718");
return incoming;
}
}
@Test
void aKeyThatLeavesUnderACertificateComesBack() {
// The service that exports mints the parameters; the service that imports holds the
// token that names the key the block is wrapped under.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
assertEquals("TR34_KEY_BLOCK", wrapped.get("WrappedKeyMaterialFormat"));
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr34KeyBlock",
exchange.importMaterial((String) wrapped.get("KeyMaterial")), "", true, Map.of());
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
assertEquals(key.getKeyUsage(), imported.getKeyUsage());
}
@Test
void theTr34HeaderCarriesTheExportabilityTheRequestNames() throws Exception {
// The request may narrow the exportability of the key, and the block carries the
// narrowed one, so the key that comes back is one that may not leave again.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
exchange.exportMaterial().put("KeyBlockHeaders", Map.of("KeyExportability", "NON_EXPORTABLE"));
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr34KeyBlock",
exchange.importMaterial((String) wrapped.get("KeyMaterial")), "", true, Map.of());
assertFalse(imported.isExportable(),
"the key came back exportable although the request narrowed it");
}
@Test
void aTr34ExportCarriesTheOptionalBlocks() throws Exception {
// The header of a TR-34 block carries the optional blocks the request names, the
// way the header of a TR-31 block does, and the padding block that keeps the
// header a whole number of cipher blocks is the last of them.
Tr34Exchange exchange = tr34Exchange("RSA_3072");
PaymentCryptographyKey key = createKey("AES_128",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
exchange.exportMaterial().put("KeyBlockHeaders",
Map.of("OptionalBlocks", Map.of("AB", "0011")));
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
// The header travels in the clear, so it can be read without opening the block.
String header = PaymentCryptographyTr34RoundTripTest.clearHeader(
HexFormat.of().parseHex((String) wrapped.get("KeyMaterial")));
// The version has no meaning in a TR-34 block, and the reference writes the same
// one every time.
assertEquals("D", header.substring(0, 1), "the version of the header");
// The header says how many optional blocks there are, and the padding block is one
// of them.
assertEquals("02", header.substring(12, 14), "the number of optional blocks");
assertTrue(header.endsWith("AB080011PB080000"), "the optional blocks are not in the header");
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr34KeyBlock",
exchange.importMaterial((String) wrapped.get("KeyMaterial")), "", true, Map.of());
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
}
@Test
void aTr34BlockWithoutANonceComesBack() {
// The nonce is optional in the model, so a block the service made without one
// comes back without one.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
exchange.exportMaterial().remove("RandomNonce");
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
Map<String, Object> incoming = exchange.importMaterial((String) wrapped.get("KeyMaterial"));
incoming.remove("RandomNonce");
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr34KeyBlock", incoming,
"", true, Map.of());
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
}
@Test
void aTr34BlockWithANonceDoesNotComeBackWithoutIt() {
// The nonce binds the block to the exchange, so a request that names none expects
// a block that carries none, and a block that carries one is refused.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
Map<String, Object> incoming = exchange.importMaterial((String) wrapped.get("KeyMaterial"));
incoming.remove("RandomNonce");
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aTr34ImportWithoutAnImportTokenIsRefused() {
// The service imports a block under the token the import parameters issued, so a
// request that names none is refused with the reason, not with a key that is not
// found.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
Map<String, Object> incoming = exchange.importMaterial((String) wrapped.get("KeyMaterial"));
incoming.remove("ImportToken");
incoming.put("WrappingKeyIdentifier", exchange.receiver().getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("import token"), refused.getMessage());
}
@Test
void aTr34ExportWithoutAnExportTokenIsRefused() {
// The service signs the block with the key the export parameters issued, so a
// request that names no token is refused with the reason, not with a key that is
// not found.
Tr34Exchange exchange = tr34Exchange();
PaymentCryptographyKey key = createKey("TDES_2KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
exchange.exportMaterial().remove("ExportToken");
AwsException refused = assertThrows(AwsException.class,
() -> service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", ""));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("export token"), refused.getMessage());
}
@Test
void theImportParametersRefusalNamesEveryTypeItTakes() {
AwsException refused = assertThrows(AwsException.class,
() -> service.parametersForImport("TR31_KEY_BLOCK", "RSA_2048", false));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("KEY_CRYPTOGRAM, TR34_KEY_BLOCK"),
refused.getMessage());
}
@Test
void aTr34BlockWithAnUnknownExportabilityIsRefused() throws Exception {
// A caller that signs its own block can put an exportability the service does not
// read into the header, and the service refuses it rather than taking it for an
// exportable one.
Tr34Exchange exchange = tr34Exchange();
Crafted crafted = craftedBlock(exchange, "B9999D0ATB00X0000",
HexFormat.of().parseHex("000102030405060708090A0B0C0D0E0F"), false);
Map<String, Object> incoming = exchange.importMaterial(crafted.block());
incoming.put("SigningKeyCertificate", crafted.signingCertificate());
incoming.put("CertificateAuthorityPublicKeyIdentifier", crafted.authority().getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("exportability"), refused.getMessage());
}
@Test
void aTr34BlockUnderATooWeakTokenIsRefused() throws Exception {
// The import token's own key protects the key that comes in, so a key stronger
// than the token may not come in under it.
Tr34Exchange exchange = tr34Exchange();
Crafted crafted = craftedBlock(exchange, "D9999D0AB00E0000",
HexFormat.of().parseHex("000102030405060708090A0B0C0D0E0F"
+ "101112131415161718191A1B1C1D1E1F"), true);
Map<String, Object> incoming = exchange.importMaterial(crafted.block());
incoming.put("SigningKeyCertificate", crafted.signingCertificate());
incoming.put("CertificateAuthorityPublicKeyIdentifier", crafted.authority().getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void anAesKeyLeavesUnderATr34BlockUnderItsOwnCipher() {
// The key block is enciphered with the cipher the key needs, so an AES key is not
// protected by something weaker than itself. An AES-128 key needs a receiver whose
// certificate is RSA-3072 or RSA-4096.
Tr34Exchange exchange = tr34Exchange("RSA_3072");
PaymentCryptographyKey key = createKey("AES_128",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
// The content encryption is the AES one, and not the Triple DES one.
assertTrue(((String) wrapped.get("KeyMaterial")).contains("608648016503040102"),
"the block does not name the AES content encryption");
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr34KeyBlock",
exchange.importMaterial((String) wrapped.get("KeyMaterial")), "", true, Map.of());
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
}
/** A block the test builds itself, and the authority that vouches for its signature. */
private record Crafted(String block, PaymentCryptographyKey authority,
String signingCertificate) {
}
/**
* A TR-34 block the test builds and signs itself.
*
* <p>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.
*
* <p>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<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
// Another authority signs it, so the signature does not verify against this one.
SecureRandom random = new SecureRandom();
KeyPair other = PaymentCryptographyKeyPairs.rsa(2048, random);
Certificates.Minted otherCertificate = CertificatesTest.mint(other.getPublic(),
"floci other", other.getPrivate(), "floci other");
Map<String, Object> incoming = exchange.importMaterial((String) wrapped.get("KeyMaterial"));
incoming.put("SigningKeyCertificate", otherCertificate.pem());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
}
@ParameterizedTest
@ValueSource(strings = {"RSA_3072", "RSA_4096", "ECC_NIST_P256", "ECC_NIST_P384", "ECC_NIST_P521"})
void anExportSigningKeyThatIsNotRsa2048IsRefused(String algorithm) {
// 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.
AwsException refused = assertThrows(AwsException.class,
() -> service.parametersForExport("TR34_KEY_BLOCK", algorithm, false));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("signed with RSA_2048"), refused.getMessage());
}
@Test
void aTr34BlockThatCarriesNoHeaderIsRefused() throws Exception {
// A block that is signed correctly but whose key block names no key says nothing
// about what it carries, so it is refused rather than read.
Tr34Exchange exchange = tr34Exchange();
Crafted crafted = craftedBlock(exchange, "",
HexFormat.of().parseHex("000102030405060708090A0B0C0D0E0F"), false);
Map<String, Object> incoming = exchange.importMaterial(crafted.block());
incoming.put("SigningKeyCertificate", crafted.signingCertificate());
incoming.put("CertificateAuthorityPublicKeyIdentifier", crafted.authority().getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void anInitialKeyThatLeavesUnderATr34BlockIsSensitive() throws Exception {
// The initial key of the DUKPT derivation is sensitive, so the header that names it
// says so, whichever form the key leaves in.
Map<String, Object> 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), false, true, Map.of());
Tr34Exchange exchange = tr34Exchange();
Map<String, Object> answer = service.exportKey("us-east-1", base.getKeyId(), "Tr34KeyBlock",
exchange.exportMaterial(), "12345678900000000001", "");
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
// The header travels in the clear, so it can be read without opening the block.
String header = PaymentCryptographyTr34RoundTripTest.clearHeader(
HexFormat.of().parseHex((String) wrapped.get("KeyMaterial")));
assertEquals("B1", header.substring(5, 7), "the usage of the derived key");
assertEquals("S", header.substring(11, 12), "the derived key is a sensitive one");
}
@Test
void anImportTokenIsRefusedForAnotherKindOfMaterial() {
// A token is issued for one kind of material, so it cannot be spent on another.
Map<String, Object> parameters = service.parametersForImport("KEY_CRYPTOGRAM", "RSA_2048",
false);
String token = (String) parameters.get("ImportToken");
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr34KeyBlock", Map.of(
"ImportToken", token,
"CertificateAuthorityPublicKeyIdentifier", protection.getKeyId(),
"KeyBlockFormat", "X9_TR34_2012",
"RandomNonce", "0102030405060708",
"SigningKeyCertificate", "x",
"WrappedKeyBlock", "00"), "", true, Map.of()));
assertEquals("ResourceNotFoundException", refused.getErrorCode());
}
/** A symmetric key of the given algorithm and usage. */
private PaymentCryptographyKey createKey(String algorithm, String usage) {
@@ -0,0 +1,304 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERSet;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.time.Instant;
import java.util.HexFormat;
import static org.junit.jupiter.api.Assertions.assertEquals;
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 TR-34 builder, against the TR-34 verifier.
*
* <p>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.
*
* <p>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();
}
}