mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(paymentcryptography): the AS2805 key cryptogram (#8172)
ExportKey and ImportKey take an As2805KeyCryptogram: a TDES key leaves and comes back under a TR31_K0 TDES key encryption key, bound to one of the four AS2805 variants. The cryptogram carries a tag over the whole of it, made under a key derived from the wrapping key and checked before anything is decrypted, and the key's ANSI X9.24 check value, which the import compares. A wrapping key that is not K0, not TDES or weaker than the key is refused, as is a variant that does not match the key's purpose. Bytes holds the concat, PKCS#7 padding and isHex the payment cryptography classes kept copies of, and the SDK and CLI compatibility tests cover the round trip and its refusals.
This commit is contained in:
1 parent
b8c08f1be4
commit
ff467b2e09
14 files changed
+1361
-105
No files matched your search
@@ -49,15 +49,14 @@ create_tdes_key() {
|
||||
|
||||
# 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.
|
||||
# The ARN is printed and the caller registers it for the cleanup: a command substitution
|
||||
# runs in a subshell, so a key registered in here would never reach the cleanup.
|
||||
import_authority() {
|
||||
local certificate="$1"
|
||||
local algorithm="$2"
|
||||
local arn
|
||||
arn=$(aws_cmd payment-cryptography import-key \
|
||||
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"
|
||||
--query 'Key.KeyArn' --output text
|
||||
}
|
||||
|
||||
@test "Payment Cryptography key exchange: the import parameters carry a token and a certificate" {
|
||||
@@ -168,6 +167,7 @@ import_authority() {
|
||||
# The receiver's authority: the public half of the certificate the block is wrapped
|
||||
# under.
|
||||
RECEIVER_ARN=$(import_authority "$WRAPPING_CERTIFICATE" RSA_3072)
|
||||
CREATED_ARNS="$CREATED_ARNS $RECEIVER_ARN"
|
||||
[ -n "$RECEIVER_ARN" ]
|
||||
|
||||
run aws_cmd payment-cryptography get-parameters-for-export \
|
||||
@@ -181,6 +181,7 @@ import_authority() {
|
||||
|
||||
# The sender's authority: the public half of the certificate the block is signed with.
|
||||
SENDER_ARN=$(import_authority "$SIGNING_CERTIFICATE" RSA_2048)
|
||||
CREATED_ARNS="$CREATED_ARNS $SENDER_ARN"
|
||||
[ -n "$SENDER_ARN" ]
|
||||
|
||||
KEY_ARN=$(create_tdes_key)
|
||||
@@ -197,6 +198,9 @@ import_authority() {
|
||||
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')" ]
|
||||
IMPORTED=$(json_get "$output" '.Key.KeyArn')
|
||||
[ -n "$IMPORTED" ]
|
||||
# The key came into the service, so the cleanup has to take it away again.
|
||||
CREATED_ARNS="$CREATED_ARNS $IMPORTED"
|
||||
[ "$(json_get "$output" '.Key.KeyAttributes.KeyUsage')" = "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY" ]
|
||||
}
|
||||
+158
-1
@@ -12,6 +12,7 @@ import software.amazon.awssdk.awscore.exception.AwsServiceException;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.Alias;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.As2805KeyVariant;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.DeriveKeyUsage;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.ExportKeyResponse;
|
||||
import software.amazon.awssdk.services.paymentcryptography.model.GetParametersForExportResponse;
|
||||
@@ -118,6 +119,20 @@ class PaymentCryptographyTest {
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The key encryption key an AS2805 cryptogram is wrapped under. */
|
||||
private static Key createKeyEncryptionKey() {
|
||||
Key key = client.createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(KeyUsage.TR31_K0_KEY_ENCRYPTION_KEY)
|
||||
.keyModesOfUse(m -> m.wrap(true).unwrap(true)))
|
||||
.exportable(true))
|
||||
.key();
|
||||
keyArns.add(key.keyArn());
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* The public half of a certificate, held by the service as a key.
|
||||
*
|
||||
@@ -140,11 +155,16 @@ class PaymentCryptographyTest {
|
||||
|
||||
/** A key of the given algorithm, for the data the cipher protects. */
|
||||
private static Key createKey(KeyAlgorithm algorithm) {
|
||||
return createKey(algorithm, KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY);
|
||||
}
|
||||
|
||||
/** A key of the given algorithm and usage, for a variant that binds a purpose. */
|
||||
private static Key createKey(KeyAlgorithm algorithm, KeyUsage usage) {
|
||||
Key key = client.createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(algorithm)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
|
||||
.keyUsage(usage)
|
||||
.keyModesOfUse(m -> m.encrypt(true).decrypt(true)))
|
||||
.exportable(true))
|
||||
.key();
|
||||
@@ -251,6 +271,143 @@ class PaymentCryptographyTest {
|
||||
.isEqualTo(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeavesTheServiceAndComesBackThroughAnAs2805Cryptogram() {
|
||||
Key encryptionKey = createKeyEncryptionKey();
|
||||
Key key = createKey(KeyAlgorithm.TDES_3_KEY, KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
|
||||
|
||||
ExportKeyResponse exported = client.exportKey(r -> r
|
||||
.exportKeyIdentifier(key.keyArn())
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
|
||||
|
||||
assertThat(exported.wrappedKey().wrappedKeyMaterialFormat())
|
||||
.isEqualTo(WrappedKeyMaterialFormat.KEY_CRYPTOGRAM);
|
||||
assertThat(exported.wrappedKey().keyMaterial()).isNotBlank();
|
||||
|
||||
ImportKeyResponse imported = client.importKey(r -> r
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn())
|
||||
.wrappedKeyCryptogram(exported.wrappedKey().keyMaterial())
|
||||
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
|
||||
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true))
|
||||
.exportable(true))));
|
||||
|
||||
assertThat(imported.key().keyArn()).isNotBlank();
|
||||
assertThat(imported.key().keyAttributes().keyUsage())
|
||||
.isEqualTo(KeyUsage.TR31_P0_PIN_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());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAs2805ImportKeepsTheExportabilityTheRequestNamed() {
|
||||
// The model carries the exportability at the top level of the AS2805 import, so a
|
||||
// key imported as one that may not leave is one that may not leave.
|
||||
Key encryptionKey = createKeyEncryptionKey();
|
||||
Key key = createKey(KeyAlgorithm.TDES_3_KEY, KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
|
||||
|
||||
ExportKeyResponse exported = client.exportKey(r -> r
|
||||
.exportKeyIdentifier(key.keyArn())
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
|
||||
|
||||
ImportKeyResponse imported = client.importKey(r -> r
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn())
|
||||
.wrappedKeyCryptogram(exported.wrappedKey().keyMaterial())
|
||||
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
|
||||
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true))
|
||||
.exportable(false))));
|
||||
|
||||
assertThat(imported.key().exportable()).isFalse();
|
||||
// The key came into the service, so the cleanup has to take it away again.
|
||||
keyArns.add(imported.key().keyArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderEachSupportedVariantIsServed() {
|
||||
// The model names four variants, and the service serves every one of them. A
|
||||
// variant says what the key is for, so the key that leaves under it is a key of
|
||||
// that purpose.
|
||||
Key encryptionKey = createKeyEncryptionKey();
|
||||
|
||||
Map<As2805KeyVariant, KeyUsage> usages = Map.of(
|
||||
As2805KeyVariant.TERMINAL_MAJOR_KEY_VARIANT_00,
|
||||
KeyUsage.TR31_K0_KEY_ENCRYPTION_KEY,
|
||||
As2805KeyVariant.DATA_ENCRYPTION_KEY_VARIANT_22,
|
||||
KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,
|
||||
As2805KeyVariant.MESSAGE_AUTHENTICATION_KEY_VARIANT_24,
|
||||
KeyUsage.TR31_M0_ISO_16609_MAC_KEY,
|
||||
As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28,
|
||||
KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
|
||||
|
||||
for (Map.Entry<As2805KeyVariant, KeyUsage> entry : usages.entrySet()) {
|
||||
As2805KeyVariant variant = entry.getKey();
|
||||
// AS2805's cryptography is all TDES, so every key is a TDES one.
|
||||
Key key = createKey(KeyAlgorithm.TDES_3_KEY, entry.getValue());
|
||||
|
||||
ExportKeyResponse exported = client.exportKey(r -> r
|
||||
.exportKeyIdentifier(key.keyArn())
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(variant)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
|
||||
|
||||
assertThat(exported.wrappedKey().wrappedKeyMaterialFormat())
|
||||
.as(variant.toString())
|
||||
.isEqualTo(WrappedKeyMaterialFormat.KEY_CRYPTOGRAM);
|
||||
assertThat(exported.wrappedKey().keyMaterial()).isNotBlank();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAVariantThatIsNotTheKeysPurposeIsRefused() {
|
||||
// The variant says what the key is for, so a key of another purpose cannot leave
|
||||
// under it.
|
||||
Key encryptionKey = createKeyEncryptionKey();
|
||||
Key key = createTdesKey();
|
||||
|
||||
assertThatThrownBy(() -> client.exportKey(r -> r
|
||||
.exportKeyIdentifier(key.keyArn())
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.TERMINAL_MAJOR_KEY_VARIANT_00)
|
||||
.wrappingKeyIdentifier(encryptionKey.keyArn())))))
|
||||
.isInstanceOf(AwsServiceException.class)
|
||||
.satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails()
|
||||
.errorCode()).isEqualTo("ValidationException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAKeyThatIsNotAKeyEncryptionKeyIsRefused() {
|
||||
// A key that is not a key encryption key cannot be the one a cryptogram is wrapped
|
||||
// under.
|
||||
Key dataKey = client.createKey(r -> r
|
||||
.keyAttributes(a -> a
|
||||
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
|
||||
.keyClass(KeyClass.SYMMETRIC_KEY)
|
||||
.keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
|
||||
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true)))
|
||||
.exportable(true))
|
||||
.key();
|
||||
keyArns.add(dataKey.keyArn());
|
||||
Key key = createKey(KeyAlgorithm.TDES_3_KEY, KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
|
||||
|
||||
assertThatThrownBy(() -> client.exportKey(r -> r
|
||||
.exportKeyIdentifier(key.keyArn())
|
||||
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
|
||||
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
|
||||
.wrappingKeyIdentifier(dataKey.keyArn())))))
|
||||
.isInstanceOf(AwsServiceException.class)
|
||||
.hasMessageContaining("key encryption key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsCreatedDisabledAndWithTags() {
|
||||
Key key = client.createKey(r -> r
|
||||
|
||||
@@ -75,9 +75,10 @@
|
||||
- **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, 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
|
||||
a TR-34 key block the service signs and wraps for the receiver, under an AS2805 cryptogram
|
||||
the receiver's key encryption key 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
|
||||
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
|
||||
@@ -121,16 +122,27 @@
|
||||
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.
|
||||
exportability of the key, and it may name a version and optional blocks, and the header
|
||||
the block carries says so, the same as it does for a TR-31 block.
|
||||
- **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 AS2805 key cryptogram:** a key leaves under a key encryption key, bound to its
|
||||
purpose by the AS2805 variant, and comes back the same way. The variant is exclusive-ored
|
||||
into the key before it is encrypted, and the cryptogram carries a tag over the whole of
|
||||
it, so a cryptogram that was changed does not open at all: the tag catches a wrong
|
||||
wrapping key and a wrong variant as well as a changed ciphertext. The variants served
|
||||
are `TERMINAL_MAJOR_KEY_VARIANT_00`, `DATA_ENCRYPTION_KEY_VARIANT_22`,
|
||||
`MESSAGE_AUTHENTICATION_KEY_VARIANT_24` and `PIN_ENCRYPTION_KEY_VARIANT_28`. A variant
|
||||
says what the key is for, so a key may only leave under the variant that matches its own
|
||||
usage, and the wrapping key has to be at least as strong as the key it carries, on the
|
||||
import as well as on the export.
|
||||
- **The bytes of an AS2805 cryptogram are this emulator's own.** The layout of the standard
|
||||
is not published, so the cryptogram this service reads and writes is its own
|
||||
construction. A cryptogram another producer built does not open here, and one this
|
||||
service built does not open there. The fields, the variant mapping and the key rules are
|
||||
the ones the service publishes, and those are what it implements.
|
||||
- **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
|
||||
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Bytes;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.ConcatKdf;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* The AS2805 key cryptogram, as this emulator reads and writes it.
|
||||
*
|
||||
* <p>AS2805 protects a key by variant rather than by a key block. The variant
|
||||
* says what the key is for, and it is exclusive-ored into the key before it is
|
||||
* encrypted, so a key wrapped for one purpose does not open under another.
|
||||
*
|
||||
* <p>The cryptogram this emulator reads is:
|
||||
*
|
||||
* <pre>
|
||||
* "HDC2" || the initialization vector || the key, with the variant
|
||||
* exclusive-ored into its first byte, followed by the key's check
|
||||
* value, encrypted under the wrapping key with CBC || the tag
|
||||
* </pre>
|
||||
*
|
||||
* <p>The tag is what makes the cryptogram more than the output of a cipher. A
|
||||
* cipher on its own says nothing about a ciphertext that was altered: a block
|
||||
* that was flipped decrypts to a plaintext a block away from the right one, and
|
||||
* a three-byte check value is not enough to tell the two apart with any
|
||||
* confidence, so a caller who could change a cryptogram could change the key it
|
||||
* carries and try again until the check value matched. The tag is an HMAC over
|
||||
* the whole of the cryptogram, and it is checked before anything is decrypted,
|
||||
* so a cryptogram that was changed is refused without the key it claims to
|
||||
* carry ever being computed.
|
||||
*
|
||||
* <p>The tag is over the variant and the algorithm as well as over the
|
||||
* ciphertext, so a cryptogram wrapped for one variant does not open under
|
||||
* another, and one that names another algorithm does not open either.
|
||||
*
|
||||
* <p>The cipher is Triple DES, and the vector is a fresh one for every
|
||||
* cryptogram, so two cryptograms of the same key under the same wrapping key
|
||||
* are not the same bytes.
|
||||
*
|
||||
* <p>The two keys the cryptogram uses, the one that encrypts and the one that
|
||||
* authenticates, are derived from the wrapping key, each from a label of its
|
||||
* own, so neither of them is the wrapping key itself.
|
||||
*
|
||||
* <p>The check value inside the cryptogram is the key's own check value: the
|
||||
* ANSI X9.24 one for a Triple DES key, the same one the service reports as the
|
||||
* key's {@code KeyCheckValue}, so the value carried inside the cryptogram and
|
||||
* the value in the import response are the same.
|
||||
*
|
||||
* <p><b>The byte layout of the AS2805 key cryptogram is in the standard and
|
||||
* is not published.</b> What the service publishes is the shape - the fields,
|
||||
* the variant mapping and the key rules - and those are what this implements.
|
||||
* The bytes this reads and writes are therefore this emulator's own
|
||||
* construction, and a cryptogram another producer built does not open here.
|
||||
*/
|
||||
public final class PaymentCryptographyAs2805Cryptogram {
|
||||
|
||||
/** The format marker, in the clear, at the head of the cryptogram. */
|
||||
private static final byte[] MARKER = {'H', 'D', 'C', '2'};
|
||||
|
||||
/** The length of the check value, in bytes. */
|
||||
private static final int KCV_BYTES = 3;
|
||||
|
||||
/** The Triple DES block size, in bytes, which the vector and the padding use. */
|
||||
private static final int BLOCK_BYTES = 8;
|
||||
|
||||
/** The length of the tag, in bytes: an HMAC-SHA-256 is thirty-two of them. */
|
||||
private static final int TAG_BYTES = 32;
|
||||
|
||||
/** The label the encryption key is derived under. */
|
||||
private static final String ENCRYPTION_LABEL = "floci AS2805 encryption";
|
||||
|
||||
/** The label the authentication key is derived under. */
|
||||
private static final String AUTHENTICATION_LABEL = "floci AS2805 authentication";
|
||||
|
||||
/** The digest the derived keys are made with. */
|
||||
private static final String DERIVATION_HASH = "SHA_256";
|
||||
|
||||
/** The hexadecimal the cryptogram is written in. */
|
||||
private static final HexFormat HEX = HexFormat.of();
|
||||
|
||||
/** The hexadecimal the cryptogram is written in: the capitals the model asks for. */
|
||||
private static final HexFormat HEX_UPPER = HexFormat.of().withUpperCase();
|
||||
|
||||
private PaymentCryptographyAs2805Cryptogram() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a clear key into an AS2805 cryptogram.
|
||||
*
|
||||
* @param clearKey the key material
|
||||
* @param variantByte the byte that binds the purpose into the key
|
||||
* @param algorithm the clear key's algorithm, which fixes its length and
|
||||
* how its check value is computed
|
||||
* @param wrappingKey the key that protects the cryptogram
|
||||
* @return the cryptogram, in hex
|
||||
*/
|
||||
public static String wrap(byte[] clearKey, int variantByte, PaymentCryptographyKeyAlgorithm algorithm,
|
||||
byte[] wrappingKey) {
|
||||
int expected = expectedBytes(algorithm);
|
||||
if (clearKey.length != expected) {
|
||||
throw new IllegalArgumentException("the key is " + clearKey.length
|
||||
+ " bytes; " + algorithm.name() + " needs " + expected);
|
||||
}
|
||||
byte[] bound = bind(clearKey, variantByte);
|
||||
byte[] check = checkValue(clearKey, algorithm);
|
||||
byte[] plain = Bytes.pkcs7Pad(Bytes.concat(bound, check), BLOCK_BYTES);
|
||||
byte[] encryptionKey = derive(wrappingKey, ENCRYPTION_LABEL, wrappingKey.length);
|
||||
byte[] authenticationKey = derive(wrappingKey, AUTHENTICATION_LABEL, TAG_BYTES);
|
||||
// The vector is fresh for every cryptogram, so the same key under the same wrapping
|
||||
// key does not give the same bytes twice.
|
||||
byte[] iv = new byte[BLOCK_BYTES];
|
||||
SecureRandom random = new SecureRandom();
|
||||
random.nextBytes(iv);
|
||||
byte[] body = Ciphers.tdesCbcEncrypt(plain, Ciphers.widenTdesKey(encryptionKey), iv);
|
||||
byte[] tag = tag(authenticationKey, algorithm, variantByte, iv, body);
|
||||
// The model's pattern for the cryptogram is upper-case hexadecimal, so that is the
|
||||
// case it is written in.
|
||||
return HEX_UPPER.formatHex(Bytes.concat(MARKER, iv, body, tag));
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an AS2805 cryptogram.
|
||||
*
|
||||
* @param cryptogram the cryptogram, in hex
|
||||
* @param variantByte the byte that binds the purpose into the key
|
||||
* @param algorithm the clear key's algorithm, which fixes its length and
|
||||
* how its check value is computed
|
||||
* @param wrappingKey the key that protects the cryptogram
|
||||
* @return the clear key
|
||||
* @throws IllegalArgumentException when the cryptogram is malformed, does
|
||||
* not decrypt under the wrapping key, or does not carry the check
|
||||
* value of the key it claims to carry
|
||||
*/
|
||||
public static byte[] unwrap(String cryptogram, int variantByte,
|
||||
PaymentCryptographyKeyAlgorithm algorithm, byte[] wrappingKey) {
|
||||
if (cryptogram == null || !Bytes.isHex(cryptogram)) {
|
||||
throw new IllegalArgumentException("the cryptogram is not hexadecimal");
|
||||
}
|
||||
byte[] payload = HEX.parseHex(cryptogram);
|
||||
int blockSize = BLOCK_BYTES;
|
||||
if (payload.length <= MARKER.length + blockSize + TAG_BYTES) {
|
||||
throw new IllegalArgumentException("the cryptogram is too short to carry a key");
|
||||
}
|
||||
for (int i = 0; i < MARKER.length; i++) {
|
||||
if (payload[i] != MARKER[i]) {
|
||||
throw new IllegalArgumentException(
|
||||
"the cryptogram does not start with the HDC2 marker");
|
||||
}
|
||||
}
|
||||
byte[] iv = new byte[blockSize];
|
||||
System.arraycopy(payload, MARKER.length, iv, 0, blockSize);
|
||||
int bodyAt = MARKER.length + blockSize;
|
||||
int tagAt = payload.length - TAG_BYTES;
|
||||
byte[] body = new byte[tagAt - bodyAt];
|
||||
System.arraycopy(payload, bodyAt, body, 0, body.length);
|
||||
byte[] tag = new byte[TAG_BYTES];
|
||||
System.arraycopy(payload, tagAt, tag, 0, TAG_BYTES);
|
||||
|
||||
// Every way the cryptogram can fail says the same thing.
|
||||
//
|
||||
// <p>The tag, the padding, the length and the check value each fail in their own
|
||||
// way, and saying which one failed tells a caller who can change the cryptogram how
|
||||
// far its plaintext is from being right. So the failures are one failure here, and
|
||||
// the caller is told only that the cryptogram did not open.
|
||||
try {
|
||||
// The tag is checked first, so a cryptogram that was changed is refused before
|
||||
// the key it claims to carry is computed.
|
||||
byte[] authenticationKey = derive(wrappingKey, AUTHENTICATION_LABEL, TAG_BYTES);
|
||||
if (!MessageDigest.isEqual(tag, tag(authenticationKey, algorithm, variantByte, iv, body))) {
|
||||
throw new IllegalArgumentException("the cryptogram was changed");
|
||||
}
|
||||
byte[] encryptionKey = derive(wrappingKey, ENCRYPTION_LABEL, wrappingKey.length);
|
||||
byte[] plain = Ciphers.tdesCbcDecrypt(body, Ciphers.widenTdesKey(encryptionKey), iv);
|
||||
plain = Bytes.pkcs7Unpad(plain, blockSize);
|
||||
|
||||
int expected = expectedBytes(algorithm);
|
||||
if (plain.length != expected + KCV_BYTES) {
|
||||
throw new IllegalArgumentException("the cryptogram carries the wrong length");
|
||||
}
|
||||
byte[] bound = new byte[expected];
|
||||
System.arraycopy(plain, 0, bound, 0, expected);
|
||||
byte[] carried = new byte[KCV_BYTES];
|
||||
System.arraycopy(plain, expected, carried, 0, KCV_BYTES);
|
||||
|
||||
byte[] clear = unbind(bound, variantByte);
|
||||
String expectedCheck = checkValueHex(clear, algorithm);
|
||||
String carriedCheck = HEX_UPPER.formatHex(carried);
|
||||
if (!expectedCheck.equals(carriedCheck)) {
|
||||
throw new IllegalArgumentException("the cryptogram carries the wrong check value");
|
||||
}
|
||||
return clear;
|
||||
} catch (RuntimeException e) {
|
||||
throw new IllegalArgumentException("the cryptogram did not open under the wrapping key");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tag over the cryptogram.
|
||||
*
|
||||
* <p>The tag covers the marker, the algorithm and the variant as well as the ciphertext,
|
||||
* so a cryptogram is bound to the purpose it was wrapped for and to the algorithm it
|
||||
* names.
|
||||
*
|
||||
* @param authenticationKey the key the tag is made under
|
||||
* @param algorithm the algorithm the cryptogram names
|
||||
* @param variantByte the variant the cryptogram is bound to
|
||||
* @param iv the initialization vector the ciphertext was encrypted under
|
||||
* @param body the ciphertext
|
||||
* @return the tag
|
||||
*/
|
||||
private static byte[] tag(byte[] authenticationKey, PaymentCryptographyKeyAlgorithm algorithm,
|
||||
int variantByte, byte[] iv, byte[] body) {
|
||||
byte[] authenticated = Bytes.concat(MARKER,
|
||||
algorithm.name().getBytes(StandardCharsets.US_ASCII),
|
||||
new byte[] {(byte) variantByte}, iv, body);
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(authenticationKey, "HmacSHA256"));
|
||||
return mac.doFinal(authenticated);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AS2805 tag could not be computed: "
|
||||
+ e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A key derived from the wrapping key, under a label of its own.
|
||||
*
|
||||
* <p>The encryption key and the authentication key are derived from the same wrapping
|
||||
* key under different labels, so neither of them is the wrapping key and neither of them
|
||||
* is the other one.
|
||||
*
|
||||
* @param wrappingKey the key that protects the cryptogram
|
||||
* @param label the label the key is derived under
|
||||
* @param length how many bytes to derive
|
||||
* @return the derived key
|
||||
*/
|
||||
private static byte[] derive(byte[] wrappingKey, String label, int length) {
|
||||
return ConcatKdf.derive(DERIVATION_HASH, wrappingKey,
|
||||
label.getBytes(StandardCharsets.US_ASCII), length);
|
||||
}
|
||||
|
||||
/** The key, with the variant exclusive-ored into its first byte. */
|
||||
private static byte[] bind(byte[] clearKey, int variantByte) {
|
||||
byte[] bound = clearKey.clone();
|
||||
bound[0] ^= (byte) variantByte;
|
||||
return bound;
|
||||
}
|
||||
|
||||
/** The key, with the variant exclusive-ored back out. */
|
||||
private static byte[] unbind(byte[] bound, int variantByte) {
|
||||
byte[] clear = bound.clone();
|
||||
clear[0] ^= (byte) variantByte;
|
||||
return clear;
|
||||
}
|
||||
|
||||
/** The check value of the key, in bytes. */
|
||||
private static byte[] checkValue(byte[] clearKey, PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
return HEX.parseHex(checkValueHex(clearKey, algorithm));
|
||||
}
|
||||
|
||||
/** The check value of the key, in upper-case hex. */
|
||||
private static String checkValueHex(byte[] clearKey, PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
return PaymentCryptographyCrypto.checkValue(clearKey, algorithm);
|
||||
}
|
||||
/** The key length an algorithm implies. */
|
||||
private static int expectedBytes(PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
if (algorithm == null || algorithm.isEcc()) {
|
||||
throw new IllegalArgumentException(
|
||||
"the key algorithm " + algorithm + " is not a symmetric algorithm");
|
||||
}
|
||||
return algorithm.bytes();
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* The AS2805 key variants, and the key usage each one carries.
|
||||
*
|
||||
* <p>AS2805 - Australian Standard 2805 - protects keys by variant rather than
|
||||
* by a TR-31 key block. Each variant is a single purpose, so a key brought in
|
||||
* under one can be used for nothing else. The service maps them onto its own
|
||||
* key usages:
|
||||
*
|
||||
* <pre>
|
||||
* TERMINAL_MAJOR_KEY_VARIANT_00 TR31_K0_KEY_ENCRYPTION_KEY
|
||||
* PIN_ENCRYPTION_KEY_VARIANT_28 TR31_P0_PIN_ENCRYPTION_KEY
|
||||
* MESSAGE_AUTHENTICATION_KEY_VARIANT_24 TR31_M0_ISO_16609_MAC_KEY
|
||||
* DATA_ENCRYPTION_KEY_VARIANT_22 TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY
|
||||
* </pre>
|
||||
*
|
||||
* <p>AS2805 binds the purpose into the key material as well: the variant is
|
||||
* exclusive-ored into the key before it is encrypted, so a key that was
|
||||
* wrapped for one purpose does not open under another.
|
||||
*/
|
||||
public enum PaymentCryptographyAs2805Variant {
|
||||
|
||||
/** The key encryption key. AS2805 calls it the terminal major key. */
|
||||
TERMINAL_MAJOR_KEY_VARIANT_00("TR31_K0_KEY_ENCRYPTION_KEY", 0x00),
|
||||
/** The data encryption key. */
|
||||
DATA_ENCRYPTION_KEY_VARIANT_22("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", 0x16),
|
||||
/** The message authentication key. */
|
||||
MESSAGE_AUTHENTICATION_KEY_VARIANT_24("TR31_M0_ISO_16609_MAC_KEY", 0x18),
|
||||
/** The PIN encryption key. */
|
||||
PIN_ENCRYPTION_KEY_VARIANT_28("TR31_P0_PIN_ENCRYPTION_KEY", 0x1C);
|
||||
|
||||
private final String usage;
|
||||
private final int variantByte;
|
||||
|
||||
PaymentCryptographyAs2805Variant(String usage, int variantByte) {
|
||||
this.usage = usage;
|
||||
this.variantByte = variantByte;
|
||||
}
|
||||
|
||||
/** The key usage the service gives a key imported under this variant. */
|
||||
public String usage() {
|
||||
return usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The byte exclusive-ored into the key before it is encrypted.
|
||||
*
|
||||
* <p>This is the purpose binding: the same key material under a different
|
||||
* variant encrypts to a different cryptogram, and unwrapping it under the
|
||||
* wrong variant gives a key that is wrong in its first byte.
|
||||
*/
|
||||
public int variantByte() {
|
||||
return variantByte;
|
||||
}
|
||||
|
||||
public static PaymentCryptographyAs2805Variant from(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
for (PaymentCryptographyAs2805Variant v : values()) {
|
||||
if (v.name().equals(name)) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The names of the variants the service serves, for a message that lists them.
|
||||
*
|
||||
* @return the names, comma-separated
|
||||
*/
|
||||
public static String names() {
|
||||
return Arrays.stream(values()).map(Enum::name).collect(Collectors.joining(", "));
|
||||
}
|
||||
}
|
||||
+3
-9
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Bytes;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
@@ -269,7 +270,7 @@ final class PaymentCryptographyCrypto {
|
||||
int n = r.length;
|
||||
for (int j = 0; j < 6; j++) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
byte[] block = concat(a, r[i]);
|
||||
byte[] block = Bytes.concat(a, r[i]);
|
||||
byte[] encrypted = Ciphers.aesEcbEncrypt(block, key);
|
||||
a = Arrays.copyOfRange(encrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
|
||||
@@ -296,7 +297,7 @@ final class PaymentCryptographyCrypto {
|
||||
int n = r.length;
|
||||
for (int j = 5; j >= 0; j--) {
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
byte[] block = concat(Ciphers.xor(a, counter(j, n, i)), r[i]);
|
||||
byte[] block = Bytes.concat(Ciphers.xor(a, counter(j, n, i)), r[i]);
|
||||
byte[] decrypted = Ciphers.aesEcbDecrypt(block, key);
|
||||
a = Arrays.copyOfRange(decrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
|
||||
@@ -329,13 +330,6 @@ final class PaymentCryptographyCrypto {
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[] left, byte[] right) {
|
||||
byte[] out = new byte[left.length + right.length];
|
||||
System.arraycopy(left, 0, out, 0, left.length);
|
||||
System.arraycopy(right, 0, out, left.length, right.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES-CBC encryption of data under a key and an initialization vector, without
|
||||
* padding: the vector is the length of the data's block size already.
|
||||
|
||||
+149
-18
@@ -2,6 +2,7 @@ package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.acm.CertificateGenerator;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Bytes;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Certificates;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.ConcatKdf;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ecdh;
|
||||
@@ -49,6 +50,8 @@ 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,7 +68,8 @@ final class PaymentCryptographyKeyExchange {
|
||||
"Tr31KeyBlock",
|
||||
"KeyCryptogram",
|
||||
"Tr34KeyBlock",
|
||||
"DiffieHellmanTr31KeyBlock");
|
||||
"DiffieHellmanTr31KeyBlock",
|
||||
"As2805KeyCryptogram");
|
||||
|
||||
/** The forms the import takes, in the order the service lists them. */
|
||||
static final List<String> IMPORT_FORMS = List.of(
|
||||
@@ -74,7 +78,8 @@ final class PaymentCryptographyKeyExchange {
|
||||
"Tr34KeyBlock",
|
||||
"RootCertificatePublicKey",
|
||||
"TrustedCertificatePublicKey",
|
||||
"DiffieHellmanTr31KeyBlock");
|
||||
"DiffieHellmanTr31KeyBlock",
|
||||
"As2805KeyCryptogram");
|
||||
|
||||
/** The key material types that take import parameters. */
|
||||
private static final List<String> IMPORT_PARAMETER_TYPES =
|
||||
@@ -232,6 +237,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
case "Tr31KeyBlock" -> exportTr31(region, key, clear, material);
|
||||
case "KeyCryptogram" -> exportCryptogram(region, key, clear, material);
|
||||
case "Tr34KeyBlock" -> exportTr34(region, key, clear, material);
|
||||
case "As2805KeyCryptogram" -> exportAs2805(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) + ")");
|
||||
@@ -345,6 +351,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
case "Tr31KeyBlock" -> importTr31(region, material);
|
||||
case "KeyCryptogram" -> importCryptogram(material);
|
||||
case "Tr34KeyBlock" -> importTr34(region, material);
|
||||
case "As2805KeyCryptogram" -> importAs2805(region, material);
|
||||
case "RootCertificatePublicKey" -> importPublicKey(region, material, "");
|
||||
case "TrustedCertificatePublicKey" -> importPublicKey(region, material,
|
||||
text(material, "CertificateAuthorityPublicKeyIdentifier"));
|
||||
@@ -536,7 +543,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
Map<String, Object> derivationData = object(material, "DerivationData");
|
||||
String sharedInformation = derivationData == null
|
||||
? "" : text(derivationData, "SharedInformation");
|
||||
if (sharedInformation.isEmpty() || !isHex(sharedInformation)) {
|
||||
if (sharedInformation.isEmpty() || !Bytes.isHex(sharedInformation)) {
|
||||
throw validation("KeyMaterial.DiffieHellmanTr31KeyBlock.DerivationData."
|
||||
+ "SharedInformation must be a hexadecimal string");
|
||||
}
|
||||
@@ -748,7 +755,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
}
|
||||
}
|
||||
|
||||
/** The clear material of a key, which an export needs. */
|
||||
/** The clear material of a key. */
|
||||
private static byte[] clearMaterial(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyKeyRules.material(key);
|
||||
}
|
||||
@@ -820,19 +827,22 @@ final class PaymentCryptographyKeyExchange {
|
||||
return value instanceof Map<?, ?> map ? (Map<String, Object>) map : Map.of();
|
||||
}
|
||||
|
||||
/** Whether a string is hexadecimal. */
|
||||
private static boolean isHex(String text) {
|
||||
if (text == null || text.isEmpty() || text.length() % 2 != 0) {
|
||||
return false;
|
||||
/**
|
||||
* Refuses a key that is not TDES, and returns its algorithm: AS2805
|
||||
* cryptography is all TDES.
|
||||
*
|
||||
* @param algorithmName the key's algorithm
|
||||
* @param role what the key is, for the refusal
|
||||
* @return the algorithm
|
||||
*/
|
||||
private static PaymentCryptographyKeyAlgorithm requireTdes(String algorithmName, String role) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
PaymentCryptographyKeyAlgorithm.from(algorithmName);
|
||||
if (algorithm == null || !algorithm.isTdes()) {
|
||||
throw validation("an AS2805 key is a TDES key, but the " + role + " is "
|
||||
+ algorithmName);
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
boolean hex = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
|
||||
if (!hex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return algorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1257,7 +1267,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
throw notFound(token);
|
||||
}
|
||||
String nonce = text(material, "RandomNonce");
|
||||
if (!nonce.isEmpty() && !isHex(nonce)) {
|
||||
if (!nonce.isEmpty() && !Bytes.isHex(nonce)) {
|
||||
throw validation("KeyMaterial.Tr34KeyBlock.RandomNonce must be hexadecimal");
|
||||
}
|
||||
// The headers the request names are the ones the block carries, the optional
|
||||
@@ -1274,8 +1284,78 @@ final class PaymentCryptographyKeyExchange {
|
||||
return new Exported(HEX_UPPER.formatHex(block), "TR34_KEY_BLOCK", null);
|
||||
}
|
||||
|
||||
/** An AS2805 cryptogram, under a key encryption key. */
|
||||
private Exported exportAs2805(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 variant is one of the four and the wrapping key is named. The rule stays
|
||||
// because the variant also says what the key is for, so a call that goes past the
|
||||
// shape check is refused by the service's own rules instead of carrying a variant
|
||||
// that names nothing.
|
||||
PaymentCryptographyAs2805Variant variant = as2805Variant(material);
|
||||
// The variant says what the key is for, so it has to be the variant the key's own
|
||||
// usage calls for. A key exported under another variant would come back with the
|
||||
// other variant's usage, so the export would change what the key is for.
|
||||
if (!variant.usage().equals(key.getKeyUsage())) {
|
||||
throw validation("the AS2805 variant " + variant.name() + " is for a key whose "
|
||||
+ "usage is " + variant.usage() + ", but the key " + key.getArn() + " is "
|
||||
+ key.getKeyUsage());
|
||||
}
|
||||
String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier");
|
||||
PaymentCryptographyKey kek = usableKey(wrappingKeyIdentifier, region);
|
||||
if (!PaymentCryptographyService.mayWrap(kek)) {
|
||||
throw validation("the key " + kek.getArn() + " does not have the mode of use Wrap, "
|
||||
+ "which it needs to wrap a key cryptogram");
|
||||
}
|
||||
requireKeyEncryptionKey(kek);
|
||||
requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn());
|
||||
// AS2805's cryptography is all TDES, so only TDES keys leave and come back in
|
||||
// an AS2805 cryptogram.
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
requireTdes(key.getKeyAlgorithm(), "key " + key.getArn());
|
||||
String tooWeak = PaymentCryptographyKeyStrength.refusal(kek.getKeyAlgorithm(),
|
||||
key.getKeyAlgorithm());
|
||||
if (tooWeak != null) {
|
||||
throw validation(tooWeak);
|
||||
}
|
||||
String cryptogram = PaymentCryptographyAs2805Cryptogram.wrap(clear, variant.variantByte(),
|
||||
algorithm, clearMaterial(kek));
|
||||
return new Exported(cryptogram, "KEY_CRYPTOGRAM", kek.getArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* The AS2805 variant a request names.
|
||||
*
|
||||
* <p>The lookup and the refusal live here, so the export and the import refuse the
|
||||
* same variants in the same words.
|
||||
*
|
||||
* @param material the request's key material
|
||||
* @return the variant
|
||||
*/
|
||||
private static PaymentCryptographyAs2805Variant as2805Variant(Map<String, Object> material) {
|
||||
String name = text(material, "As2805KeyVariant");
|
||||
PaymentCryptographyAs2805Variant variant = PaymentCryptographyAs2805Variant.from(name);
|
||||
if (variant == null) {
|
||||
throw validation("KeyMaterial.As2805KeyCryptogram.As2805KeyVariant '" + name
|
||||
+ "' not supported (" + PaymentCryptographyAs2805Variant.names() + ")");
|
||||
}
|
||||
return variant;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a cryptogram is wrapped under has to be a key encryption key.
|
||||
*
|
||||
* <p>The import insists on it, so an export that accepted any other key would produce
|
||||
* something its own import rejects.
|
||||
*
|
||||
* @param kek the wrapping key
|
||||
*/
|
||||
private static void requireKeyEncryptionKey(PaymentCryptographyKey kek) {
|
||||
if (!"TR31_K0_KEY_ENCRYPTION_KEY".equals(kek.getKeyUsage())) {
|
||||
throw validation("an AS2805 cryptogram is wrapped under a key encryption key, but "
|
||||
+ kek.getArn() + " is " + kek.getKeyUsage());
|
||||
}
|
||||
}
|
||||
|
||||
/** A key out of a TR-34 key block. */
|
||||
private Imported importTr34(String region, Map<String, Object> material) {
|
||||
@@ -1311,7 +1391,7 @@ final class PaymentCryptographyKeyExchange {
|
||||
// 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)) {
|
||||
if (!nonce.isEmpty() && !Bytes.isHex(nonce)) {
|
||||
throw validation("KeyMaterial.Tr34KeyBlock.RandomNonce must be hexadecimal");
|
||||
}
|
||||
Tr34.Recovered recovered;
|
||||
@@ -1351,5 +1431,56 @@ final class PaymentCryptographyKeyExchange {
|
||||
exportableOnImport(exportability), clear, null, null, null, "SYMMETRIC_KEY");
|
||||
}
|
||||
|
||||
/** A key out of an AS2805 cryptogram. */
|
||||
private Imported importAs2805(String region, Map<String, Object> material) {
|
||||
// The shape check settles the members the model requires and the values it names,
|
||||
// so the variant is one of the four and the wrapping key is named. The rule stays
|
||||
// because the variant also says what the key is for, so a call that goes past the
|
||||
// shape check is refused by the service's own rules instead of carrying a variant
|
||||
// that names nothing.
|
||||
PaymentCryptographyAs2805Variant variant = as2805Variant(material);
|
||||
String wrappingKeyIdentifier = text(material, "WrappingKeyIdentifier");
|
||||
PaymentCryptographyKey kek = usableKey(wrappingKeyIdentifier, region);
|
||||
requireKeyEncryptionKey(kek);
|
||||
requireTdes(kek.getKeyAlgorithm(), "AS2805 wrapping key " + kek.getArn());
|
||||
// The wrapping key opens an incoming cryptogram, so it has to be allowed to unwrap.
|
||||
// The model names no error code of its own for this, so it is a validation error,
|
||||
// as the rest of the refusals about a key's modes of use are.
|
||||
if (!PaymentCryptographyService.mayUnwrap(kek)) {
|
||||
throw validation("the key " + kek.getArn() + " does not have the mode of use Unwrap, "
|
||||
+ "which it needs to unwrap a key");
|
||||
}
|
||||
String cryptogram = text(material, "WrappedKeyCryptogram");
|
||||
String algorithmName = text(material, "KeyAlgorithm");
|
||||
// AS2805's cryptography is all TDES, so only TDES keys leave and come back in
|
||||
// an AS2805 cryptogram.
|
||||
PaymentCryptographyKeyAlgorithm algorithm = requireTdes(algorithmName, "carried key");
|
||||
// The wrapping key has to be at least as strong as the key it protects, the same
|
||||
// rule the export enforces, so a cryptogram that the export would refuse to write
|
||||
// does not open here either.
|
||||
String tooWeak = PaymentCryptographyKeyStrength.refusal(kek.getKeyAlgorithm(),
|
||||
algorithmName);
|
||||
if (tooWeak != null) {
|
||||
throw validation(tooWeak);
|
||||
}
|
||||
// The material of the wrapping key is read before the cryptogram is opened, so a
|
||||
// key whose material is not held is refused with that reason and not with a
|
||||
// cryptogram that did not open.
|
||||
byte[] kekMaterial = clearMaterial(kek);
|
||||
byte[] clear;
|
||||
try {
|
||||
clear = PaymentCryptographyAs2805Cryptogram.unwrap(cryptogram, variant.variantByte(),
|
||||
algorithm, kekMaterial);
|
||||
} catch (RuntimeException e) {
|
||||
throw validation("the AS2805 cryptogram did not open: " + e.getMessage());
|
||||
}
|
||||
// The model carries the modes of use and the exportability at the top level of the
|
||||
// AS2805 import, and it names no usage: the variant says what the key is for.
|
||||
Map<String, Boolean> modes = modesOf(material);
|
||||
String usage = variant.usage();
|
||||
boolean exportable = Boolean.TRUE.equals(material.get("Exportable"));
|
||||
return new Imported(algorithmName, usage, modes, exportable, clear, null, null, null,
|
||||
"SYMMETRIC_KEY");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
/**
|
||||
* Byte array helpers shared across the data-plane ciphers.
|
||||
*
|
||||
* <p>Each method is static and stateless, so there is no need for an instance.
|
||||
*/
|
||||
public final class Bytes {
|
||||
|
||||
private Bytes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenate byte arrays into one.
|
||||
*
|
||||
* @param parts the arrays to join, in order
|
||||
* @return a single array containing all the bytes
|
||||
*/
|
||||
public static byte[] concat(byte[]... parts) {
|
||||
int n = 0;
|
||||
for (byte[] p : parts) {
|
||||
n += p.length;
|
||||
}
|
||||
byte[] out = new byte[n];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* PKCS#5/PKCS#7 padding.
|
||||
*
|
||||
* <p>A whole block is added when the input already fills one, so the
|
||||
* padding is never ambiguous.
|
||||
*
|
||||
* @param data the bytes to pad
|
||||
* @param blockSize the block size to pad to
|
||||
* @return the padded bytes
|
||||
*/
|
||||
public static byte[] pkcs7Pad(byte[] data, int blockSize) {
|
||||
int padLength = blockSize - (data.length % blockSize);
|
||||
byte[] out = new byte[data.length + padLength];
|
||||
System.arraycopy(data, 0, out, 0, data.length);
|
||||
for (int i = 0; i < padLength; i++) {
|
||||
out[data.length + i] = (byte) padLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip PKCS#5/PKCS#7 padding, and refuse anything that is not properly padded.
|
||||
*
|
||||
* @param data the padded bytes
|
||||
* @param blockSize the block size the padding works to
|
||||
* @return the unpadded bytes
|
||||
* @throws IllegalArgumentException when the data is not whole-block or
|
||||
* not properly padded
|
||||
*/
|
||||
public static byte[] pkcs7Unpad(byte[] data, int blockSize) {
|
||||
if (data.length == 0 || data.length % blockSize != 0) {
|
||||
throw new IllegalArgumentException("the data is not whole blocks");
|
||||
}
|
||||
int padLength = data[data.length - 1] & 0xFF;
|
||||
if (padLength < 1 || padLength > blockSize || padLength > data.length) {
|
||||
throw new IllegalArgumentException("the padding is not valid");
|
||||
}
|
||||
for (int i = data.length - padLength; i < data.length; i++) {
|
||||
if ((data[i] & 0xFF) != padLength) {
|
||||
throw new IllegalArgumentException("the padding is not valid");
|
||||
}
|
||||
}
|
||||
byte[] out = new byte[data.length - padLength];
|
||||
System.arraycopy(data, 0, out, 0, out.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a string is non-empty and entirely hexadecimal.
|
||||
*
|
||||
* @param text the string to check
|
||||
* @return true if the string is a hex sequence of even length
|
||||
*/
|
||||
public static boolean isHex(String text) {
|
||||
if (text == null || text.isEmpty() || text.length() % 2 != 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
boolean digit = c >= '0' && c <= '9';
|
||||
boolean lower = c >= 'a' && c <= 'f';
|
||||
boolean upper = c >= 'A' && c <= 'F';
|
||||
if (!digit && !lower && !upper) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ public final class DukptCrypto {
|
||||
throw new IllegalArgumentException("BDK must be a 16-byte (double-length TDES) key");
|
||||
}
|
||||
byte[] left8 = Arrays.copyOfRange(zeroCounter(normalizeKsn(ksnHex)), 0, 8);
|
||||
return concat(
|
||||
return Bytes.concat(
|
||||
Ciphers.tdes2Encrypt(left8, bdk),
|
||||
Ciphers.tdes2Encrypt(left8, Ciphers.xor(bdk, KEY_VARIANT)));
|
||||
}
|
||||
@@ -81,7 +81,7 @@ public final class DukptCrypto {
|
||||
/** The X9.24-1 non-reversible key generation step, the single-DES "black box". */
|
||||
public static byte[] deriveStep(byte[] key16, byte[] reg8) {
|
||||
// Order matters: the variant-keyed half comes first.
|
||||
return concat(right(Ciphers.xor(key16, KEY_VARIANT), reg8), right(key16, reg8));
|
||||
return Bytes.concat(right(Ciphers.xor(key16, KEY_VARIANT), reg8), right(key16, reg8));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,17 +127,4 @@ public final class DukptCrypto {
|
||||
return Ciphers.xor(Ciphers.tdesSingleDesEncrypt(Ciphers.xor(reg8, kr), kl), kr);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int n = 0;
|
||||
for (byte[] p : parts) {
|
||||
n += p.length;
|
||||
}
|
||||
byte[] out = new byte[n];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,7 @@ public final class EmvCrypto {
|
||||
for (int i = 0; i < 8; i++) {
|
||||
zr[i] = (byte) (y[i] ^ 0xff);
|
||||
}
|
||||
return adjustDesParity(concat(
|
||||
return adjustDesParity(Bytes.concat(
|
||||
Ciphers.tdes2Encrypt(y, imk16),
|
||||
Ciphers.tdes2Encrypt(zr, imk16)));
|
||||
}
|
||||
@@ -191,7 +191,7 @@ public final class EmvCrypto {
|
||||
for (int i = 0; i < 8; i++) {
|
||||
zr[i] = (byte) (zl[i] ^ 0xff);
|
||||
}
|
||||
return adjustDesParity(concat(
|
||||
return adjustDesParity(Bytes.concat(
|
||||
Ciphers.tdes2Encrypt(zl, imk16),
|
||||
Ciphers.tdes2Encrypt(zr, imk16)));
|
||||
}
|
||||
@@ -244,7 +244,7 @@ public final class EmvCrypto {
|
||||
f1[2] = (byte) 0xf0;
|
||||
byte[] f2 = r.clone();
|
||||
f2[2] = (byte) 0x0f;
|
||||
return adjustDesParity(concat(
|
||||
return adjustDesParity(Bytes.concat(
|
||||
Ciphers.tdes2Encrypt(f1, mk16),
|
||||
Ciphers.tdes2Encrypt(f2, mk16)));
|
||||
}
|
||||
@@ -287,7 +287,7 @@ public final class EmvCrypto {
|
||||
*/
|
||||
public static byte[] computeArpcMethod2(byte[] sk, byte[] arqc,
|
||||
String csuHex, String padHex) {
|
||||
byte[] data = concat(
|
||||
byte[] data = Bytes.concat(
|
||||
arqc,
|
||||
csuHex == null ? new byte[0] : HEX.parseHex(csuHex),
|
||||
padHex == null ? new byte[0] : HEX.parseHex(padHex));
|
||||
@@ -332,17 +332,4 @@ public final class EmvCrypto {
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... parts) {
|
||||
int n = 0;
|
||||
for (byte[] p : parts) {
|
||||
n += p.length;
|
||||
}
|
||||
byte[] out = new byte[n];
|
||||
int at = 0;
|
||||
for (byte[] p : parts) {
|
||||
System.arraycopy(p, 0, out, at, p.length);
|
||||
at += p.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -245,7 +245,7 @@ public final class Tr34 {
|
||||
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[] padded = Bytes.pkcs7Pad(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);
|
||||
@@ -273,7 +273,7 @@ public final class Tr34 {
|
||||
// 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)),
|
||||
byte[] envelope = Bytes.concat(encoded(new ASN1Integer(0)),
|
||||
encoded(new DERSet(new DERSequence(recipientInfo))),
|
||||
encoded(new DERSequence(encryptedContentInfo)));
|
||||
|
||||
@@ -680,16 +680,6 @@ public final class Tr34 {
|
||||
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 {
|
||||
@@ -731,18 +721,4 @@ public final class Tr34 {
|
||||
+ 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;
|
||||
}
|
||||
}
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.util.HexFormat;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* The AS2805 key cryptogram.
|
||||
*
|
||||
* <p>The cryptogram is this emulator's own construction, so the tests here are about the
|
||||
* rules it has to follow: a cryptogram opens under the key it was wrapped under and under
|
||||
* the variant it was bound to, and a cryptogram that was changed in any way does not open
|
||||
* at all.
|
||||
*/
|
||||
class PaymentCryptographyAs2805CryptogramTest {
|
||||
|
||||
/** The hexadecimal the cryptograms are written in. */
|
||||
private static final HexFormat HEX = HexFormat.of().withUpperCase();
|
||||
|
||||
/** The variant the PIN encryption key is bound to. */
|
||||
private static final int PIN_VARIANT = 0x1C;
|
||||
|
||||
/** The variant the data encryption key is bound to. */
|
||||
private static final int DATA_VARIANT = 0x16;
|
||||
|
||||
/** The length of the marker, in bytes. */
|
||||
private static final int MARKER_BYTES = 4;
|
||||
|
||||
/** The length of the initialization vector, in bytes: the Triple DES block size. */
|
||||
private static final int IV_BYTES = 8;
|
||||
|
||||
/** The length of the tag, in bytes. */
|
||||
private static final int TAG_BYTES = 32;
|
||||
|
||||
/** The byte the key the cryptogram carries starts at. */
|
||||
private static final int KEY_SEED = 0x00;
|
||||
|
||||
/** The byte the other key the cryptogram carries starts at. */
|
||||
private static final int OTHER_KEY_SEED = 0x10;
|
||||
|
||||
/** The byte the wrapping key starts at. */
|
||||
private static final int WRAPPING_KEY_SEED = 0xF0;
|
||||
|
||||
/** The byte the other wrapping key starts at. */
|
||||
private static final int OTHER_WRAPPING_KEY_SEED = 0x20;
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(value = PaymentCryptographyKeyAlgorithm.class,
|
||||
names = {"TDES_2KEY", "TDES_3KEY"})
|
||||
void aCryptogramComesBackUnderTheKeyItWasWrappedUnder(PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
|
||||
String cryptogram = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
byte[] clear = unwrap(cryptogram, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.fromHex(key), clear);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"marker", "ciphertext", "tag"})
|
||||
void aCryptogramThatWasChangedDoesNotOpen(String part) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
String cryptogram = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
String changed = changed(cryptogram, atOf(part, cryptogram));
|
||||
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap(changed, PIN_VARIANT, algorithm, wrappingKey));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramThatCarriesAnotherKeysCiphertextDoesNotOpen() {
|
||||
// The check value inside the cryptogram is the check value of the key the
|
||||
// ciphertext carries, so a ciphertext of another key passes it. The tag is over the
|
||||
// ciphertext, so the substitution is caught.
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
String cryptogram = wrap(keyOf(algorithm.bytes(), KEY_SEED), PIN_VARIANT, algorithm,
|
||||
wrappingKey);
|
||||
String other = wrap(keyOf(algorithm.bytes(), OTHER_KEY_SEED), PIN_VARIANT, algorithm,
|
||||
wrappingKey);
|
||||
|
||||
String spliced = splice(cryptogram, other);
|
||||
|
||||
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap(spliced, PIN_VARIANT, algorithm, wrappingKey));
|
||||
|
||||
assertEquals("the cryptogram did not open under the wrapping key", refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderOneVariantDoesNotOpenUnderAnother() {
|
||||
// The tag is over the variant, so a cryptogram bound to one purpose does not open
|
||||
// under another even though the key it carries is the same.
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
String cryptogram = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap(cryptogram, DATA_VARIANT, algorithm, wrappingKey));
|
||||
|
||||
assertEquals("the cryptogram did not open under the wrapping key", refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramWhoseAlgorithmWasChangedDoesNotOpen() {
|
||||
// The tag is over the algorithm as well, so a cryptogram that names another
|
||||
// algorithm does not open under it.
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
String cryptogram = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap(cryptogram, PIN_VARIANT, PaymentCryptographyKeyAlgorithm.TDES_2KEY,
|
||||
wrappingKey));
|
||||
|
||||
assertEquals("the cryptogram did not open under the wrapping key", refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderOneWrappingKeyDoesNotOpenUnderAnother() {
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
String cryptogram = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap(cryptogram, PIN_VARIANT, algorithm,
|
||||
keyOf(algorithm.bytes(), OTHER_WRAPPING_KEY_SEED)));
|
||||
|
||||
assertEquals("the cryptogram did not open under the wrapping key", refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoCryptogramsOfTheSameKeyAreNotTheSameBytes() {
|
||||
// The vector is fresh for every cryptogram, so the same key under the same wrapping
|
||||
// key does not give the same bytes twice.
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.TDES_3KEY;
|
||||
String key = keyOf(algorithm.bytes(), KEY_SEED);
|
||||
String wrappingKey = keyOf(algorithm.bytes(), WRAPPING_KEY_SEED);
|
||||
|
||||
String first = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
String second = wrap(key, PIN_VARIANT, algorithm, wrappingKey);
|
||||
|
||||
assertNotEquals(first, second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramThatIsNotHexadecimalIsRefused() {
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> unwrap("not hexadecimal", PIN_VARIANT, PaymentCryptographyKeyAlgorithm.TDES_3KEY,
|
||||
keyOf(PaymentCryptographyKeyAlgorithm.TDES_3KEY.bytes(), WRAPPING_KEY_SEED)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The cryptogram of a key under a wrapping key.
|
||||
*
|
||||
* <p>The cryptogram is written under Triple DES, the cipher AS2805 uses.
|
||||
*
|
||||
* @param key the key that is carried, in hexadecimal
|
||||
* @param variant the variant the key is bound to
|
||||
* @param algorithm the algorithm of the key
|
||||
* @param wrappingKey the key the cryptogram is wrapped under, in hexadecimal
|
||||
* @return the cryptogram, in hexadecimal
|
||||
*/
|
||||
private static String wrap(String key, int variant, PaymentCryptographyKeyAlgorithm algorithm,
|
||||
String wrappingKey) {
|
||||
return PaymentCryptographyAs2805Cryptogram.wrap(
|
||||
PaymentCryptographyCrypto.fromHex(key), variant, algorithm,
|
||||
PaymentCryptographyCrypto.fromHex(wrappingKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a cryptogram opens under.
|
||||
*
|
||||
* @param cryptogram the cryptogram, in hexadecimal
|
||||
* @param variant the variant the key is bound to
|
||||
* @param algorithm the algorithm of the key
|
||||
* @param wrappingKey the key the cryptogram is wrapped under, in hexadecimal
|
||||
* @return the clear key
|
||||
*/
|
||||
private static byte[] unwrap(String cryptogram, int variant,
|
||||
PaymentCryptographyKeyAlgorithm algorithm, String wrappingKey) {
|
||||
return PaymentCryptographyAs2805Cryptogram.unwrap(cryptogram, variant, algorithm,
|
||||
PaymentCryptographyCrypto.fromHex(wrappingKey));
|
||||
}
|
||||
|
||||
/**
|
||||
* A key of the given length, in hexadecimal.
|
||||
*
|
||||
* <p>The seed tells the key apart from the other keys of the same length, so a key and
|
||||
* the wrapping key that carries it are never the same bytes.
|
||||
*
|
||||
* @param length the length of the key, in bytes
|
||||
* @param seed the byte the key starts at
|
||||
* @return the key
|
||||
*/
|
||||
private static String keyOf(int length, int seed) {
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
hex.append(String.format("%02X", (seed + i) & 0xFF));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The byte a part of the cryptogram is at.
|
||||
*
|
||||
* @param part the part of the cryptogram
|
||||
* @param cryptogram the cryptogram, in hexadecimal
|
||||
* @return the byte, counting from the front
|
||||
*/
|
||||
private static int atOf(String part, String cryptogram) {
|
||||
return switch (part) {
|
||||
case "marker" -> 0;
|
||||
case "ciphertext" -> MARKER_BYTES + IV_BYTES;
|
||||
case "tag" -> HEX.parseHex(cryptogram).length - 1;
|
||||
default -> throw new IllegalArgumentException("no part named " + part);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The cryptogram with one of its bytes changed.
|
||||
*
|
||||
* @param cryptogram the cryptogram, in hexadecimal
|
||||
* @param at the byte that is changed, counting from the front
|
||||
* @return the changed cryptogram
|
||||
*/
|
||||
private static String changed(String cryptogram, int at) {
|
||||
byte[] bytes = HEX.parseHex(cryptogram);
|
||||
bytes[at] = (byte) (bytes[at] ^ 0x01);
|
||||
return HEX.formatHex(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* One cryptogram with the encrypted part of another one.
|
||||
*
|
||||
* <p>The marker and the tag are the first one's, and the vector and the ciphertext are
|
||||
* the second one's, so the ciphertext is not the one the tag was made over. The
|
||||
* ciphertext decrypts under the first cryptogram's own vector, because the second
|
||||
* cryptogram carries its own.
|
||||
*
|
||||
* @param cryptogram the cryptogram the marker and the tag come from
|
||||
* @param other the cryptogram the vector and the ciphertext come from
|
||||
* @return the spliced cryptogram
|
||||
*/
|
||||
private static String splice(String cryptogram, String other) {
|
||||
byte[] first = HEX.parseHex(cryptogram);
|
||||
byte[] second = HEX.parseHex(other);
|
||||
byte[] spliced = new byte[first.length];
|
||||
System.arraycopy(first, 0, spliced, 0, MARKER_BYTES);
|
||||
System.arraycopy(second, MARKER_BYTES, spliced, MARKER_BYTES,
|
||||
second.length - MARKER_BYTES - TAG_BYTES);
|
||||
System.arraycopy(first, first.length - TAG_BYTES, spliced, spliced.length - TAG_BYTES,
|
||||
TAG_BYTES);
|
||||
return HEX.formatHex(spliced);
|
||||
}
|
||||
}
|
||||
+51
-4
@@ -247,18 +247,34 @@ class PaymentCryptographyIntegrationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestNamingAFormTheServiceDoesNotServeIsRefused() {
|
||||
// The AS2805 form is one the model has and this service does not make yet.
|
||||
void theAs2805FormIsServed() {
|
||||
// The AS2805 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\":{"
|
||||
+ "\"As2805KeyCryptogram\":{\"As2805KeyVariant\":"
|
||||
+ "\"PIN_ENCRYPTION_KEY_VARIANT_28\",\"WrappingKeyIdentifier\":\"" + arn + "\"}}}")
|
||||
+ "\"PIN_ENCRYPTION_KEY_VARIANT_28\"}}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", containsString("not a form the service exports"));
|
||||
.body("message", containsString("WrappingKeyIdentifier"));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void aRequestNamingNoFormIsRefused() {
|
||||
// Every form the model names is one the service makes now, so a request that
|
||||
// names none of them names no form at all.
|
||||
String arn = call("CreateKey", CREATE_KEY)
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
|
||||
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{}}")
|
||||
.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
.body("message", containsString("must specify exactly one variant"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -428,6 +444,37 @@ class PaymentCryptographyIntegrationTest {
|
||||
assertTheModelRefused(answer, "WrappedKeyBlock");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnAs2805ExportWithoutItsWrappingKey() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"As2805KeyCryptogram\":{"
|
||||
+ "\"As2805KeyVariant\":\"PIN_ENCRYPTION_KEY_VARIANT_28\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "WrappingKeyIdentifier");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnAs2805ExportUnderAVariantItDoesNotName() {
|
||||
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + keyArn() + "\","
|
||||
+ "\"KeyMaterial\":{\"As2805KeyCryptogram\":{"
|
||||
+ "\"As2805KeyVariant\":\"TERMINAL_MINOR_KEY_VARIANT_01\","
|
||||
+ "\"WrappingKeyIdentifier\":\"" + keyArn() + "\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "As2805KeyVariant");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theModelCheckRefusesAnAs2805ImportWithoutItsWrappedKeyCryptogram() {
|
||||
Response answer = call("ImportKey", "{\"KeyMaterial\":{\"As2805KeyCryptogram\":{"
|
||||
+ "\"As2805KeyVariant\":\"PIN_ENCRYPTION_KEY_VARIANT_28\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true},"
|
||||
+ "\"KeyAlgorithm\":\"AES_256\","
|
||||
+ "\"Exportable\":true,"
|
||||
+ "\"WrappingKeyIdentifier\":\"" + keyArn() + "\"}}}");
|
||||
|
||||
assertTheModelRefused(answer, "WrappedKeyCryptogram");
|
||||
}
|
||||
|
||||
private static void assertTheModelRefused(Response answer, String member) {
|
||||
answer.then().statusCode(400)
|
||||
.body("__type", equalTo("ValidationException"))
|
||||
|
||||
+225
@@ -48,6 +48,15 @@ class PaymentCryptographyKeyExchangeTest {
|
||||
/** The key a key block is wrapped under. */
|
||||
private PaymentCryptographyKey protection;
|
||||
|
||||
/** The variant the PIN encryption key is bound to. */
|
||||
private static final String PIN_VARIANT = "PIN_ENCRYPTION_KEY_VARIANT_28";
|
||||
|
||||
/** The variant the data encryption key is bound to. */
|
||||
private static final String DATA_VARIANT = "DATA_ENCRYPTION_KEY_VARIANT_22";
|
||||
|
||||
/** The variant the terminal major key is bound to. */
|
||||
private static final String MAJOR_VARIANT = "TERMINAL_MAJOR_KEY_VARIANT_00";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new PaymentCryptographyService(
|
||||
@@ -768,6 +777,146 @@ class PaymentCryptographyKeyExchangeTest {
|
||||
() -> service.importKey("us-east-1", "Tr34KeyBlock", incoming, "", true, Map.of()));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrapped key an AS2805 export answers with.
|
||||
*
|
||||
* @param key the key that leaves
|
||||
* @param kek the key the cryptogram is wrapped under
|
||||
* @param variant the variant the key is bound to
|
||||
* @return the wrapped key
|
||||
*/
|
||||
private Map<?, ?> as2805Export(PaymentCryptographyKey key, PaymentCryptographyKey kek,
|
||||
String variant) {
|
||||
Map<String, Object> answer = service.exportKey("us-east-1", key.getKeyId(),
|
||||
"As2805KeyCryptogram", Map.of(
|
||||
"As2805KeyVariant", variant,
|
||||
"WrappingKeyIdentifier", kek.getKeyId()), "", "");
|
||||
return (Map<?, ?>) answer.get("WrappedKey");
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of an AS2805 import.
|
||||
*
|
||||
* @param variant the variant the cryptogram is bound to
|
||||
* @param wrappingKeyId the key the cryptogram is wrapped under
|
||||
* @param cryptogram the cryptogram that comes in
|
||||
* @param algorithm the algorithm of the key that comes in
|
||||
* @param usage the usage of the key that comes in
|
||||
* @return the material
|
||||
*/
|
||||
private static Map<String, Object> as2805Import(String variant, String wrappingKeyId,
|
||||
String cryptogram, String algorithm, String usage) {
|
||||
Map<String, Object> incoming = new LinkedHashMap<>();
|
||||
incoming.put("As2805KeyVariant", variant);
|
||||
incoming.put("WrappingKeyIdentifier", wrappingKeyId);
|
||||
incoming.put("WrappedKeyCryptogram", cryptogram);
|
||||
incoming.put("KeyAlgorithm", algorithm);
|
||||
incoming.put("KeyAttributes", Map.of(
|
||||
"KeyAlgorithm", algorithm,
|
||||
"KeyClass", "SYMMETRIC_KEY",
|
||||
"KeyUsage", usage,
|
||||
"KeyModesOfUse", Map.of("Encrypt", true, "Decrypt", true)));
|
||||
incoming.put("Exportable", true);
|
||||
return incoming;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatLeavesUnderAnAs2805CryptogramComesBack() {
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
Map<?, ?> wrapped = as2805Export(key, kek, PIN_VARIANT);
|
||||
assertEquals("KEY_CRYPTOGRAM", wrapped.get("WrappedKeyMaterialFormat"));
|
||||
|
||||
PaymentCryptographyKey imported = service.importKey("us-east-1", "As2805KeyCryptogram",
|
||||
as2805Import(PIN_VARIANT, kek.getKeyId(), (String) wrapped.get("KeyMaterial"),
|
||||
"TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY"), "", true, Map.of());
|
||||
|
||||
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
|
||||
assertEquals("TR31_P0_PIN_ENCRYPTION_KEY", imported.getKeyUsage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramThatWasChangedDoesNotOpen() {
|
||||
// The cryptogram carries a tag over the whole of it, so a cryptogram that was
|
||||
// changed does not open at all, and not under a key that is wrong but plausible.
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
String cryptogram = (String) as2805Export(key, kek, PIN_VARIANT).get("KeyMaterial");
|
||||
// The character is inside the ciphertext, which is where the key it carries is.
|
||||
String changed = changed(cryptogram, 50);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "As2805KeyCryptogram",
|
||||
as2805Import(PIN_VARIANT, kek.getKeyId(), changed, "TDES_3KEY",
|
||||
"TR31_P0_PIN_ENCRYPTION_KEY"), "", true, Map.of()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAKeyWhoseMaterialIsNotHeldIsRefused() {
|
||||
// The material of a key is held while the emulator runs and is not written to the
|
||||
// store, so a key read back after a restart has none, and the export says so
|
||||
// rather than failing on the missing value.
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
kek.setKeyMaterialHex(null);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "As2805KeyCryptogram",
|
||||
Map.of(
|
||||
"As2805KeyVariant", PIN_VARIANT,
|
||||
"WrappingKeyIdentifier", kek.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("material"), refused.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* The cryptogram with one of its characters changed.
|
||||
*
|
||||
* @param cryptogram the cryptogram, in hexadecimal
|
||||
* @param at the character that is changed, counting from the front
|
||||
* @return the changed cryptogram
|
||||
*/
|
||||
private static String changed(String cryptogram, int at) {
|
||||
char[] characters = cryptogram.toCharArray();
|
||||
characters[at] = characters[at] == 'A' ? 'B' : 'A';
|
||||
return new String(characters);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAVariantTheServiceDoesNotServeIsRefused() {
|
||||
// The model's union names four variants, and the service serves every one of them,
|
||||
// so a variant outside the four names no variant at all.
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "As2805KeyCryptogram",
|
||||
Map.of(
|
||||
"As2805KeyVariant", "TERMINAL_MINOR_KEY_VARIANT_01",
|
||||
"WrappingKeyIdentifier", kek.getKeyId()), "", ""));
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramThatIsWrappedUnderTheWrongVariantDoesNotOpen() {
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
String cryptogram = (String) as2805Export(key, kek, PIN_VARIANT).get("KeyMaterial");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "As2805KeyCryptogram",
|
||||
as2805Import(DATA_VARIANT, kek.getKeyId(), cryptogram, "TDES_3KEY",
|
||||
"TR31_P0_PIN_ENCRYPTION_KEY"), "", 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) {
|
||||
@@ -780,6 +929,82 @@ class PaymentCryptographyKeyExchangeTest {
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("signed with RSA_2048"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAVariantThatIsNotTheKeysPurposeIsRefused() {
|
||||
// The variant says what the key is for, so a key exported under another variant
|
||||
// would come back with the other variant's usage, and the export would change what
|
||||
// the key is for.
|
||||
PaymentCryptographyKey kek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "As2805KeyCryptogram",
|
||||
Map.of(
|
||||
"As2805KeyVariant", MAJOR_VARIANT,
|
||||
"WrappingKeyIdentifier", kek.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCryptogramUnderAWeakerWrappingKeyIsRefused() {
|
||||
// The wrapping key has to be at least as strong as the key it protects, the same
|
||||
// rule the export enforces, so a cryptogram the export would refuse to write does
|
||||
// not open here either.
|
||||
// TDES_2KEY is weaker than TDES_3KEY, so a TDES_2KEY wrapping key cannot protect
|
||||
// a TDES_3KEY key.
|
||||
PaymentCryptographyKey kek = createKey("TDES_2KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
String cryptogram = PaymentCryptographyAs2805Cryptogram.wrap(
|
||||
HexFormat.of().parseHex("000102030405060708090A0B0C0D0E0F1011121314151617"),
|
||||
0x00, PaymentCryptographyKeyAlgorithm.TDES_3KEY,
|
||||
PaymentCryptographyCrypto.fromHex(kek.getKeyMaterialHex()));
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "As2805KeyCryptogram",
|
||||
as2805Import(MAJOR_VARIANT, kek.getKeyId(), cryptogram, "TDES_3KEY",
|
||||
"TR31_K0_KEY_ENCRYPTION_KEY"), "", true, Map.of()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExportUnderAnAesWrappingKeyIsRefused() {
|
||||
// AS2805's cryptography is all TDES, so a key encryption key that is AES cannot
|
||||
// wrap a key cryptogram even though it is a key encryption key.
|
||||
PaymentCryptographyKey kek = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.exportKey("us-east-1", key.getKeyId(), "As2805KeyCryptogram",
|
||||
Map.of(
|
||||
"As2805KeyVariant", PIN_VARIANT,
|
||||
"WrappingKeyIdentifier", kek.getKeyId()), "", ""));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("TDES"), refused.getMessage());
|
||||
assertTrue(refused.getMessage().contains("AES_128"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anImportUnderAnAesWrappingKeyIsRefused() {
|
||||
// The export and the import refuse the same wrapping key, so a cryptogram the
|
||||
// export would not write does not open here either.
|
||||
PaymentCryptographyKey tdesKek = createKey("TDES_3KEY", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
PaymentCryptographyKey key = createKey("TDES_3KEY", "TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
String cryptogram = (String) as2805Export(key, tdesKek, PIN_VARIANT).get("KeyMaterial");
|
||||
PaymentCryptographyKey kek = createKey("AES_128", "TR31_K0_KEY_ENCRYPTION_KEY");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> service.importKey("us-east-1", "As2805KeyCryptogram",
|
||||
as2805Import(PIN_VARIANT, kek.getKeyId(), cryptogram, "TDES_3KEY",
|
||||
"TR31_P0_PIN_ENCRYPTION_KEY"), "", true, Map.of()));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("TDES"), refused.getMessage());
|
||||
assertTrue(refused.getMessage().contains("AES_128"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTr34BlockThatCarriesNoHeaderIsRefused() throws Exception {
|
||||
// A block that is signed correctly but whose key block names no key says nothing
|
||||
|
||||
Reference in new issue
Block a user