feat(paymentcryptography): the key exchange, with TR-31, RSA-OAEP and ECDH (#7862)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-12 08:59:48 -04:00
1 parent f2a0bfce4e
commit 77d73ee4b7
32 files changed
+5863 -129

No files matched your search

@@ -118,6 +118,11 @@ public final class RequestConstraintCheck {
checkValue(model.path("operations").path(operation).asText(), request, operation);
}
/** Whether the model holds the input shape of {@code operation}. */
public boolean holds(String operation) {
return model.path("operations").has(operation);
}
/** Checks one modeled value without treating it as a whole request. */
public void checkShape(String shapeName, JsonNode value) {
checkValue(shapeName, value, shapeName);
@@ -35,8 +35,8 @@ import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttri
*
* <p>Two derivations are refused rather than approximated. The American Express one is
* proprietary and there is nothing to verify it against, and a plausible wrong cryptogram is
* worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which needs the
* card's public key certificate.
* worse than an error. The EMV 2000 one is the EMV 4.1 tree derivation, which is over the
* master key and the ATC, and this service does not implement it.
*/
@ApplicationScoped
public class PaymentCryptographyAuthCryptogramOperations {
@@ -260,11 +260,9 @@ public class PaymentCryptographyAuthCryptogramOperations {
private static SessionKey resolveDerivation(JsonNode request) {
boolean optionB = "EMV_OPTION_B".equals(text(request, "MajorKeyDerivationMode"));
JsonNode skd = request.get("SessionKeyDerivationAttributes");
if (skd == null) {
throw validation("SessionKeyDerivationAttributes is required");
}
String variant = soleVariant(skd);
// The shape check settles the derivation attributes, so they are there, and the
// attributes must name exactly one variant.
String variant = soleVariant(request.get("SessionKeyDerivationAttributes"));
if (variant == null) {
throw validation("SessionKeyDerivationAttributes must specify exactly one variant");
}
@@ -285,7 +283,7 @@ public class PaymentCryptographyAuthCryptogramOperations {
throw validation("SessionKeyDerivationAttributes." + variant
+ " is not a recognized variant");
}
JsonNode attrs = skd.get(variant);
JsonNode attrs = request.get("SessionKeyDerivationAttributes").get(variant);
String pan = text(attrs, "PrimaryAccountNumber");
String psn = text(attrs, "PanSequenceNumber");
String atc = text(attrs, "ApplicationTransactionCounter");
@@ -234,7 +234,7 @@ public class PaymentCryptographyCardValidationOperations {
}
/**
* Checks that the key has the mode of use the operation needs.
* The error a card request is refused with.
*/
private static AwsException validation(String message) {
return new AwsException("ValidationException", message, 400);
@@ -14,7 +14,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
/**
* The Payment Cryptography control plane.
@@ -35,49 +35,55 @@ public class PaymentCryptographyJsonHandler {
this.service = service;
}
/** The actions whose requests are checked against the vendored model constraints first. */
private static final Set<String> MODEL_CHECKED = Set.of(
"CreateKey", "GetKey", "ListKeys", "DeleteKey",
"CreateAlias", "GetAlias", "ListAliases", "UpdateAlias", "DeleteAlias",
"TagResource", "UntagResource", "ListTagsForResource");
/** The forms the model's export union holds. */
private static final List<String> EXPORT_UNION = List.of("Tr31KeyBlock", "Tr34KeyBlock",
"KeyCryptogram", "DiffieHellmanTr31KeyBlock", "As2805KeyCryptogram");
/** The forms the model's import union holds. */
private static final List<String> IMPORT_UNION = List.of("RootCertificatePublicKey",
"TrustedCertificatePublicKey", "Tr31KeyBlock", "Tr34KeyBlock", "KeyCryptogram",
"DiffieHellmanTr31KeyBlock", "As2805KeyCryptogram");
public Response handle(String action, JsonNode request, String region) {
if (MODEL_CHECKED.contains(action)) {
PaymentCryptographyRequestShapes.check(action, request);
}
return switch (action) {
case "CreateKey" -> Response.ok(createKey(request, region)).build();
case "GetKey" -> Response.ok(getKey(request, region)).build();
case "ListKeys" -> Response.ok(listKeys(request, region)).build();
case "DeleteKey" -> Response.ok(deleteKey(request, region)).build();
case "CreateAlias" -> Response.ok(createAlias(request, region)).build();
case "GetAlias" -> Response.ok(getAlias(request, region)).build();
case "ListAliases" -> Response.ok(listAliases(request, region)).build();
case "UpdateAlias" -> Response.ok(updateAlias(request, region)).build();
case "DeleteAlias" -> Response.ok(deleteAlias(request, region)).build();
case "TagResource" -> Response.ok(tagResource(request, region)).build();
case "UntagResource" -> Response.ok(untagResource(request, region)).build();
case "ListTagsForResource" -> Response.ok(listTagsForResource(request, region)).build();
// The switch names the operation and nothing else, so an operation this class serves
// later cannot go without its model check: the check reads the name from the action.
Supplier<Object> answer = switch (action) {
case "CreateKey" -> () -> createKey(request, region);
case "GetKey" -> () -> getKey(request, region);
case "ListKeys" -> () -> listKeys(request, region);
case "DeleteKey" -> () -> deleteKey(request, region);
case "CreateAlias" -> () -> createAlias(request, region);
case "GetAlias" -> () -> getAlias(request, region);
case "ListAliases" -> () -> listAliases(request, region);
case "UpdateAlias" -> () -> updateAlias(request, region);
case "DeleteAlias" -> () -> deleteAlias(request, region);
case "ExportKey" -> () -> exportKey(request, region);
case "ImportKey" -> () -> importKey(request, region);
case "GetPublicKeyCertificate" -> () -> getPublicKeyCertificate(request, region);
case "GetParametersForImport" -> () -> getParametersForImport(request, region);
case "GetParametersForExport" -> () -> getParametersForExport(request, region);
case "TagResource" -> () -> tagResource(request, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
default -> throw new AwsException("UnknownOperationException",
"Operation " + action + " is not supported by floci", 400);
};
// The vendored model holds every operation it names, so the request is checked against
// the model's own rules without this class listing the operations it serves. The check
// runs after the switch, so an operation the model names and this service does not
// serve is refused as the unknown operation it is, whatever its body says, and it
// runs before the operation does, so a request that breaks the model's rules is
// refused before the operation does any work.
PaymentCryptographyRequestShapes.check(action, request);
return Response.ok(answer.get()).build();
}
// ---- keys ---------------------------------------------------------------
private Map<String, Object> createKey(JsonNode request, String region) {
// The shape check settles the attributes and the members they must carry, so they are
// there and they carry a usage and the modes of use, as the reference requires.
JsonNode attributes = request.get("KeyAttributes");
if (attributes == null || !attributes.isObject()) {
throw new AwsException("ValidationException", "KeyAttributes is required", 400);
}
// The service requires the usage and the modes of use of a key, as the
// reference does: a key without them says nothing about what it is for.
if (!attributes.hasNonNull("KeyUsage")) {
throw new AwsException("ValidationException", "KeyAttributes.KeyUsage is required", 400);
}
if (!attributes.hasNonNull("KeyModesOfUse")) {
throw new AwsException("ValidationException", "KeyAttributes.KeyModesOfUse is required", 400);
}
Map<String, Object> declared = new LinkedHashMap<>();
attributes.fields().forEachRemaining(entry -> {
// KeyModesOfUse is a nested structure, not a name: it is read below
@@ -376,4 +382,144 @@ public class PaymentCryptographyJsonHandler {
}
return out;
}
/**
* The key as it leaves the service, in the form the request names.
*
* <p>The {@code KeyMaterial} union names one form, and the form says how the key is
* protected: a TR-31 block under a key the service holds, an RSA-OAEP cryptogram under
* the receiver's certificate, a TR-34 block the service signs, a block under a key the
* two parties agreed, or an AS2805 cryptogram.
*/
private Map<String, Object> exportKey(JsonNode request, String region) {
// The required members are settled by the shape check before the handler runs, so
// the identifier is read and not checked again.
String keyIdentifier = request.path("ExportKeyIdentifier").asText();
JsonNode material = request.path("KeyMaterial");
String form = soleForm(material, EXPORT_UNION, PaymentCryptographyKeyExchange.EXPORT_FORMS,
"exports");
JsonNode attributes = request.path("ExportAttributes");
return service.exportKey(region, keyIdentifier, form, members(material.path(form)),
initialKeySerialNumber(attributes),
attributes.path("KeyCheckValueAlgorithm").asText());
}
/** The certificate of an asymmetric key. */
private Map<String, Object> getPublicKeyCertificate(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
return service.publicKeyCertificate(key);
}
/**
* The parameters a counterparty needs to import a key into this service: the token the
* import quotes back and the certificate the wrapping key is under.
*/
private Map<String, Object> getParametersForImport(JsonNode request, String region) {
return service.parametersForImport(request.path("KeyMaterialType").asText(),
request.path("WrappingKeyAlgorithm").asText(),
request.path("ReuseLastGeneratedToken").asBoolean(false));
}
/**
* The parameters a counterparty needs to import a key this service exported: the token
* the export quotes back and the certificate the signing key is under.
*/
private Map<String, Object> getParametersForExport(JsonNode request, String region) {
return service.parametersForExport(request.path("KeyMaterialType").asText(),
request.path("SigningKeyAlgorithm").asText(),
request.path("ReuseLastGeneratedToken").asBoolean(false));
}
/**
* The key that comes into the service, in the form the request names.
*/
private Map<String, Object> importKey(JsonNode request, String region) {
JsonNode material = request.path("KeyMaterial");
String form = soleForm(material, IMPORT_UNION, PaymentCryptographyKeyExchange.IMPORT_FORMS,
"imports");
PaymentCryptographyKey key = service.importKey(region, form, members(material.path(form)),
request.path("KeyCheckValueAlgorithm").asText(),
request.path("Enabled").asBoolean(true), tagsOf(request));
return Map.of("Key", keyObject(key));
}
/**
* The serial number of the initial key the request asks to be derived.
*
* <p>The export attributes name the kind of key that leaves: an initial key for the
* DUKPT derivation is derived from the base derivation key and the serial number the
* request gives, and it is that derived key which leaves.
*
* @param attributes the export attributes of the request
* @return the serial number, or an empty string when the request names no initial key
*/
private static String initialKeySerialNumber(JsonNode attributes) {
JsonNode initial = attributes.path("ExportDukptInitialKey");
if (initial.isMissingNode() || initial.isNull()) {
return "";
}
// The serial number is required by the model, so the shape check has settled it.
return initial.path("KeySerialNumber").asText();
}
/**
* The one form of the key material union the request names.
*
* <p>The union holds a member per form, and a request names exactly one of them. Several
* at once is not the same as none: the request says which one it meant, and it cannot be
* more than one.
*/
private static String soleForm(JsonNode material, List<String> union, List<String> served,
String what) {
List<String> named = new ArrayList<>();
for (String form : union) {
if (material.has(form) && !material.path(form).isNull()) {
named.add(form);
}
}
if (named.size() != 1) {
throw new AwsException("ValidationException",
"KeyMaterial must specify exactly one variant (" + String.join(", ", union) + ")",
400);
}
String form = named.get(0);
if (!served.contains(form)) {
throw new AwsException("ValidationException",
"KeyMaterial." + form + " is not a form the service " + what + " ("
+ String.join(", ", served) + ")", 400);
}
return form;
}
/** The members of a form, as the service reads them. */
private static Map<String, Object> members(JsonNode node) {
Map<String, Object> out = new LinkedHashMap<>();
if (node == null || !node.isObject()) {
return out;
}
node.properties().forEach(entry -> out.put(entry.getKey(), value(entry.getValue())));
return out;
}
/** One member of a form, as the service reads it. */
private static Object value(JsonNode node) {
if (node == null || node.isNull()) {
return null;
}
if (node.isObject()) {
return members(node);
}
if (node.isArray()) {
List<Object> values = new ArrayList<>();
node.forEach(child -> values.add(value(child)));
return values;
}
if (node.isBoolean()) {
return node.asBoolean();
}
if (node.isNumber()) {
return node.asText();
}
return node.asText();
}
}
@@ -12,6 +12,13 @@ import io.floci.aws.core.common.RequestConstraintCheck;
* of a key, the ARN of an alias or the name of an alias, while {@code KeyArn} and {@code ResourceArn}
* take the ARN of a key alone. A violation is a {@code ValidationException}, with the member's path
* from the request's top level.
*
* <p>The vendored file holds every operation the model names, so an operation the service serves
* is checked without anyone listing it. An operation the model does not name is not checked, and
* the service refuses it as the operation it does not serve.
*
* <p>Only the operations the service serves are checked: an operation the model names and the
* service does not serve is refused as the unknown operation it is, whatever its body says.
*/
final class PaymentCryptographyRequestShapes {
@@ -23,6 +30,9 @@ final class PaymentCryptographyRequestShapes {
}
static void check(String operation, JsonNode request) {
if (!CHECK.holds(operation)) {
return;
}
CHECK.check(operation, request);
}
}
@@ -11,6 +11,8 @@ import io.floci.aws.core.common.StoredResourceArns;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
@@ -18,6 +20,7 @@ import jakarta.inject.Inject;
import java.security.KeyPair;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
@@ -64,23 +67,34 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
/** The class of a key that is only a public half. */
private static final String PUBLIC_KEY_CLASS = "PUBLIC_KEY";
/** The origin of a key the service made itself. */
private static final String ORIGIN_SERVICE = "AWS_PAYMENT_CRYPTOGRAPHY";
/** The origin of a key whose material came in from outside the service. */
private static final String ORIGIN_EXTERNAL = "EXTERNAL";
private final StorageBackend<String, PaymentCryptographyKey> keyStore;
private final StorageBackend<String, PaymentCryptographyAlias> aliasStore;
/** The key exchange: the forms a key may leave in, and the certificates that carry them. */
private final PaymentCryptographyKeyExchange exchange;
private final RegionResolver regionResolver;
private final SecureRandom secureRandom;
private final PaymentCryptographyRequestContext requestContext;
@Inject
public PaymentCryptographyService(StorageFactory storageFactory, RegionResolver regionResolver,
PaymentCryptographyRequestContext requestContext) {
PaymentCryptographyRequestContext requestContext,
CertificateGenerator certificates) {
this(storageFactory.create(STORAGE_KEY, "payment-cryptography-keys.json",
new TypeReference<>() {}),
storageFactory.create(STORAGE_KEY, "payment-cryptography-aliases.json",
new TypeReference<>() {}),
regionResolver,
new SecureRandom(),
requestContext);
requestContext,
certificates,
Clock.systemUTC());
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
@@ -108,9 +122,21 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
RegionResolver regionResolver,
SecureRandom secureRandom,
PaymentCryptographyRequestContext requestContext) {
this(keyStore, aliasStore, regionResolver, secureRandom, requestContext,
new CertificateGenerator(), Clock.systemUTC());
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
RegionResolver regionResolver,
SecureRandom secureRandom,
PaymentCryptographyRequestContext requestContext,
CertificateGenerator certificates,
Clock clock) {
this.keyStore = keyStore;
this.aliasStore = aliasStore;
this.regionResolver = regionResolver;
this.exchange = new PaymentCryptographyKeyExchange(this, certificates, clock);
this.secureRandom = secureRandom;
this.requestContext = requestContext;
}
@@ -135,7 +161,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
boolean enabled, Map<String, String> tags,
String materialHex) {
return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, materialHex,
null, null, null);
null, null, null, ORIGIN_SERVICE);
}
/**
@@ -148,12 +174,14 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
* @param publicKeyBase64 the public half of an asymmetric key, or null
* @param privateKeyBase64 the private half of an asymmetric key, or null
* @param certificatePem the certificate an imported public key arrived with, or null
* @param origin where the key material came from
*/
private PaymentCryptographyKey makeKey(String region, Map<String, Object> attributes,
Map<String, Boolean> modesOfUse, boolean exportable,
boolean enabled, Map<String, String> tags,
String materialHex, String publicKeyBase64,
String privateKeyBase64, String certificatePem) {
String privateKeyBase64, String certificatePem,
String origin) {
String algorithmName = string(attributes, "KeyAlgorithm", "AES_256");
String keyClass = string(attributes, "KeyClass", "SYMMETRIC_KEY");
// The material has to be the algorithm's, so a key that says otherwise would be a key
@@ -212,6 +240,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
key.setKeyPublicKeyBase64(publicKeyBase64);
key.setKeyPrivateKeyBase64(privateKeyBase64);
key.setKeyCertificatePem(certificatePem);
key.setKeyOrigin(origin);
if (algorithm.symmetric()) {
key.setKeyMaterialHex(materialHex != null
? materialHex
@@ -527,6 +556,182 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
// ---- the key exchange ----------------------------------------------------
/**
* The key as it leaves the service, in the form the request names.
*
* <p>A key that is not exportable does not leave. The form decides how it is protected: a
* TR-31 block under a key the service holds, an RSA-OAEP cryptogram under the receiver's
* certificate, a TR-34 block the service signs, a block under a key the two parties
* agreed, or an AS2805 cryptogram.
*
* @param region the region the key is in
* @param keyIdentifier the key that leaves
* @param form the form the request names
* @param material the members of the form
* @return the material, the format it is in, and the key that protects it
*/
public Map<String, Object> exportKey(String region, String keyIdentifier, String form,
Map<String, Object> material, String keySerialNumber,
String checkValueAlgorithm) {
PaymentCryptographyKey key = findKey(region, keyIdentifier);
if (key == null) {
throw new AwsException("ResourceNotFoundException", "Key not found: " + keyIdentifier, 400);
}
PaymentCryptographyKeyRules.requireEnabled(key);
// An initial key leaves instead of the key itself: the service derives it and does
// not keep it.
PaymentCryptographyKey leaving = keySerialNumber.isEmpty() ? key : initialKey(key, keySerialNumber);
if (!checkValueAlgorithm.isEmpty()
&& !checkValueAlgorithm.equals(leaving.getKeyCheckValueAlgorithm())) {
throw new AwsException("ValidationException",
"the check value algorithm " + checkValueAlgorithm + " is not the one the key "
+ leaving.getArn() + " has, which is "
+ leaving.getKeyCheckValueAlgorithm(), 400);
}
if (!leaving.isExportable() && keySerialNumber.isEmpty()) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is not exportable", 400);
}
PaymentCryptographyKeyExchange.Exported exported = exchange.export(region, leaving, form, material);
Map<String, Object> wrapped = new LinkedHashMap<>();
wrapped.put("KeyMaterial", exported.material());
wrapped.put("WrappedKeyMaterialFormat", exported.format());
// The check value belongs to a key block: a cryptogram carries no block, so it has no
// check value either, which is what the reference answers.
if (!"KEY_CRYPTOGRAM".equals(exported.format())) {
wrapped.put("KeyCheckValue", leaving.getKeyCheckValue());
wrapped.put("KeyCheckValueAlgorithm", leaving.getKeyCheckValueAlgorithm());
}
if (exported.wrappingKeyArn() != null) {
wrapped.put("WrappingKeyArn", exported.wrappingKeyArn());
}
return Map.of("WrappedKey", wrapped);
}
/**
* The key that comes into the service, in the form the request names.
*
* @param region the region the key comes into
* @param form the form the request names
* @param material the members of the form
* @return the key
*/
public PaymentCryptographyKey importKey(String region, String form, Map<String, Object> material,
String checkValueAlgorithm, boolean enabled,
Map<String, String> tags) {
PaymentCryptographyKeyExchange.Imported imported = exchange.importKey(region, form, material);
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", imported.algorithm());
attributes.put("KeyClass", imported.keyClass());
attributes.put("KeyUsage", imported.usage());
if (!checkValueAlgorithm.isEmpty()) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(imported.algorithm());
String own = algorithm == null ? "" : algorithm.checkValueAlgorithm();
if (!checkValueAlgorithm.equals(own)) {
throw new AwsException("ValidationException",
"the check value algorithm " + checkValueAlgorithm + " is not the one a "
+ imported.algorithm() + " key has, which is " + own, 400);
}
}
return makeKey(region, attributes, imported.modes(), imported.exportable(), enabled, tags,
imported.material() == null ? null
: PaymentCryptographyCrypto.toHex(imported.material()),
imported.publicKeyBase64(), imported.privateKeyBase64(), imported.certificatePem(),
ORIGIN_EXTERNAL);
}
/**
* The initial key of the DUKPT derivation, derived from a base derivation key.
*
* <p>The derived key is a PIN encryption key of sixteen bytes, and it does not leave the
* service again: what leaves is the derived key, not the base one.
*
* @param base the base derivation key
* @param keySerialNumber the serial number of the key the derivation starts from
* @return the derived key, as the key that leaves
*/
private static PaymentCryptographyKey initialKey(PaymentCryptographyKey base,
String keySerialNumber) {
if (!"TR31_B0_BASE_DERIVATION_KEY".equals(base.getKeyUsage())) {
throw new AwsException("ValidationException",
"an initial key under export is derived from a base derivation key, but "
+ base.getArn() + " is " + base.getKeyUsage(), 400);
}
byte[] initial;
try {
initial = DukptCrypto.deriveIpek(PaymentCryptographyKeyRules.materialHex(base),
keySerialNumber);
} catch (RuntimeException e) {
throw new AwsException("ValidationException",
"the initial key could not be derived: " + e.getMessage(), 400);
}
PaymentCryptographyKey derived = new PaymentCryptographyKey();
derived.setKeyId(base.getKeyId());
derived.setArn(base.getArn());
derived.setRegion(base.getRegion());
derived.setKeyAlgorithm("TDES_2KEY");
derived.setKeyClass("SYMMETRIC_KEY");
// The standard gives the key derived from a base derivation key the usage of an
// initial derivation key, and the mode of a derivable one.
derived.setKeyUsage("TR31_B1_INITIAL_DERIVATION_KEY");
derived.setKeyModesOfUse(new LinkedHashMap<>(Map.of("DeriveKey", Boolean.TRUE)));
derived.setKeyMaterialHex(PaymentCryptographyCrypto.toHex(initial));
derived.setKeyCheckValue(PaymentCryptographyCrypto.checkValue(derived.getKeyMaterialHex(),
PaymentCryptographyKeyAlgorithm.TDES_2KEY));
derived.setKeyCheckValueAlgorithm("ANSI_X9_24");
// The derived key is for the counterparty's use and does not leave again.
derived.setExportable(false);
return derived;
}
/**
* The number of exchange tokens the service holds.
*
* <p>For the test that watches the expired ones swept.
*
* @return how many tokens are held
*/
int issuedTokenCount() {
return exchange.issuedTokenCount();
}
/**
* The algorithm a key block carries.
*
* <p>The block names the algorithm of the key it carries, and the length of the material
* says which of that family's keys it is. The algorithm is not guessed from the length
* alone, because a TDES key and an AES key of the same length are different keys.
*
* <p>The header's algorithm byte fixes how long the key may be, so a key of a length the
* algorithm does not allow is refused rather than read as a key of another length.
*/
static String algorithmOf(String block, int materialLength) {
String family = PaymentCryptographyTr31.algorithmInHeader(block);
int length = materialLength;
return switch (family) {
case "A" -> switch (length) {
case 16 -> "AES_128";
case 24 -> "AES_192";
case 32 -> "AES_256";
default -> throw new AwsException("ValidationException",
"the key block carries a " + (length * 8) + "-bit key; AES needs 128/192/256", 400);
};
case "T" -> switch (length) {
case 16 -> "TDES_2KEY";
case 24 -> "TDES_3KEY";
default -> throw new AwsException("ValidationException",
"the key block carries a " + (length * 8) + "-bit key; TDES needs 128/192", 400);
};
default -> throw new AwsException("ValidationException",
"the key block's algorithm is '" + family + "', which is not one this service has a key "
+ "algorithm for (T for TDES, A for AES)", 400);
};
}
/**
* The usages a key block may carry, and the modes of use each of them has.
*
@@ -557,6 +762,36 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
Map.entry("V2", "TR31_V2_VISA_PIN_VERIFICATION_KEY"),
Map.entry("S0", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"));
/**
* The usage name of the key an initial derivation key has.
*
* <p>The standard gives an initial derivation key the usage code B1, and the key the
* service derives carries that code in the block it is exported in. The name is the
* service's own marker for such a key: the API has no usage name for it, because a key
* with that usage never lives in the service.
*/
static final String INITIAL_DERIVATION_KEY_USAGE = "TR31_B1_INITIAL_DERIVATION_KEY";
/** The TR-31 usage code of an initial derivation key. */
static final String INITIAL_DERIVATION_KEY_CODE = "B1";
/**
* Whether a key is the one derived from a base derivation key.
*
* <p>It is an initial derivation key, and the standard gives it the usage code B1.
*/
static boolean isInitialDerivationKey(PaymentCryptographyKey key) {
return INITIAL_DERIVATION_KEY_USAGE.equals(key.getKeyUsage());
}
/** The TR-31 usage code of a key, which the initial derivation key has of its own. */
static String usageCode(PaymentCryptographyKey key) {
if (isInitialDerivationKey(key)) {
return INITIAL_DERIVATION_KEY_CODE;
}
return usageCode(key.getKeyUsage());
}
/** The TR-31 usage code of a usage name, such as {@code D0}. */
static String usageCode(String usageName) {
for (Map.Entry<String, String> entry : USAGE_NAMES.entrySet()) {
@@ -620,23 +855,20 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
/**
* The modes of use a mode of use code of a key block stands for.
*
* <p>A key encryption key wraps and unwraps rather than encrypts and decrypts, so the
* same character means the other modes for one.
* <p>The character says what the key may be used for, and both spellings of a direction
* stand for it: a key that may encrypt may also wrap, and a key that may decrypt may also
* unwrap. A block that says {@code B} therefore grants all four of them, whichever use the
* key has, which is what the reference does.
*
* @param mode the mode of use character of the block
* @param isKek true when the block carries a key encryption key
* @return the modes of use the character stands for
*/
static Map<String, Boolean> modesFor(String mode, boolean isKek) {
static Map<String, Boolean> modesFor(String mode) {
return switch (mode) {
case "B" -> isKek
? Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE)
: Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE);
case "E" -> isKek
? Map.of("Wrap", Boolean.TRUE)
: Map.of("Encrypt", Boolean.TRUE);
case "D" -> isKek
? Map.of("Unwrap", Boolean.TRUE)
: Map.of("Decrypt", Boolean.TRUE);
case "B" -> Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE,
"Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE);
case "E" -> Map.of("Encrypt", Boolean.TRUE, "Wrap", Boolean.TRUE);
case "D" -> Map.of("Decrypt", Boolean.TRUE, "Unwrap", Boolean.TRUE);
case "G" -> Map.of("Generate", Boolean.TRUE);
case "V" -> Map.of("Verify", Boolean.TRUE);
case "C" -> Map.of("Generate", Boolean.TRUE, "Verify", Boolean.TRUE);
@@ -648,19 +880,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
}
/**
* The mode of use character a key block carries.
* The mode of use character a set of modes gives.
*
* <p>The character is read off the key's own modes, because that is what it says: a key
* that encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key
* encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are read
* that way.
* <p>The character is read off the modes, because that is what it says: a key that
* encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key
* encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are
* read that way.
*
* @param key the key the block carries
* @param modes the modes of the key
* @param isKek whether the key is a key encryption key, whose modes are wrap and unwrap
* @return the character
*/
static String modeCode(PaymentCryptographyKey key) {
Map<String, Boolean> modes = key.getKeyModesOfUse();
boolean isKek = isKeyEncryptionKey(key.getKeyUsage());
static String modeCode(Map<String, Boolean> modes, boolean isKek) {
boolean encrypt = isKek
? enabled(modes, "Wrap") || enabled(modes, "Encrypt")
: enabled(modes, "Encrypt");
@@ -694,6 +925,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return "N";
}
/**
* The mode of use character a key block carries.
*
* <p>The character is read off the key's own modes, because that is what it says.
*
* @param key the key the block carries
* @return the character
*/
static String modeCode(PaymentCryptographyKey key) {
return modeCode(key.getKeyModesOfUse(), isKeyEncryptionKey(key.getKeyUsage()));
}
/** Whether a mode of use is on. A key with no modes at all has every one of them. */
private static boolean enabled(Map<String, Boolean> modes, String mode) {
return modes == null || Boolean.TRUE.equals(modes.get(mode));
@@ -848,4 +1091,21 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
Optional<PaymentCryptographyKey> storedKey(String region, String keyId) {
return keyStore.get(storageKey(region, keyId));
}
/** The certificate of a public key. */
public Map<String, Object> publicKeyCertificate(PaymentCryptographyKey key) {
return exchange.publicKeyCertificate(key);
}
/** The parameters a counterparty needs to import a key into this service. */
public Map<String, Object> parametersForImport(String materialType, String algorithm,
boolean reuse) {
return exchange.parametersForImport(materialType, algorithm, reuse);
}
/** The parameters a counterparty needs to import a key this service exported. */
public Map<String, Object> parametersForExport(String materialType, String algorithm,
boolean reuse) {
return exchange.parametersForExport(materialType, algorithm, reuse);
}
}
@@ -0,0 +1,593 @@
package io.floci.aws.services.paymentcryptography;
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* The TR-31 key block, the form a key takes when it leaves the service.
*
* <p>A type D block carries a key under a key block protection key: the key is length
* encoded, encrypted under the derived key, and the block carries a MAC over the header and
* the length encoded key. The keys the service makes are AES, so the block is a type D one and
* the protection key is an AES key too.
*
* <p>The length field of the header counts the whole block in characters, and the key is
* length encoded with its length in bits in front of it, so a reader knows how long the key is
* without the confidential data saying.
*/
final class PaymentCryptographyTr31 {
/** The initialization vector block of the type D key derivation. */
private static final String AES_IV_CONST = "80000000000000000000000000000000";
/** The reduction constant of Triple DES. */
private static final String TDEA_RB = "000000000000001B";
/** The length of the header, in characters. */
private static final int HEADER_LENGTH = 16;
/** The length of the MAC of a type D block, in characters. */
private static final int MAC_LENGTH = 32;
private PaymentCryptographyTr31() {
}
/**
* Wraps a key into a TR-31 block under a key block protection key.
*
* @param clearKey the key the block carries
* @param protectionKey the key that protects the block
* @param protectionAes whether the protection key is an AES key, which decides the block
* type: a type D block under an AES key and a type B one under a TDES
* key. The length alone does not say it, because a 16-byte key is
* both an AES-128 key and a two-key TDES one.
* @param algorithm the algorithm byte of the key the block carries: {@code A} for an
* AES key and {@code T} for a TDES one
* @param usage the usage code of the key, such as {@code D0}
* @param mode the mode of use code of the key, such as {@code B}
* @param exportability {@code E} when the key may leave the service again
* @return the block, in upper-case hexadecimal
*/
static String wrap(byte[] clearKey, byte[] protectionKey, boolean protectionAes,
String algorithm, String usage, String mode, String exportability) {
return wrap(clearKey, protectionKey, protectionAes, algorithm, usage, mode, exportability,
"00", List.of());
}
/**
* A key block, with the optional blocks the header carries.
*
* <p>The optional blocks sit between the header and the cipher text, in the clear, and
* they are authenticated with it.
*
* @param version the version of the key the block carries, over two characters
* @param optionalBlocks the optional blocks, each its identifier and its value
*/
static String wrap(byte[] clearKey, byte[] protectionKey, boolean protectionAes,
String algorithm, String usage, String mode, String exportability,
String version, List<String[]> optionalBlocks) {
String type = protectionAes ? "D" : "B";
byte[] lengthEncoded = lengthEncode(clearKey, protectionAes ? 16 : 8);
// The optional blocks are padded so that the header keeps the block alignment the
// standard asks for, and the padding block is one of them.
List<String[]> padded = withPadding(optionalBlocks, protectionAes ? 16 : 8);
String optional = optionalBlocks(padded);
int blockLength = HEADER_LENGTH + optional.length() + lengthEncoded.length * 2
+ macLength(protectionAes);
String header = header16(type, usage, mode, exportability, blockLength, algorithm, version,
padded.size());
byte[][] derived = deriveKeys(protectionKey, protectionAes);
byte[] encryptionKey = derived[0];
byte[] macKey = derived[1];
byte[] mac = computeMac(header + optional, lengthEncoded, macKey, protectionAes);
// The block is encrypted under the derived key, and the MAC is the vector of that
// encryption: the block is authenticated before it is read.
byte[] cipherText = protectionAes
? PaymentCryptographyCrypto.aesCbcEncrypt(encryptionKey, mac, lengthEncoded)
: Ciphers.tdesCbcEncrypt(lengthEncoded, Ciphers.widenTdesKey(encryptionKey), mac);
return header + optional + hexUpper(cipherText) + hexUpper(mac);
}
/**
* The optional blocks of a header, with the padding block that keeps them aligned.
*
* <p>The standard requires the optional blocks to take up a whole number of cipher
* blocks, so a header that carries them and is not aligned gets a padding block whose
* length is the smallest that aligns it. A header whose optional blocks are already
* aligned gets no padding block at all, because one would break the alignment.
*
* @param blocks the optional blocks the caller asked for
* @param blockSize the cipher block size in characters
* @return the blocks, with the padding block appended when one is needed
*/
private static List<String[]> withPadding(List<String[]> blocks, int blockSize) {
int total = 0;
for (String[] block : blocks) {
total += block[0].length() + 2 + block[1].length();
}
if (total % blockSize == 0) {
return blocks;
}
// The padding block spends four characters on its identifier and its length, and
// the rest of the space is what it carries.
int padding = blockSize - ((total + 4) % blockSize);
if (padding == blockSize) {
padding = 0;
}
List<String[]> padded = new ArrayList<>(blocks);
padded.add(new String[] {"PB", "0".repeat(padding)});
return padded;
}
/**
* Opens a TR-31 block under a key block protection key, and gives the key it carries.
*
* @param block the block, in hexadecimal
* @param protectionKey the key that protects the block
* @return the key the block carries
* @throws IllegalArgumentException when the block does not authenticate, or its header says
* something this service does not serve
*/
static byte[] unwrap(String block, byte[] protectionKey) {
if (block == null || block.length() < HEADER_LENGTH + MAC_LENGTH) {
throw new IllegalArgumentException("the key block is too short to be a key block");
}
String header = block.substring(0, HEADER_LENGTH);
String type = header.substring(0, 1);
if (!"D".equals(type) && !"B".equals(type)) {
throw new IllegalArgumentException("the key block is of type " + type
+ ", and this service reads type B and type D blocks");
}
int declared = parseInt(header.substring(1, 5), "the length of the key block");
if (declared != block.length()) {
throw new IllegalArgumentException("the key block says it is " + declared
+ " characters long, and it is " + block.length());
}
boolean aes = "D".equals(type);
int macLength = macLength(aes);
byte[] mac = fromHex(block.substring(block.length() - macLength));
// The optional blocks sit between the header and the cipher text in the clear, and
// they are authenticated with it.
int optionalLength = optionalLength(header, block);
String optional = block.substring(HEADER_LENGTH, HEADER_LENGTH + optionalLength);
byte[] cipherText = fromHex(
block.substring(HEADER_LENGTH + optionalLength, block.length() - macLength));
byte[][] derived = deriveKeys(protectionKey, aes);
byte[] encryptionKey = derived[0];
byte[] macKey = derived[1];
byte[] lengthEncoded = aes
? PaymentCryptographyCrypto.aesCbcDecrypt(encryptionKey, mac, cipherText)
: Ciphers.tdesCbcDecrypt(cipherText, Ciphers.widenTdesKey(encryptionKey), mac);
byte[] recomputed = computeMac(header + optional, lengthEncoded, macKey, aes);
// The MACs are compared as bytes and in constant time: a comparison that stopped at
// the first difference would say how much of the MAC matched.
if (!MessageDigest.isEqual(recomputed, mac)) {
throw new IllegalArgumentException("the key block did not authenticate under the key");
}
int bits = parseInt(hexUpper(Arrays.copyOfRange(lengthEncoded, 0, 2)), "the length of the key", 16);
if (bits % 8 != 0) {
throw new IllegalArgumentException("the key block says its key is " + bits
+ " bits long, which is not a whole number of bytes");
}
if (lengthEncoded.length < 2 + bits / 8) {
throw new IllegalArgumentException("the key block says its key is longer than the block");
}
return Arrays.copyOfRange(lengthEncoded, 2, 2 + bits / 8);
}
/**
* The optional blocks a key block carries, as the characters of the key block.
*
* <p>An optional block is its identifier over two characters, its length over two, and
* then its value. The length covers the whole block in characters, the identifier and the
* length included, and it is written in hexadecimal.
*
* @param blocks the optional blocks, each its identifier and its value
* @return the optional blocks, as the characters of the key block
*/
private static String optionalBlocks(List<String[]> blocks) {
StringBuilder out = new StringBuilder();
for (String[] block : blocks) {
String id = block[0];
String value = block[1];
// The length covers the whole block, the identifier and the length included.
out.append(id).append(two(4 + value.length(), 16)).append(value);
}
return out.toString();
}
/**
* How many characters the block's optional blocks take.
*
* <p>An optional block is its identifier over two characters, its length over two, and
* then its value. The length covers the whole block in characters, the identifier and the
* length included, and it is written in hexadecimal. The header says how many of them
* there are.
*
* @param header the block's header
* @param block the whole block
* @return the length of the optional blocks, in characters
*/
static int optionalLength(String header, String block) {
int count = parseInt(header.substring(12, 14), "the number of optional blocks");
int length = 0;
for (int i = 0; i < count; i++) {
length += optionalBlockLength(block, HEADER_LENGTH + length);
}
return length;
}
/**
* How many characters the optional block at a place takes.
*
* <p>The length field says how long the whole block is, the identifier and the length
* included. A block longer than a length field can hold says so with a zero length, and
* then the number of characters the length itself takes follows, and the length after
* that.
*
* @param block the whole block
* @param at where the optional block starts
* @return the length of the optional block, in characters
*/
private static int optionalBlockLength(String block, int at) {
if (block.length() < at + 4) {
throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ "is too short to hold them");
}
int length = parseInt(block.substring(at + 2, at + 4),
"the length of an optional block", 16);
if (length != 0) {
return length;
}
// The length did not fit in its field, so the field says so and the length follows
// the number of characters it takes.
if (block.length() < at + 8) {
throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ "is too short to hold them");
}
int digits = parseInt(block.substring(at + 4, at + 6),
"the length of the length of an optional block", 16);
if (digits == 0 || block.length() < at + 6 + digits) {
throw new IllegalArgumentException("the key block says it has optional blocks, and it "
+ "is too short to hold them");
}
return parseInt(block.substring(at + 6, at + 6 + digits),
"the length of an optional block", 16);
}
/** The usage code of a block's header, such as {@code D0}. */
static String usageOf(String block) {
return block.substring(5, 7);
}
/**
* Whether a block is a type D one, which is derived with AES.
*
* <p>The type is in the block's own header, so it is read from there and not from the
* wrapping key: a type D block is protected with AES and a type B one with TDES.
*/
static boolean typeOf(String block) {
return "D".equals(block.substring(0, 1));
}
/** The type of a block, {@code D} or {@code B}, for a message that names it. */
static String typeName(String block) {
return block.substring(0, 1);
}
/** The mode of use code of a block's header, such as {@code B}. */
static String modeOf(String block) {
return block.substring(8, 9);
}
/** The exportability of a block's header: {@code E}, {@code N} or {@code S}. */
static String exportabilityOf(String block) {
return block.substring(11, 12);
}
/**
* The 16-character header of a block, whose layout the standard fixes.
*
* @param blockLength the length of the whole block, in characters
*/
private static String header16(String type, String usage, String mode, String exportability,
int blockLength, String algorithm, String version,
int optionalBlocks) {
String header = type
+ pad4(blockLength)
+ usage
+ algorithm // the algorithm of the key the block carries
+ mode
+ version // the version of the key
+ exportability
+ two(optionalBlocks, 10) // the number of optional blocks
+ "00"; // the reserved characters
if (header.length() != HEADER_LENGTH) {
throw new IllegalArgumentException("the key block header must be 16 characters");
}
return header;
}
/** The algorithm the header of a block names for the key it carries. */
static String algorithmInHeader(String block) {
return block.substring(7, 8);
}
/** The length of the MAC of a block of that type, in characters. */
private static int macLength(boolean aes) {
return aes ? 32 : 16;
}
/**
* The two masks of the last block of the MAC: the CMAC subkeys of the MAC key.
*
* <p>A last block that needed no padding is masked with the first subkey and one that was
* padded with the second, which is what the reference implementation does.
*/
private static byte[][] masksOf(byte[] macKey, boolean aes) {
if (aes) {
byte[][] subkeys = PaymentCryptographyCrypto.cmacSubkeys(macKey);
return new byte[][] {subkeys[0], subkeys[1]};
}
byte[] subkeys = cmacSubkeys(macKey, 8, TDEA_RB);
return new byte[][] {Arrays.copyOfRange(subkeys, 0, 8), Arrays.copyOfRange(subkeys, 8, 16)};
}
/**
* The key as a length encoded block: its length in bits in front of it, zero padded to the
* block size.
*/
static byte[] lengthEncode(byte[] clearKey, int blockSize) {
byte[] body = new byte[2 + clearKey.length];
body[0] = (byte) ((clearKey.length * 8) >> 8);
body[1] = (byte) (clearKey.length * 8);
System.arraycopy(clearKey, 0, body, 2, clearKey.length);
int padding = (blockSize - (body.length % blockSize)) % blockSize;
byte[] out = new byte[body.length + padding];
System.arraycopy(body, 0, out, 0, body.length);
return out;
}
/** The block size of AES, in bytes. */
private static final int BLOCK_SIZE = 16;
/**
* The MAC of a block: the CBC-MAC of the header and the length encoded key under the MAC
* key, with the last block masked by a subkey of it.
*
* <p>A last block that needed no padding is masked with the first subkey and one that was
* padded with the second, which is what the reference implementation does.
*/
static byte[] computeMac(String header, byte[] lengthEncoded, byte[] macKey, boolean aes) {
int blockSize = aes ? BLOCK_SIZE : 8;
byte[][] masks = masksOf(macKey, aes);
byte[] data = new byte[header.length() + lengthEncoded.length];
System.arraycopy(header.getBytes(StandardCharsets.US_ASCII), 0, data, 0, header.length());
System.arraycopy(lengthEncoded, 0, data, header.length(), lengthEncoded.length);
byte[] last;
if (data.length % blockSize != 0) {
int padding = blockSize - (data.length % blockSize);
data = Arrays.copyOf(data, data.length + padding);
data[data.length - padding] = (byte) 0x80;
last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[1]);
} else {
last = xor(Arrays.copyOfRange(data, data.length - blockSize, data.length), masks[0]);
}
byte[] macInput = Arrays.copyOf(data, data.length);
System.arraycopy(last, 0, macInput, macInput.length - blockSize, blockSize);
byte[] out = aes
? PaymentCryptographyCrypto.aesCbcEncrypt(macKey, new byte[BLOCK_SIZE], macInput)
: Ciphers.tdesCbcEncrypt(macInput, Ciphers.widenTdesKey(macKey), new byte[8]);
return Arrays.copyOfRange(out, out.length - blockSize, out.length);
}
/**
* The two keys a block is made under: the one that encrypts the key and the one that
* authenticates it.
*
* <p>The derivation follows the family of the protection key, because the block type does
* too: a type D block is derived with AES and a type B one with Triple DES.
*/
static byte[][] deriveKeys(byte[] protectionKey, boolean aes) {
return aes ? deriveAesKeys(protectionKey) : deriveTypeBKeys(protectionKey);
}
/**
* The derived keys of a type D block.
*
* <p>The derivation is the counter mode key derivation of NIST SP800-108, seeded with the
* second CMAC subkey of the protection key and encrypted by the protection key itself. The
* derived key is as long as the protection key: a 192-bit protection key derives a 192-bit
* key, whose second part is truncated to eight bytes, so the cipher that uses the result is
* AES-192 rather than a widened AES-256.
*/
private static byte[][] deriveAesKeys(byte[] protectionKey) {
int bits = protectionKey.length * 8;
if (bits != 128 && bits != 192 && bits != 256) {
throw new IllegalArgumentException("a type D block needs a 128, 192 or 256 bit key block "
+ "protection key, and this one is " + bits + " bits");
}
int derivedBytes = bits / 8;
int firstPart = 16;
int secondPart = derivedBytes - firstPart;
byte[] seed = PaymentCryptographyCrypto.cmacSubkeys(protectionKey)[1];
byte[] encryptionKey = new byte[derivedBytes];
byte[] macKey = new byte[derivedBytes];
System.arraycopy(part(seed, bits, false, 1, protectionKey), 0, encryptionKey, 0, firstPart);
System.arraycopy(part(seed, bits, true, 1, protectionKey), 0, macKey, 0, firstPart);
if (secondPart > 0) {
System.arraycopy(part(seed, bits, false, 2, protectionKey), 0, encryptionKey, firstPart,
secondPart);
System.arraycopy(part(seed, bits, true, 2, protectionKey), 0, macKey, firstPart, secondPart);
}
return new byte[][] {encryptionKey, macKey};
}
/**
* The derived keys of a type B block.
*
* <p>The derivation is the counter mode key derivation of NIST SP800-108, seeded with the
* first CMAC subkey of the protection key, and the reduction constant of Triple DES is the
* whole buffer rather than the top bit alone.
*/
private static byte[][] deriveTypeBKeys(byte[] protectionKey) {
int bits = protectionKey.length * 8;
if (bits != 128 && bits != 192) {
throw new IllegalArgumentException("a type B block needs a 128 or 192 bit key block "
+ "protection key, and this one is " + bits + " bits");
}
byte[] wide = Ciphers.widenTdesKey(protectionKey);
int parts = bits == 192 ? 3 : 2;
byte[] seed = Arrays.copyOfRange(cmacSubkeys(wide, 8, TDEA_RB), 0, 8);
byte[] encryptionKey = new byte[parts * 8];
byte[] macKey = new byte[parts * 8];
for (int counter = 1; counter <= parts; counter++) {
byte[] input = xor(seed, fromHex(typeBConstant(bits, false, counter)));
byte[] part = Ciphers.tdes3Encrypt(input, wide);
System.arraycopy(part, 0, encryptionKey, (counter - 1) * 8, 8);
input = xor(seed, fromHex(typeBConstant(bits, true, counter)));
part = Ciphers.tdes3Encrypt(input, wide);
System.arraycopy(part, 0, macKey, (counter - 1) * 8, 8);
}
return new byte[][] {encryptionKey, macKey};
}
/** The constant of the type B key derivation. */
private static String typeBConstant(int bits, boolean mac, int counter) {
String algorithm = bits == 192 ? "0001" : "0000";
String use = mac ? "0001" : "0000";
String keyLength = bits == 192 ? "00C0" : "0080";
return (counter < 10 ? "0" + counter : Integer.toString(counter))
+ use + "00" + algorithm + keyLength;
}
/**
* The CMAC subkeys of a TDES key.
*
* <p>The reduction constant of Triple DES is the whole buffer, which is what the reference
* implementation does, and it is not the top bit alone.
*/
private static byte[] cmacSubkeys(byte[] key, int blockSize, String rbHex) {
byte[] s = Ciphers.tdes3Encrypt(new byte[blockSize], key);
byte[] rb = fromHex(rbHex);
byte[] k1 = shiftXor(s, rb);
byte[] k2 = shiftXor(k1, rb);
byte[] out = new byte[k1.length + k2.length];
System.arraycopy(k1, 0, out, 0, k1.length);
System.arraycopy(k2, 0, out, k1.length, k2.length);
return out;
}
/** A left shift by one bit, then the reduction constant when the top bit was set. */
private static byte[] shiftXor(byte[] value, byte[] rb) {
byte[] out = new byte[value.length];
int carry = 0;
for (int i = value.length - 1; i >= 0; i--) {
int nextCarry = (value[i] & 0x80) != 0 ? 1 : 0;
out[i] = (byte) (((value[i] << 1) | carry) & 0xff);
carry = nextCarry;
}
if ((value[0] & 0x80) != 0) {
for (int i = 0; i < out.length; i++) {
out[i] ^= rb[i % rb.length];
}
}
return out;
}
/** One part of the derivation: the protection key encrypts the seeded constant. */
private static byte[] part(byte[] seed, int bits, boolean mac, int counter, byte[] protectionKey) {
byte[] constant = fromHex(derivationConstant(bits, mac, counter));
byte[] input = xor(seed, constant);
return PaymentCryptographyCrypto.aesEcbEncrypt(input, protectionKey);
}
/** The constant of the key derivation, which says what is derived and how long it is. */
private static String derivationConstant(int bits, boolean mac, int counter) {
String algorithm = bits == 128 ? "0002" : bits == 192 ? "0003" : "0004";
String use = mac ? "0001" : "0000";
String keyLength = bits == 128 ? "0080" : bits == 192 ? "00C0" : "0100";
return (counter < 10 ? "0" + counter : Integer.toString(counter))
+ use + "00" + algorithm + keyLength + AES_IV_CONST;
}
/** Two byte arrays, one after the other. */
private static byte[] xor(byte[] left, byte[] right) {
byte[] out = new byte[left.length];
for (int i = 0; i < left.length; i++) {
out[i] = (byte) (left[i] ^ right[i % right.length]);
}
return out;
}
/** The length of the block, in four decimal characters. */
private static String pad4(int value) {
String text = Integer.toString(value);
if (text.length() > 4) {
throw new IllegalArgumentException("the key block is too long: " + value);
}
return "0000".substring(0, 4 - text.length()) + text;
}
/**
* A number of two characters, in the radix the field it goes into is written in.
*
* <p>The header's count of the optional blocks is written in ten, and the length of an
* optional block in sixteen, as the standard has it.
*
* @param value the number
* @param radix the radix the field is written in
* @return the number, in two characters
*/
private static String two(int value, int radix) {
String text = Integer.toString(value, radix).toUpperCase(Locale.ROOT);
if (text.length() > 2) {
throw new IllegalArgumentException("the number does not fit in two characters: " + value);
}
return "00".substring(0, 2 - text.length()) + text;
}
private static int parseInt(String text, String what) {
return parseInt(text, what, 10);
}
/**
* A number of the text.
*
* <p>The length of the block is written in decimal and the length of the key in the
* length encoded block is written in hexadecimal, so the base is a parameter.
*/
private static int parseInt(String text, String what, int radix) {
try {
return Integer.parseInt(text, radix);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(what + " is not a number: " + text);
}
}
private static String hexUpper(byte[] bytes) {
return PaymentCryptographyCrypto.toHex(bytes).toUpperCase(Locale.ROOT);
}
private static byte[] fromHex(String hex) {
try {
return PaymentCryptographyCrypto.fromHex(hex);
} catch (RuntimeException e) {
throw new IllegalArgumentException("the key block is not hexadecimal");
}
}
}
@@ -0,0 +1,134 @@
package io.floci.aws.services.paymentcryptography.crypto;
import io.floci.aws.core.common.CertificateMaterialException;
import io.floci.aws.core.common.Pem;
import org.bouncycastle.asn1.pkcs.IssuerAndSerialNumber;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.util.io.pem.PemObject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
/**
* The certificates the key exchange hands out and reads.
*
* <p>The service gives a counterparty a certificate over a key pair it made for the occasion,
* and reads the certificate a counterparty brings. A certificate travels in three shapes: PEM,
* base64 of PEM (which is how the service returns one), and base64 of DER.
*
* <p>Reading a certificate is the emulator's own business, through {@link Pem}; minting one
* belongs to ACM's generator, which the service asks for a certificate with.
*/
public final class Certificates {
private Certificates() {
}
/** A minted certificate, in the two forms the service uses it in. */
public record Minted(byte[] der, String pem) {
}
/**
* Parse a certificate the service hands over, or one a counterparty brings.
*
* <p>PEM, base64 of PEM and base64 of DER are all accepted: the service returns a
* certificate as base64 of its PEM, and a client certificate arrives the same way.
*
* @param pemOrBase64 the certificate, in any of those shapes
* @return the parsed certificate
* @throws IllegalArgumentException if the text is not a certificate in any of them
*/
public static X509Certificate parseCertificate(String pemOrBase64) {
String text = pemOrBase64 == null ? "" : pemOrBase64.trim();
if (text.contains("-----BEGIN")) {
return readPem(text);
}
byte[] decoded;
try {
decoded = Base64.getMimeDecoder().decode(text);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("the certificate is neither PEM nor base64");
}
String decodedText = new String(decoded, StandardCharsets.UTF_8);
// base64 of a PEM, which is how the service returns one, or base64 of the DER itself.
if (decodedText.contains("-----BEGIN")) {
return readPem(decodedText);
}
return readDer(decoded);
}
/** The certificate a DER document holds. */
private static X509Certificate readDer(byte[] der) {
try {
return (X509Certificate) CertificateFactory.getInstance("X.509")
.generateCertificate(new ByteArrayInputStream(der));
} catch (CertificateException e) {
throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage());
}
}
/** The certificate a PEM document holds, read by the emulator's own PEM reader. */
private static X509Certificate readPem(String pem) {
try {
return Pem.parseCertificate(pem);
} catch (CertificateMaterialException e) {
throw new IllegalArgumentException("the certificate does not parse: " + e.getMessage());
}
}
/**
* The identifier a TR-34 block uses to name its recipient.
*
* <p>A RecipientInfo carries the receiver's certificate identifier: an
* IssuerAndSerialNumber, which is the issuer's name and the certificate's serial number.
* Both are taken from the certificate itself, so the identifier is the one the receiver's
* own certificate carries.
*
* @param certDer the certificate in DER
* @return the issuer and serial number, as the DER of an IssuerAndSerialNumber
*/
public static byte[] certificateId(byte[] certDer) {
X509Certificate certificate = readDer(certDer);
try {
return new IssuerAndSerialNumber(
new X500Name(certificate.getIssuerX500Principal().getName()),
certificate.getSerialNumber()).getEncoded();
} catch (IOException e) {
throw new IllegalStateException("cannot encode the certificate identifier", e);
}
}
/**
* Wrap DER as a PEM document.
*
* @param der the certificate in DER
* @return the certificate in PEM
*/
public static String toPem(byte[] der) {
StringWriter writer = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) {
pemWriter.writeObject(new PemObject("CERTIFICATE", der));
} catch (IOException e) {
throw new IllegalStateException("cannot write the certificate as PEM", e);
}
return writer.toString();
}
/**
* A PEM certificate as base64, which is how the service returns one.
*
* @param pem the certificate in PEM
* @return the base64 of the PEM
*/
public static String pemBase64(String pem) {
return Base64.getEncoder().encodeToString(pem.getBytes(StandardCharsets.US_ASCII));
}
}
@@ -84,6 +84,34 @@ public final class Ciphers {
return block(AESEngine.newInstance(), false, block16, key);
}
/**
* Widen a two-key (sixteen-byte) Triple DES key to the three-key form, K1||K2 to
* K1||K2||K1.
*
* <p>The cipher takes the three keys K1||K2||K1, which is what the two-key form means,
* and TR-31 derives a type B block's keys from the widened form, so the derivation and
* the cipher have to be on the same key. A three-key key is returned as it is.
*
* @param key the sixteen- or twenty-four-byte key
* @return the twenty-four-byte key
*/
public static byte[] widenTdesKey(byte[] key) {
if (key == null) {
throw new IllegalArgumentException("key is required");
}
if (key.length == 24) {
return key;
}
if (key.length != 16) {
throw new IllegalArgumentException(
"TDES key must be 16 or 24 bytes, got " + key.length);
}
byte[] out = new byte[24];
System.arraycopy(key, 0, out, 0, 16);
System.arraycopy(key, 0, out, 16, 8);
return out;
}
/**
* The Triple DES encryption of a block under a two-key key, in ECB mode.
*
@@ -0,0 +1,112 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import java.util.Arrays;
/**
* The NIST SP 800-56A concatenation KDF, as the service applies it.
*
* <p>It is the single-step KDF of SP 800-56A with the counter, the shared
* secret and the shared information concatenated in that order:
*
* <pre>
* K = H(counter || Z || OtherInfo) for counter = 1, 2, ... truncated to length
* </pre>
*
* <p>The other information is what binds the derived key to the two parties and
* to the context, so the same shared secret derived under different shared
* information gives a different key.
*/
public final class ConcatKdf {
private ConcatKdf() {
}
/**
* Derive key material from a shared secret.
*
* @param hash the digest algorithm: {@code SHA-256}, {@code SHA-384} or
* {@code SHA-512}
* @param secret the shared secret
* @param otherInfo the shared information
* @param length how many bytes to derive
* @return the derived key
*/
public static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length) {
return derive(hash, secret, otherInfo, length, true);
}
/**
* The ANSI X9.63 key derivation.
*
* <p>The same construction as the SP 800-108 concatenation KDF, but with
* the shared secret and the counter the other way round:
*
* <pre>
* K = H(Z || counter || OtherInfo)
* </pre>
*
* <p>So the two derivations over the same secret give different keys, and
* a caller has to say which one it means.
*/
public static byte[] deriveX963(String hash, byte[] secret, byte[] otherInfo, int length) {
return derive(hash, secret, otherInfo, length, false);
}
private static byte[] derive(String hash, byte[] secret, byte[] otherInfo, int length,
boolean counterFirst) {
if (length <= 0) {
throw new IllegalArgumentException("the derived length must be positive");
}
Digest digest = digestFor(hash);
int hashBytes = digest.getDigestSize();
int reps = (length + hashBytes - 1) / hashBytes;
byte[] out = new byte[reps * hashBytes];
byte[] block = new byte[hashBytes];
for (int i = 1; i <= reps; i++) {
digest.reset();
if (counterFirst) {
digest.update(counter(i), 0, 4);
digest.update(secret, 0, secret.length);
} else {
digest.update(secret, 0, secret.length);
digest.update(counter(i), 0, 4);
}
digest.update(otherInfo, 0, otherInfo.length);
digest.doFinal(block, 0);
System.arraycopy(block, 0, out, (i - 1) * hashBytes, hashBytes);
}
return Arrays.copyOf(out, length);
}
/** The four-byte big-endian counter, starting at one. */
private static byte[] counter(int n) {
return new byte[] {
(byte) (n >>> 24), (byte) (n >>> 16), (byte) (n >>> 8), (byte) n,
};
}
/**
* The digest for a wire hash name.
*
* <p>The service names the digests with an underscore, and the library
* knows them as the SHA-2 family.
*/
private static Digest digestFor(String hash) {
if ("SHA_256".equals(hash)) {
return new SHA256Digest();
}
if ("SHA_384".equals(hash)) {
return new SHA384Digest();
}
if ("SHA_512".equals(hash)) {
return new SHA512Digest();
}
throw new IllegalArgumentException("unsupported digest '" + hash
+ "' (SHA_256, SHA_384, SHA_512)");
}
}
@@ -0,0 +1,62 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.crypto.agreement.ECDHBasicAgreement;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
/**
* The elliptic curve key agreement the key exchange derives its shared secret with.
*
* <p>The keys are the ones the service holds, which are the JDK's key objects. They are
* turned into the library's own parameters through their encodings, which carry the curve
* by name, so the two parties' keys are read on the same curve rather than on two curves
* that happen to look alike.
*/
public final class Ecdh {
private Ecdh() {
}
/**
* The secret the two parties agree.
*
* @param privateKey the service's own private key
* @param counterpartyKey the other party's public key
* @return the shared secret, the x coordinate of the agreed point
* @throws GeneralSecurityException when the two keys are not on the same curve
*/
public static byte[] agree(ECPrivateKey privateKey, ECPublicKey counterpartyKey)
throws GeneralSecurityException {
try {
ECPrivateKeyParameters own = (ECPrivateKeyParameters) PrivateKeyFactory
.createKey(PrivateKeyInfo.getInstance(privateKey.getEncoded()));
ECPublicKeyParameters other = (ECPublicKeyParameters) PublicKeyFactory
.createKey(SubjectPublicKeyInfo.getInstance(counterpartyKey.getEncoded()));
ECDHBasicAgreement agreement = new ECDHBasicAgreement();
agreement.init(own);
// The agreed point's x coordinate, in as many bytes as the field is wide.
BigInteger x = agreement.calculateAgreement(other);
int size = agreement.getFieldSize();
byte[] raw = x.toByteArray();
byte[] secret = new byte[size];
int from = Math.max(0, raw.length - size);
System.arraycopy(raw, from, secret, size - (raw.length - from), raw.length - from);
return secret;
} catch (IOException | ClassCastException | IllegalArgumentException
| IllegalStateException e) {
// The library raises IllegalStateException when the two keys are on different
// curves, which is a refusal and not a crash.
throw new GeneralSecurityException("the key agreement failed: " + e.getMessage(), e);
}
}
}
@@ -19,8 +19,8 @@ import java.util.HexFormat;
* it was sent, and the padding the service applies is the one it applies to the input it
* builds itself, which is the issuer authentication cryptogram.
*
* <p>All DES is done through three-key TDES rather than a single-DES provider:
* single DES is expressed as TDES with K||K||K.
* <p>Each cipher says which one it uses: the retail MAC is single DES, and the
* key derivations are two-key TDES, which the cipher takes as K1||K2||K1.
*
* <p>The full PAN flows into master key derivation, because the derivation is
* defined over the whole of it.
@@ -94,11 +94,12 @@ public final class EmvCrypto {
}
/**
* ISO/IEC 9797-1 MAC algorithm 3 (the retail MAC) with a 16-byte key.
* The retail MAC over data padded with the given ISO 9797-1 method.
*
* <p>This is single-DES chaining, not three-key TDES. The key splits into
* K1 (left 8) and K2 (right 8); each block is enciphered under K1, and a
* single D_KR then E_KL final transform closes the tag:
* <p>This is ISO/IEC 9797-1 MAC algorithm 3 with a 16-byte key, and it is
* single-DES chaining, not three-key TDES. The key splits into K1 (left 8)
* and K2 (right 8); each block is enciphered under K1, and a single D_KR
* then E_KL final transform closes the tag:
*
* <pre>
* H_i = E_KL(D_i XOR H_{i-1}) for i = 1..n
@@ -108,7 +109,6 @@ public final class EmvCrypto {
* <p>Running a 3DES transform per block instead - the obvious reading -
* produces a different MAC.
*/
/** The retail MAC over data padded with the given ISO 9797-1 method. */
public static byte[] retailMac(byte[] key16, byte[] data, Padding padding) {
byte[] kl = slice(key16, 0, 8);
byte[] kr = slice(key16, 8, 16);
@@ -0,0 +1,114 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.encodings.OAEPEncoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
/**
* RSA-OAEP, with the parameters built explicitly.
*
* <p><strong>MGF1 follows the OAEP digest.</strong> The parameters are still
* built by hand rather than by asking for {@code OAEPWithSHA-256AndMGF1Padding},
* for two reasons. There is no {@code OAEPWithSHA-512AndMGF1Padding} constant,
* so the SHA-512 wrapping specification has to be constructed - and a spec
* built by copying a SHA-1 example leaves MGF1 on SHA-1 and fails with an
* opaque OAEP decoding error on a hex string that looks perfectly valid. And
* every OAEP operation in this project routes through here, so the two digests
* cannot drift apart again.
*/
public final class RsaOaep {
private RsaOaep() {
}
/** The OAEP digest for a wrapping specification, or null when unsupported. */
public static String digestFor(String wrappingSpec) {
if ("RSA_OAEP_SHA_256".equals(wrappingSpec) || wrappingSpec == null) {
return "SHA-256";
}
if ("RSA_OAEP_SHA_512".equals(wrappingSpec)) {
return "SHA-512";
}
return null;
}
/** Decrypt an OAEP-wrapped block. */
public static byte[] decrypt(PrivateKey key, byte[] ciphertext, String digest) {
return run(false, key, null, ciphertext, digest);
}
/** Encrypt to an OAEP-wrapped block. Used by tests and by the demo. */
public static byte[] encrypt(PublicKey key, byte[] plaintext, String digest) {
return run(true, null, key, plaintext, digest);
}
/**
* The OAEP encoding, with the requested digest for the OAEP digest and for MGF1.
*
* <p>The label is empty, which is what the reference implementation's
* {@code PSource.PSpecified.DEFAULT} means.
*/
private static OAEPEncoding encoding(String digest, boolean encrypt) {
// The private operation is the blinded one: it decrypts what a caller brought, so its
// timing must not say how far the exponentiation has come. The public operation
// exponentiates with a public exponent, and blinding that protects nothing.
AsymmetricBlockCipher engine = encrypt ? new RSAEngine() : new RSABlindedEngine();
Digest hash = "SHA-512".equals(digest) ? new SHA512Digest() : new SHA256Digest();
return new OAEPEncoding(engine, hash, hash, null);
}
private static byte[] run(boolean encrypt, PrivateKey priv, PublicKey pub,
byte[] input, String digest) {
try {
OAEPEncoding oaep = encoding(digest, encrypt);
if (encrypt) {
RSAPublicKey rsa = (RSAPublicKey) pub;
oaep.init(true, new RSAKeyParameters(false, rsa.getModulus(), rsa.getPublicExponent()));
} else {
oaep.init(false, privateParameters((RSAPrivateKey) priv));
}
return oaep.processBlock(input, 0, input.length);
} catch (InvalidCipherTextException e) {
throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e);
} catch (RuntimeException e) {
throw new IllegalArgumentException("RSA-OAEP failed: " + e.getMessage(), e);
}
}
/**
* The private key's parameters, with the CRT values when the key carries them.
*
* <p>The blinded engine blinds the exponentiation it is given, and it does so with the
* CRT values, so a key that has them is passed as they are.
*
* @param key the private key
* @return the parameters the engine works with
*/
private static RSAKeyParameters privateParameters(RSAPrivateKey key) {
if (key instanceof RSAPrivateCrtKey crt) {
return new RSAPrivateCrtKeyParameters(crt.getModulus(), crt.getPublicExponent(),
crt.getPrivateExponent(), crt.getPrimeP(), crt.getPrimeQ(),
crt.getPrimeExponentP(), crt.getPrimeExponentQ(), crt.getCrtCoefficient());
}
return new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());
}
/** Decrypt with a key given as the generic {@link Key} type. */
public static byte[] decrypt(Key key, byte[] ciphertext, String digest) {
return decrypt((PrivateKey) key, ciphertext, digest);
}
}