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
+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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user