mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(paymentcryptography): the PIN operations (#7397)
This commit is contained in:
1 parent
d0b50384fc
commit
6130fe9568
27 files changed
+3427
-191
No files matched your search
@@ -68,6 +68,7 @@ import io.floci.aws.services.oam.OamController;
|
||||
import io.floci.aws.services.opensearch.ElasticsearchController;
|
||||
import io.floci.aws.services.opensearch.OpenSearchController;
|
||||
import io.floci.aws.services.paymentcryptography.PaymentCryptographyCryptoController;
|
||||
import io.floci.aws.services.paymentcryptography.PaymentCryptographyPinController;
|
||||
import io.floci.aws.services.pipes.PipesController;
|
||||
import io.floci.aws.services.quicksight.QuickSightController;
|
||||
import io.floci.aws.services.quicksight.QuickSightEmbedController;
|
||||
@@ -322,7 +323,8 @@ public class ResolvedServiceCatalog {
|
||||
// signs for the service, which is one scope for both of its planes; the
|
||||
// scope its own plane is named by is an alias of that one.
|
||||
Set.of(), Set.of("payment-cryptography", "payment-cryptography-data"), Set.of(),
|
||||
Set.of(PaymentCryptographyCryptoController.class)),
|
||||
Set.of(PaymentCryptographyCryptoController.class,
|
||||
PaymentCryptographyPinController.class)),
|
||||
descriptor("secretsmanager", "secretsmanager", config.services().secretsmanager().enabled(), true,
|
||||
"secretsmanager", storageMode(config.storage().services().secretsmanager().mode(), config.storage().mode()),
|
||||
config.storage().services().secretsmanager().flushIntervalMs(), null, ServiceProtocol.JSON,
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* How the attributes of a data plane request are read.
|
||||
*
|
||||
* <p>The data plane's requests name what they want in an attributes member, and the
|
||||
* attributes member holds one variant: the algorithms a MAC may use, the formats a PIN
|
||||
* block may be in, and the key a DUKPT derivation is made from. Reading them is the same
|
||||
* whatever the operation is, so it is read in one place.
|
||||
*/
|
||||
final class PaymentCryptographyAttributes {
|
||||
|
||||
private PaymentCryptographyAttributes() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The text of a member, or the empty string when the member is not there.
|
||||
*
|
||||
* @param request the request or the attributes to read
|
||||
* @param member the member to read
|
||||
* @return the member's text
|
||||
*/
|
||||
static String text(JsonNode request, String member) {
|
||||
if (request == null) {
|
||||
return "";
|
||||
}
|
||||
JsonNode declared = request.get(member);
|
||||
return declared == null || declared.isNull() ? "" : declared.asText("");
|
||||
}
|
||||
|
||||
/**
|
||||
* The one variant an attributes member holds.
|
||||
*
|
||||
* <p>An attributes member holds exactly one variant, so a member with none or with two
|
||||
* is a request that cannot be read.
|
||||
*
|
||||
* @param attributes the attributes to read
|
||||
* @return the variant's name, or null when there is not exactly one
|
||||
*/
|
||||
static String soleVariant(JsonNode attributes) {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return null;
|
||||
}
|
||||
String found = null;
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
|
||||
while (fields.hasNext()) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = fields.next().getKey();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
}
|
||||
+11
-158
@@ -10,11 +10,21 @@ import jakarta.inject.Inject;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.material;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.materialHex;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireEnabled;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireFamily;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireMode;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireUsage;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyService.isAes;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyService.isTdes;
|
||||
|
||||
/**
|
||||
* The data plane's encryption and its MACs: the operations that use a key to protect data.
|
||||
*
|
||||
@@ -291,48 +301,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
return iv;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key is an AES key.
|
||||
*
|
||||
* <p>The key record knows its algorithm, so the family is read from there and not guessed
|
||||
* from the length of the material: a sixteen-byte key is a two-key Triple DES one and an
|
||||
* AES-128 one.
|
||||
*/
|
||||
private static boolean isAes(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyService.isAes(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the key is a Triple DES one.
|
||||
*
|
||||
* <p>The reference ciphers with AES and with Triple DES, and the block and the vector follow
|
||||
* the key's family: sixteen bytes and a sixteen-byte vector for AES, eight for Triple DES.
|
||||
*
|
||||
* @param key the key the cipher runs under
|
||||
* @return whether the key is a Triple DES one
|
||||
*/
|
||||
private static boolean isTdes(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyService.isTdes(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm has to be for an operation.
|
||||
*
|
||||
* <p>The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
|
||||
* the CMAC over AES, so a key of the other family would be read as bytes it is not.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param aes whether the operation needs an AES key
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
private static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
|
||||
if (isAes(key) != aes) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
|
||||
+ what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm belongs to.
|
||||
*
|
||||
@@ -402,56 +370,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
return key;
|
||||
}
|
||||
|
||||
/**
|
||||
* A key that is disabled does no work.
|
||||
*
|
||||
* <p>The service reads a disabled key and tells the caller about it, but it does not
|
||||
* encrypt with it, decrypt with it, or make a MAC under it.
|
||||
*
|
||||
* @param key the key the request names
|
||||
*/
|
||||
private static void requireEnabled(PaymentCryptographyKey key) {
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is disabled", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material
|
||||
*/
|
||||
private static byte[] material(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyCrypto.fromHex(materialHex(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key, as it is held.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material, as hexadecimal
|
||||
*/
|
||||
private static String materialHex(PaymentCryptographyKey key) {
|
||||
String hex = key.getKeyMaterialHex();
|
||||
if (hex == null || hex.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the material of the key " + key.getArn() + " is not held: it is kept while the "
|
||||
+ "emulator runs and is not written to the store, so a key read back after "
|
||||
+ "a restart has none", 400);
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
/**
|
||||
* The block the key's cipher works in: sixteen bytes for AES and eight for Triple DES, as
|
||||
* the reference says.
|
||||
@@ -484,46 +402,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The usage a key has to have for an operation.
|
||||
*
|
||||
* <p>The usage is what binds a key to its purpose, so an operation that belongs to one
|
||||
* purpose is not served with a key of another: a PIN encryption key does not encrypt
|
||||
* arbitrary data, and a MAC key does not either. The check is on the usage itself, not
|
||||
* on the mode, because a key may carry the mode and still be of another purpose.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param usages the usages the operation serves
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
private static void requireUsage(PaymentCryptographyKey key, List<String> usages, String what) {
|
||||
String usage = key.getKeyUsage();
|
||||
if (usage == null || usages.contains(usage)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
|
||||
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
|
||||
}
|
||||
|
||||
/** The modes of use a key has to have for an operation. */
|
||||
private static void requireMode(PaymentCryptographyKey key, String mode, String what) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
if (modes == null) {
|
||||
return;
|
||||
}
|
||||
// A NoRestrictions that is false is not a permission: a request that names the
|
||||
// member says nothing about what it allows, so the mode itself decides.
|
||||
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(modes.get(mode))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " does not have the mode of use " + mode
|
||||
+ ", which it needs to " + what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The MAC a request asks for, and the key it is computed under.
|
||||
*
|
||||
@@ -625,31 +503,6 @@ public class PaymentCryptographyCryptoHandler {
|
||||
byte[] apply(byte[] key, byte[] message);
|
||||
}
|
||||
|
||||
/** The one variant of an attributes structure, or null when there is not exactly one. */
|
||||
private static String soleVariant(JsonNode attributes) {
|
||||
if (attributes == null || !attributes.isObject()) {
|
||||
return null;
|
||||
}
|
||||
String found = null;
|
||||
Iterator<Map.Entry<String, JsonNode>> fields = attributes.fields();
|
||||
while (fields.hasNext()) {
|
||||
if (found != null) {
|
||||
return null;
|
||||
}
|
||||
found = fields.next().getKey();
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** The text of a member. */
|
||||
private static String text(JsonNode request, String member) {
|
||||
if (request == null) {
|
||||
return "";
|
||||
}
|
||||
JsonNode declared = request.get(member);
|
||||
return declared == null || declared.isNull() ? "" : declared.asText("");
|
||||
}
|
||||
|
||||
/**
|
||||
* A blob of the request.
|
||||
*
|
||||
|
||||
+2
-2
@@ -28,8 +28,8 @@ import java.util.Map;
|
||||
* besides it, and then the two must agree, so a request cannot act on a key other than the
|
||||
* one its path names.
|
||||
*
|
||||
* <p>{@code /mac}, {@code /pindata}, {@code /cardvalidationdata} and {@code /cryptogram} are
|
||||
* two-segment paths, which S3's path-style routes would claim, so
|
||||
* <p>{@code /mac}, {@code /macemvpinchange}, {@code /pindata}, {@code /cardvalidationdata} and
|
||||
* {@code /cryptogram} are two-segment paths, which S3's path-style routes would claim, so
|
||||
* {@link PaymentCryptographyDataPlaneRouteFilter} moves them for the requests signed for this
|
||||
* service.
|
||||
*
|
||||
|
||||
+33
-5
@@ -9,6 +9,7 @@ import jakarta.ws.rs.container.PreMatching;
|
||||
import jakarta.ws.rs.ext.Provider;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Rewrites the data plane's two-segment paths to an internal prefix before JAX-RS route
|
||||
@@ -23,6 +24,24 @@ public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequest
|
||||
|
||||
static final String INTERNAL_PREFIX = "/_paymentcryptography";
|
||||
|
||||
/**
|
||||
* The path prefixes the data plane's routes sit under.
|
||||
*
|
||||
* <p>The routes are the ones the model names, and every one of them starts with one of
|
||||
* these. A route whose prefix is not here is not rewritten, so it never reaches its
|
||||
* controller, and the request is answered by whichever controller claims it instead.
|
||||
* The test reads the generated routes and holds this list to them.
|
||||
*/
|
||||
static final Set<String> CONTESTED_PATHS = Set.of(
|
||||
"/keys",
|
||||
"/mac",
|
||||
"/macemvpinchange",
|
||||
"/pindata",
|
||||
"/cardvalidationdata",
|
||||
"/cryptogram",
|
||||
"/keymaterial",
|
||||
"/as2805kekvalidation");
|
||||
|
||||
private final SignedServiceRoute route;
|
||||
|
||||
@Inject
|
||||
@@ -33,15 +52,24 @@ public class PaymentCryptographyDataPlaneRouteFilter implements ContainerRequest
|
||||
// is served as well, so that either scope reaches the data plane.
|
||||
this.route = new SignedServiceRoute(catalog,
|
||||
Set.of("paymentcryptography", "payment-cryptography-data"), INTERNAL_PREFIX,
|
||||
SignedServiceRoute.under("/mac")
|
||||
.or(SignedServiceRoute.under("/pindata"))
|
||||
.or(SignedServiceRoute.under("/cardvalidationdata"))
|
||||
.or(SignedServiceRoute.under("/cryptogram"))
|
||||
.or(SignedServiceRoute.under("/keys")));
|
||||
under(CONTESTED_PATHS));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void filter(ContainerRequestContext ctx) {
|
||||
route.apply(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* The predicate that says a path is one of the service's contested routes.
|
||||
*
|
||||
* @param roots the path prefixes the routes sit under
|
||||
* @return the predicate
|
||||
*/
|
||||
private static Predicate<String> under(Set<String> roots) {
|
||||
return roots.stream()
|
||||
.map(SignedServiceRoute::under)
|
||||
.reduce(Predicate::or)
|
||||
.orElseThrow(() -> new IllegalStateException("the data plane has no routes"));
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The rules a key has to satisfy before an operation runs under it.
|
||||
*
|
||||
* <p>The data plane has more than one kind of operation, and they all ask the same questions
|
||||
* of the key they run under: is it enabled, does it allow the mode of use the operation
|
||||
* needs, is it of the usage the operation is for, is it of the cipher family the algorithm
|
||||
* is defined over, and does it hold its material. The answers are the same whatever the
|
||||
* operation is, so they are asked in one place.
|
||||
*
|
||||
* <p>A key that does not satisfy a rule is refused with the error that names it, so a caller
|
||||
* is told which of the key's attributes is wrong rather than that the request failed. The
|
||||
* refusal is a {@code ValidationException}, which is the error the data plane's model
|
||||
* states for a request that is well made but that the service will not serve.
|
||||
*/
|
||||
final class PaymentCryptographyKeyRules {
|
||||
|
||||
private PaymentCryptographyKeyRules() {
|
||||
}
|
||||
|
||||
/**
|
||||
* A key that is disabled does no work.
|
||||
*
|
||||
* <p>The service reads a disabled key and tells the caller about it, but it does not
|
||||
* encrypt with it, decrypt with it, or make a MAC under it.
|
||||
*
|
||||
* @param key the key the request names
|
||||
*/
|
||||
static void requireEnabled(PaymentCryptographyKey key) {
|
||||
if (!key.isEnabled()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is disabled", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode of use a key has to have for an operation.
|
||||
*
|
||||
* <p>The mode is what the key allows: a key that may only decrypt may not encrypt, and a
|
||||
* key with no restrictions may do both.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param mode the mode of use the operation needs
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
static void requireMode(PaymentCryptographyKey key, String mode, String what) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
if (modes == null) {
|
||||
return;
|
||||
}
|
||||
// A NoRestrictions that is false is not a permission: a request that names the
|
||||
// member says nothing about what it allows, so the mode itself decides.
|
||||
if (Boolean.TRUE.equals(modes.get("NoRestrictions"))) {
|
||||
return;
|
||||
}
|
||||
if (!Boolean.TRUE.equals(modes.get(mode))) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " does not have the mode of use " + mode
|
||||
+ ", which it needs to " + what, 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The usage a key has to have for an operation.
|
||||
*
|
||||
* <p>The usage is what binds a key to its purpose, so an operation that belongs to one
|
||||
* purpose is not served with a key of another: a PIN encryption key does not encrypt
|
||||
* arbitrary data, and a MAC key does not either. The check is on the usage itself, not
|
||||
* on the mode, because a key may carry the mode and still be of another purpose.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param usages the usages the operation serves
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
static void requireUsage(PaymentCryptographyKey key, List<String> usages, String what) {
|
||||
String usage = key.getKeyUsage();
|
||||
if (usage == null || usages.contains(usage)) {
|
||||
return;
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is of the usage " + usage + ", and it may not be used to "
|
||||
+ what + ", which needs a key of the usage " + String.join(" or ", usages), 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* The family a key's algorithm has to be for an operation.
|
||||
*
|
||||
* <p>The algorithm runs under the key: the ISO 9797 MACs are defined over Triple DES and
|
||||
* the CMAC over AES, so a key of the other family would be read as bytes it is not.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @param aes whether the operation needs an AES key
|
||||
* @param what the operation, for the message
|
||||
*/
|
||||
static void requireFamily(PaymentCryptographyKey key, boolean aes, String what) {
|
||||
if (PaymentCryptographyService.isAes(key) != aes) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the key " + key.getArn() + " is a " + key.getKeyAlgorithm() + " key, and "
|
||||
+ what + " needs a " + (aes ? "AES" : "Triple DES") + " one", 400);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material
|
||||
*/
|
||||
static byte[] material(PaymentCryptographyKey key) {
|
||||
return PaymentCryptographyCrypto.fromHex(materialHex(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* The material of a key, as it is held.
|
||||
*
|
||||
* <p>The material is held by the key while the emulator runs and is not written to the
|
||||
* store, so a key read back after a restart has none. A request that needs the material
|
||||
* is then refused with an error that says so, rather than failing on the missing value.
|
||||
*
|
||||
* @param key the key the operation runs under
|
||||
* @return the key's material, as hexadecimal
|
||||
*/
|
||||
static String materialHex(PaymentCryptographyKey key) {
|
||||
String hex = key.getKeyMaterialHex();
|
||||
if (hex == null || hex.isEmpty()) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the material of the key " + key.getArn() + " is not held: it is kept while the "
|
||||
+ "emulator runs and is not written to the store, so a key read back after "
|
||||
+ "a restart has none", 400);
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
/**
|
||||
* The data plane's PIN operations.
|
||||
*
|
||||
* <p>The routes are the ones the AWS SDK builds: the PIN data is made, verified and
|
||||
* translated under the paths the model names.
|
||||
*/
|
||||
@Path(PaymentCryptographyDataPlaneRouteFilter.INTERNAL_PREFIX)
|
||||
public class PaymentCryptographyPinController extends PaymentCryptographyDataPlaneController {
|
||||
|
||||
private final PaymentCryptographyPinOperations operations;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyPinController(PaymentCryptographyPinOperations operations,
|
||||
ObjectMapper objectMapper,
|
||||
RegionResolver regionResolver) {
|
||||
super(objectMapper, regionResolver);
|
||||
this.operations = operations;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/pindata/generate")
|
||||
public Response generatePinData(String body, @Context HttpHeaders headers) {
|
||||
return respond(operations.generatePinData(parse(body), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/pindata/verify")
|
||||
public Response verifyPinData(String body, @Context HttpHeaders headers) {
|
||||
return respond(operations.verifyPinData(parse(body), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/pindata/translate")
|
||||
public Response translatePinData(String body, @Context HttpHeaders headers) {
|
||||
return respond(operations.translatePinData(parse(body), region(headers)));
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/macemvpinchange/generate")
|
||||
public Response generateMacEmvPinChange(String body, @Context HttpHeaders headers) {
|
||||
return respond(operations.generateMacEmvPinChange(parse(body), region(headers)));
|
||||
}
|
||||
|
||||
}
|
||||
+627
@@ -0,0 +1,627 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.PinBlockFormat;
|
||||
import io.floci.aws.services.paymentcryptography.crypto.PinCrypto;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.soleVariant;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyAttributes.text;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.materialHex;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireEnabled;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireFamily;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireMode;
|
||||
import static io.floci.aws.services.paymentcryptography.PaymentCryptographyKeyRules.requireUsage;
|
||||
|
||||
/**
|
||||
* The PIN operations, over the Visa PVV path.
|
||||
*
|
||||
* <p>VerifyPinData deciphers the inbound PIN block under the PEK, recovers the PIN, recomputes
|
||||
* the PVV under the PVK and compares. GeneratePinData is the same arithmetic with a fresh
|
||||
* random PIN. TranslatePinData re-enciphers a block from one PEK to another, which is the
|
||||
* core acquiring operation and the mechanism behind a PEK rotation.
|
||||
*
|
||||
* <p>PEK encryption: the eight-byte ISO 0 block is enciphered as a single TDES block, no IV
|
||||
* and no padding. ISO format 4 is the exception: it is a sixteen-byte block protected by AES,
|
||||
* and it binds the PIN to the whole PAN rather than to the twelve-digit account field. The
|
||||
* format decides the cipher, so a format and a key from different families are refused
|
||||
* together rather than producing a garbled PIN.
|
||||
*
|
||||
* <p>The IBM 3624 variants, the AS2805 translation and the EMV PIN change MAC are not made.
|
||||
* A request that asks for one of them is refused with the error that says so, rather than
|
||||
* answered with something of another kind.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class PaymentCryptographyPinOperations {
|
||||
|
||||
/** The PIN length the Visa path works over: the verification value is over four. */
|
||||
private static final int VISA_PIN_LENGTH = 4;
|
||||
|
||||
/** The usages a key may have for the encryption of a PIN block. */
|
||||
private static final List<String> PIN_ENCRYPTION_USAGES = List.of(
|
||||
"TR31_P0_PIN_ENCRYPTION_KEY");
|
||||
|
||||
/** The usages a key may have for the Visa PIN verification value. */
|
||||
private static final List<String> VISA_VERIFICATION_USAGES = List.of(
|
||||
"TR31_V2_VISA_PIN_VERIFICATION_KEY");
|
||||
|
||||
/** The usages a key may have for the derivation a DUKPT PIN key is made by. */
|
||||
private static final List<String> DERIVATION_USAGES = List.of(
|
||||
"TR31_B0_BASE_DERIVATION_KEY");
|
||||
|
||||
/** The source of the random fill of the format 3 blocks and the format 4 pads. */
|
||||
private final SecureRandom random;
|
||||
|
||||
private final PaymentCryptographyService service;
|
||||
|
||||
@Inject
|
||||
public PaymentCryptographyPinOperations(PaymentCryptographyService service) {
|
||||
this(service, new SecureRandom());
|
||||
}
|
||||
|
||||
PaymentCryptographyPinOperations(PaymentCryptographyService service, SecureRandom random) {
|
||||
this.service = service;
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
/**
|
||||
* A resolved PIN-encryption leg: the key the answer names, and the working key.
|
||||
*/
|
||||
private static final class PinLeg {
|
||||
/** The key the answer names. */
|
||||
final PaymentCryptographyKey record;
|
||||
/** The working key: the one that protects the PIN block. */
|
||||
final byte[] keyBytes;
|
||||
/** Whether the working key is an AES key. */
|
||||
final boolean aes;
|
||||
/** How the working key's algorithm is named in an error message. */
|
||||
final String algorithmName;
|
||||
|
||||
PinLeg(PaymentCryptographyKey record, byte[] keyBytes, boolean aes, String algorithmName) {
|
||||
this.record = record;
|
||||
this.keyBytes = keyBytes;
|
||||
this.aes = aes;
|
||||
this.algorithmName = algorithmName;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- VerifyPinData -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Verifies a PIN block against the verification value the issuer holds.
|
||||
*/
|
||||
Map<String, Object> verifyPinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("VerifyPinData", request);
|
||||
String encryptionKeyIdentifier = text(request, "EncryptionKeyIdentifier");
|
||||
String verificationKeyIdentifier = text(request, "VerificationKeyIdentifier");
|
||||
refuseWrappedKey(request, "EncryptionWrappedKey");
|
||||
PinBlockFormat format = format(text(request, "PinBlockFormat"));
|
||||
String pan = requirePan(text(request, "PrimaryAccountNumber"),
|
||||
"PrimaryAccountNumber is required for Visa PVV verification");
|
||||
requireVisaPinLength(request);
|
||||
requireExactLength(text(request, "EncryptedPinBlock"), format.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + format.blockHexLength()
|
||||
+ " characters (one " + format.label() + " block)");
|
||||
|
||||
JsonNode verificationAttributes = request.get("VerificationAttributes");
|
||||
String variant = soleVariant(verificationAttributes);
|
||||
if (variant == null) {
|
||||
throw validation("VerificationAttributes must specify exactly one variant");
|
||||
}
|
||||
if (!"VisaPin".equals(variant)) {
|
||||
throw validation("VerificationAttributes." + variant
|
||||
+ " not supported by this service (only VisaPin)");
|
||||
}
|
||||
JsonNode visa = verificationAttributes.get("VisaPin");
|
||||
int pvki = pvki(visa);
|
||||
String pvv = text(visa, "VerificationValue");
|
||||
|
||||
PinLeg pek = resolvePinLeg(encryptionKeyIdentifier, request.get("DukptAttributes"), region,
|
||||
"Decrypt", "decrypting a PIN block");
|
||||
requireNoDukptForAes(format, request.get("DukptAttributes"));
|
||||
requireKeyMatchesFormat(pek, format, "EncryptionKeyIdentifier");
|
||||
|
||||
PaymentCryptographyKey pvk = requiredKey(verificationKeyIdentifier, region);
|
||||
requireMode(pvk, "Verify", "verifying a PIN");
|
||||
requireUsage(pvk, VISA_VERIFICATION_USAGES, "verifying a PIN");
|
||||
// The Visa PVV is defined over Triple DES, so the key is one.
|
||||
requireFamily(pvk, false, "verifying a PIN");
|
||||
|
||||
String pin;
|
||||
try {
|
||||
pin = PinCrypto.decipherPinBlock(format, text(request, "EncryptedPinBlock"), pan,
|
||||
pek.keyBytes);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The block did not decipher into a well-formed PIN field: the key is another one,
|
||||
// the account number is another one, or the block is corrupted. The reference
|
||||
// answers that with the error that says the block is invalid.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
// A wrong key, or a wrong KSN, deciphers to garble, and what the block carries is
|
||||
// then not a PIN. That is an invalid block rather than a PIN that does not verify.
|
||||
if (!isRecoveredPin(pin)) {
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
// The Visa verification value is a four digit number, so a block that deciphers to a
|
||||
// longer PIN has no value to be compared with.
|
||||
if (pin.length() != VISA_PIN_LENGTH) {
|
||||
throw verificationFailed();
|
||||
}
|
||||
if (!PinCrypto.computePvv(pan, pvki, pin, materialHex(pvk)).equals(pvv)) {
|
||||
throw verificationFailed();
|
||||
}
|
||||
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("EncryptionKeyArn", pek.record.getArn());
|
||||
out.put("EncryptionKeyCheckValue", pek.record.getKeyCheckValue());
|
||||
out.put("VerificationKeyArn", pvk.getArn());
|
||||
out.put("VerificationKeyCheckValue", pvk.getKeyCheckValue());
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- GeneratePinData -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Generates a PIN block and the verification value that goes with it.
|
||||
*/
|
||||
Map<String, Object> generatePinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("GeneratePinData", request);
|
||||
String encryptionKeyIdentifier = text(request, "EncryptionKeyIdentifier");
|
||||
String generationKeyIdentifier = text(request, "GenerationKeyIdentifier");
|
||||
refuseWrappedKey(request, "EncryptionWrappedKey");
|
||||
PinBlockFormat format = format(text(request, "PinBlockFormat"));
|
||||
String pan = requirePan(text(request, "PrimaryAccountNumber"),
|
||||
"PrimaryAccountNumber is required");
|
||||
|
||||
JsonNode generationAttributes = request.get("GenerationAttributes");
|
||||
String variant = soleVariant(generationAttributes);
|
||||
if (!"VisaPin".equals(variant) && !"VisaPinVerificationValue".equals(variant)) {
|
||||
throw validation("GenerationAttributes." + (variant == null ? "(missing)" : variant)
|
||||
+ " not supported (VisaPin, VisaPinVerificationValue)");
|
||||
}
|
||||
JsonNode visa = generationAttributes == null ? null : generationAttributes.get(variant);
|
||||
int pvki = pvki(visa);
|
||||
|
||||
// VisaPinVerificationValue carries the block to verify, so the verification value is
|
||||
// computed for a PIN the caller already has rather than a new one.
|
||||
String givenBlock = "VisaPinVerificationValue".equals(variant) && visa != null
|
||||
? text(visa, "EncryptedPinBlock")
|
||||
: "";
|
||||
requireVisaPinLength(request);
|
||||
|
||||
PinLeg pek = resolvePinLeg(encryptionKeyIdentifier, null, region,
|
||||
"Encrypt", "encrypting a PIN block");
|
||||
PaymentCryptographyKey pvk = requiredKey(generationKeyIdentifier, region);
|
||||
requireMode(pvk, "Generate", "generating a PIN verification value");
|
||||
requireUsage(pvk, VISA_VERIFICATION_USAGES, "generating a PIN verification value");
|
||||
// The Visa PVV is defined over Triple DES, so the key is one.
|
||||
requireFamily(pvk, false, "generating a PIN verification value");
|
||||
requireKeyMatchesFormat(pek, format, "EncryptionKeyIdentifier");
|
||||
if (!givenBlock.isEmpty()) {
|
||||
// The caller's own block is decrypted to recover the PIN, so the key has to be
|
||||
// allowed to decrypt as well as to encrypt.
|
||||
requireMode(pek.record, "Decrypt", "decrypting a PIN block");
|
||||
}
|
||||
|
||||
String pin;
|
||||
String encryptedPinBlock;
|
||||
if (!givenBlock.isEmpty()) {
|
||||
// The caller's own block: recover the PIN from it and leave the block as it is.
|
||||
requireExactLength(givenBlock, format.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + format.blockHexLength()
|
||||
+ " characters (one " + format.label() + " block)");
|
||||
try {
|
||||
pin = PinCrypto.decipherPinBlock(format, givenBlock, pan, pek.keyBytes);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The caller's block did not decipher into a well-formed PIN field under the
|
||||
// key it named: the block and the key do not go together.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
if (!isRecoveredPin(pin)) {
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
encryptedPinBlock = givenBlock;
|
||||
} else {
|
||||
pin = randomPin(VISA_PIN_LENGTH);
|
||||
encryptedPinBlock = PinCrypto.encipherPinBlock(format, pin, pan, pek.keyBytes, random);
|
||||
}
|
||||
// The Visa verification value is a four digit number, so it is computed over a four
|
||||
// digit PIN. A block that carries a longer PIN has no value to be computed, and the
|
||||
// computation refuses it, so the length is checked here where the refusal is the
|
||||
// caller's to act on.
|
||||
if (pin.length() != VISA_PIN_LENGTH) {
|
||||
throw validation("the Visa verification value is computed over a four digit PIN, and "
|
||||
+ "the PIN block carries " + pin.length() + " digits");
|
||||
}
|
||||
String pvv = PinCrypto.computePvv(pan, pvki, pin, materialHex(pvk));
|
||||
|
||||
// The model's PinData is a union of the PIN offset and the verification value, and a
|
||||
// union carries one of them: this is the verification value.
|
||||
Map<String, Object> pinData = new LinkedHashMap<>();
|
||||
pinData.put("VerificationValue", pvv);
|
||||
Map<String, Object> out = new LinkedHashMap<>();
|
||||
out.put("EncryptedPinBlock", encryptedPinBlock);
|
||||
out.put("PinData", pinData);
|
||||
out.put("EncryptionKeyArn", pek.record.getArn());
|
||||
out.put("EncryptionKeyCheckValue", pek.record.getKeyCheckValue());
|
||||
out.put("GenerationKeyArn", pvk.getArn());
|
||||
out.put("GenerationKeyCheckValue", pvk.getKeyCheckValue());
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---- GenerateMacEmvPinChange ---------------------------------------------
|
||||
|
||||
/**
|
||||
* The EMV PIN change MAC.
|
||||
*
|
||||
* <p>The MAC of an EMV PIN change is taken over the command message with a session key
|
||||
* that the EMV secure messaging rules define, and this service does not make that
|
||||
* session key. The request is refused with the error that says so, rather than answered
|
||||
* with a MAC of another kind.
|
||||
*
|
||||
* <p>The route answers, so a client that calls the operation learns why it is refused,
|
||||
* but the action is not one the service lists as supported.
|
||||
*/
|
||||
Map<String, Object> generateMacEmvPinChange(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("GenerateMacEmvPinChange", request);
|
||||
throw validation("the EMV PIN change MAC is not supported by this service");
|
||||
}
|
||||
|
||||
// ---- TranslatePinData -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Re-enciphers a PIN block from one PEK to another.
|
||||
*/
|
||||
Map<String, Object> translatePinData(JsonNode request, String region) {
|
||||
// The request is checked against the constraints the model states for it.
|
||||
PaymentCryptographyDataRequestShapes.check("TranslatePinData", request);
|
||||
String incomingKeyIdentifier = text(request, "IncomingKeyIdentifier");
|
||||
String outgoingKeyIdentifier = text(request, "OutgoingKeyIdentifier");
|
||||
if (request.get("IncomingAs2805Attributes") != null) {
|
||||
throw validation("AS2805 translation is not supported by this service");
|
||||
}
|
||||
refuseWrappedKey(request, "IncomingWrappedKey");
|
||||
refuseWrappedKey(request, "OutgoingWrappedKey");
|
||||
|
||||
JsonNode incoming = request.get("IncomingTranslationAttributes");
|
||||
JsonNode outgoing = request.get("OutgoingTranslationAttributes");
|
||||
String inVariant = soleVariant(incoming);
|
||||
String outVariant = soleVariant(outgoing);
|
||||
if (inVariant == null) {
|
||||
throw validation("IncomingTranslationAttributes must specify exactly one format");
|
||||
}
|
||||
if (outVariant == null) {
|
||||
throw validation("OutgoingTranslationAttributes must specify exactly one format");
|
||||
}
|
||||
PinBlockFormat inFormat = PinBlockFormat.fromTranslationMember(inVariant);
|
||||
PinBlockFormat outFormat = PinBlockFormat.fromTranslationMember(outVariant);
|
||||
if (inFormat == null) {
|
||||
throw validation("IncomingTranslationAttributes." + inVariant
|
||||
+ " not supported (" + translationFormats() + ")");
|
||||
}
|
||||
if (outFormat == null) {
|
||||
throw validation("OutgoingTranslationAttributes." + outVariant
|
||||
+ " not supported (" + translationFormats() + ")");
|
||||
}
|
||||
|
||||
// The block length follows the incoming format: eight bytes for the TDES formats,
|
||||
// sixteen for the AES one.
|
||||
requireExactLength(text(request, "EncryptedPinBlock"), inFormat.blockHexLength(),
|
||||
"EncryptedPinBlock must be " + inFormat.blockHexLength()
|
||||
+ " characters (one " + inFormat.label() + " block)");
|
||||
|
||||
JsonNode inAttrs = incoming.get(inVariant);
|
||||
JsonNode outAttrs = outgoing.get(outVariant);
|
||||
String inPan = inAttrs == null ? "" : text(inAttrs, "PrimaryAccountNumber");
|
||||
String outPan = outAttrs == null ? "" : text(outAttrs, "PrimaryAccountNumber");
|
||||
// For PCI compliance the incoming and the outgoing account number are the same one,
|
||||
// and a PIN is not translated from one account number to another. The model states
|
||||
// that the attributes carry the account number, so the two are read and compared.
|
||||
if (!inPan.equals(outPan)) {
|
||||
throw validation("the incoming and the outgoing PrimaryAccountNumber must be the "
|
||||
+ "same one, and a PIN is not translated from one account number to another");
|
||||
}
|
||||
|
||||
PinLeg in = resolvePinLeg(incomingKeyIdentifier, request.get("IncomingDukptAttributes"), region,
|
||||
"Decrypt", "decrypting a PIN block");
|
||||
PinLeg out = resolvePinLeg(outgoingKeyIdentifier, request.get("OutgoingDukptAttributes"),
|
||||
region, "Encrypt", "encrypting a PIN block");
|
||||
requireNoDukptForAes(inFormat, request.get("IncomingDukptAttributes"));
|
||||
requireNoDukptForAes(outFormat, request.get("OutgoingDukptAttributes"));
|
||||
requireKeyMatchesFormat(in, inFormat, "IncomingKeyIdentifier");
|
||||
requireKeyMatchesFormat(out, outFormat, "OutgoingKeyIdentifier");
|
||||
|
||||
String pinBlock;
|
||||
try {
|
||||
String pin = PinCrypto.decipherPinBlock(inFormat, text(request, "EncryptedPinBlock"),
|
||||
inPan, in.keyBytes);
|
||||
if (!isRecoveredPin(pin)) {
|
||||
// The block deciphered, but what it carries is not a PIN, so it is not a block
|
||||
// the service can read.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
pinBlock = PinCrypto.encipherPinBlock(outFormat, pin, outPan, out.keyBytes, random);
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The incoming block did not decipher into a well-formed PIN field under the
|
||||
// incoming key: the caller's block and key do not go together.
|
||||
throw invalidPinBlock();
|
||||
}
|
||||
|
||||
Map<String, Object> out2 = new LinkedHashMap<>();
|
||||
out2.put("PinBlock", pinBlock);
|
||||
out2.put("KeyArn", out.record.getArn());
|
||||
out2.put("KeyCheckValue", out.record.getKeyCheckValue());
|
||||
return out2;
|
||||
}
|
||||
|
||||
// ---- the legs ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Resolves a PIN-encryption leg.
|
||||
*
|
||||
* <p>Without DUKPT attributes the identifier names a fixed PEK; with them it names a base
|
||||
* derivation key and the working key is the X9.24 DUKPT PIN key for the KSN.
|
||||
*/
|
||||
private PinLeg resolvePinLeg(String identifier, JsonNode dukptAttributes, String region,
|
||||
String mode, String what) {
|
||||
PaymentCryptographyKey key = service.findKey(region, identifier);
|
||||
if (key == null) {
|
||||
throw notFound(identifier);
|
||||
}
|
||||
requireEnabled(key);
|
||||
if (dukptAttributes == null) {
|
||||
requireMode(key, mode, what);
|
||||
requireUsage(key, PIN_ENCRYPTION_USAGES, what);
|
||||
PaymentCryptographyKeyAlgorithm algorithm = algorithmOf(key);
|
||||
return new PinLeg(key, PaymentCryptographyCrypto.fromHex(materialHex(key)), algorithm.aes,
|
||||
algorithm.name());
|
||||
}
|
||||
// A DUKPT PIN key is derived from the base derivation key, so that is what the key has
|
||||
// to allow, and the derivation is over Triple DES, so the key is one.
|
||||
requireMode(key, "DeriveKey", "deriving a PIN key");
|
||||
requireUsage(key, DERIVATION_USAGES, "deriving a PIN key");
|
||||
requireFamily(key, false, "deriving a PIN key");
|
||||
|
||||
// The model's DUKPT attributes come in two shapes. The PIN operations take
|
||||
// DukptAttributes, whose derivation type is DukptDerivationType, and the translation
|
||||
// takes DukptDerivationAttributes, whose derivation type is DukptKeyDerivationType and
|
||||
// whose variant is DukptKeyVariant. The derivation this path makes is the Triple DES
|
||||
// one, and the PIN key it derives is the one that both encrypts and decrypts.
|
||||
String ksn = text(dukptAttributes, "KeySerialNumber");
|
||||
String derivationType = text(dukptAttributes, "DukptDerivationType");
|
||||
if (derivationType.isEmpty()) {
|
||||
derivationType = text(dukptAttributes, "DukptKeyDerivationType");
|
||||
}
|
||||
if (!derivationType.isEmpty() && !"TDES_2KEY".equals(derivationType)) {
|
||||
throw validation("the DUKPT derivation type '" + derivationType
|
||||
+ "' is not supported by this service (TDES_2KEY)");
|
||||
}
|
||||
String keyVariant = text(dukptAttributes, "DukptKeyVariant");
|
||||
if (!keyVariant.isEmpty() && !"BIDIRECTIONAL".equals(keyVariant)) {
|
||||
throw validation("the DUKPT key variant '" + keyVariant
|
||||
+ "' is not supported by this service (BIDIRECTIONAL)");
|
||||
}
|
||||
try {
|
||||
// A DUKPT PIN key is a TDES key, whatever the base derivation key is.
|
||||
return new PinLeg(key, DukptCrypto.pinKey(materialHex(key), ksn), false, "TDES");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// The derivation refuses what the request names, so the refusal is the caller's to
|
||||
// act on.
|
||||
throw validation("DUKPT derivation failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses DUKPT for a format that needs an AES key.
|
||||
*
|
||||
* <p>DUKPT derives a TDES PIN key, so it can only ever produce a format 0 or 3 block.
|
||||
*/
|
||||
private static void requireNoDukptForAes(PinBlockFormat format, JsonNode dukptAttributes) {
|
||||
if (format.isAes() && dukptAttributes != null) {
|
||||
throw validation("DukptAttributes derive a TDES PIN key, but " + format.name()
|
||||
+ " PIN blocks require an AES PEK");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the PIN encryption key suits the PIN block format.
|
||||
*
|
||||
* <p>Formats 0 and 3 are eight-byte TDES blocks and format 4 is a sixteen-byte AES block. A
|
||||
* key from the wrong family cannot produce a block of that shape, so the mismatch is a
|
||||
* validation error rather than a garbled PIN.
|
||||
*/
|
||||
private static void requireKeyMatchesFormat(PinLeg leg, PinBlockFormat format, String label) {
|
||||
if (leg.aes != format.isAes()) {
|
||||
throw validation(label + " must resolve to an "
|
||||
+ (format.isAes() ? "AES" : "TDES") + " key for " + format.name()
|
||||
+ " PIN blocks (it resolves to " + leg.algorithmName + ")");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the helpers ---------------------------------------------------------
|
||||
|
||||
private PaymentCryptographyKey requiredKey(String identifier, String region) {
|
||||
PaymentCryptographyKey key = service.findKey(region, identifier);
|
||||
if (key == null) {
|
||||
throw notFound(identifier);
|
||||
}
|
||||
requireEnabled(key);
|
||||
return key;
|
||||
}
|
||||
|
||||
private static PaymentCryptographyKeyAlgorithm algorithmOf(PaymentCryptographyKey key) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
|
||||
if (algorithm == null) {
|
||||
throw validation("the key " + key.getArn() + " has the algorithm "
|
||||
+ key.getKeyAlgorithm() + ", which this service does not make");
|
||||
}
|
||||
return algorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* The PIN length the request declares, which the Visa path fixes at four digits.
|
||||
*
|
||||
* <p>The Visa verification value is a four digit number, and the algorithm's transformed
|
||||
* security parameter is sixteen digits: eleven of account number, one of verification key
|
||||
* index and four of PIN. A longer PIN has no place in it, so there is no verification
|
||||
* value for one, and a request that declares another length names something this path
|
||||
* cannot answer.
|
||||
*
|
||||
* <p>The model lets the length be between four and twelve, which is the range of the PIN
|
||||
* a block holds and the range the IBM 3624 variants need; the Visa verification value is
|
||||
* the four digit one.
|
||||
*
|
||||
* @param request the request, whose PinDataLength member may be absent
|
||||
*/
|
||||
private static void requireVisaPinLength(JsonNode request) {
|
||||
JsonNode declared = request.get("PinDataLength");
|
||||
if (declared == null || declared.isNull()) {
|
||||
return;
|
||||
}
|
||||
if (!declared.isIntegralNumber() || declared.asInt() != VISA_PIN_LENGTH) {
|
||||
throw validation("Visa PVV requires a 4-digit PIN (PinDataLength 4)");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses the wrapped-key form of a PIN encryption key.
|
||||
*
|
||||
* <p>A wrapped key is a TR-31 key block that the service unwraps with a key-encryption
|
||||
* key, and the unwrapping is part of the key exchange. Until it is made, a request that
|
||||
* carries one is refused rather than answered as if the key were a fixed one.
|
||||
*/
|
||||
private static void refuseWrappedKey(JsonNode request, String member) {
|
||||
if (request.get(member) != null) {
|
||||
throw validation(member + " is not supported by this service");
|
||||
}
|
||||
}
|
||||
|
||||
private static PinBlockFormat format(String wireName) {
|
||||
PinBlockFormat format = PinBlockFormat.from(wireName);
|
||||
if (format == null) {
|
||||
throw validation("PinBlockFormat '" + wireName + "' not supported by this service ("
|
||||
+ PinBlockFormat.supported() + ")");
|
||||
}
|
||||
return format;
|
||||
}
|
||||
|
||||
/**
|
||||
* The verification key index the attributes name.
|
||||
*
|
||||
* <p>The model states that the attributes carry the index and the range it holds, and the
|
||||
* request has been checked against it, so it is read and not checked again.
|
||||
*
|
||||
* @param visa the VisaPin attributes of the request
|
||||
* @return the index of the verification key
|
||||
*/
|
||||
private static int pvki(JsonNode visa) {
|
||||
return visa.path("PinVerificationKeyIndex").asInt();
|
||||
}
|
||||
|
||||
/**
|
||||
* The account number the request names.
|
||||
*
|
||||
* <p>The member is optional in the model, so a request that leaves it out is refused
|
||||
* here. Its length and its digits are the model's to settle.
|
||||
*
|
||||
* @param pan the account number of the request
|
||||
* @param message what to say when the request leaves it out
|
||||
* @return the account number
|
||||
*/
|
||||
private static String requirePan(String pan, String message) {
|
||||
if (pan.isEmpty()) {
|
||||
throw validation(message);
|
||||
}
|
||||
return pan;
|
||||
}
|
||||
|
||||
private static void requireExactLength(String value, int length, String message) {
|
||||
if (value == null || value.length() != length) {
|
||||
throw validation(message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a recovered PIN is one the service can work with.
|
||||
*
|
||||
* <p>A block that was enciphered under another key deciphers to something that is not a
|
||||
* PIN, and what it carries is then not a PIN block the service can read.
|
||||
*/
|
||||
private static boolean isRecoveredPin(String pin) {
|
||||
if (pin == null || pin.length() < 4 || pin.length() > 12) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < pin.length(); i++) {
|
||||
if (!Character.isDigit(pin.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private String randomPin(int length) {
|
||||
StringBuilder pin = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
pin.append(random.nextInt(10));
|
||||
}
|
||||
return pin.toString();
|
||||
}
|
||||
|
||||
/** The translation attributes this service accepts, for a message. */
|
||||
private static String translationFormats() {
|
||||
StringBuilder names = new StringBuilder();
|
||||
for (PinBlockFormat format : PinBlockFormat.values()) {
|
||||
if (names.length() > 0) {
|
||||
names.append(", ");
|
||||
}
|
||||
names.append(format.translationMember());
|
||||
}
|
||||
return names.toString();
|
||||
}
|
||||
|
||||
private static AwsException validation(String message) {
|
||||
return new AwsException("ValidationException", message, 400);
|
||||
}
|
||||
|
||||
private static AwsException notFound(String identifier) {
|
||||
return new AwsException("ResourceNotFoundException", "Key not found: " + identifier, 404);
|
||||
}
|
||||
|
||||
/**
|
||||
* The PIN did not verify.
|
||||
*
|
||||
* <p>A PIN that does not verify is not a bad request: the request was well made and the
|
||||
* answer is that the PIN is not the one the issuer holds.
|
||||
*/
|
||||
private static AwsException verificationFailed() {
|
||||
return new AwsException("VerificationFailedException", "Pin block verification failed.", 400,
|
||||
Map.of("Reason", "INVALID_PIN"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The PIN block the request carries is not one the service can read.
|
||||
*
|
||||
* <p>The reference answers a block that is not a valid PIN block with this error, and
|
||||
* names the three causes: the wrong key, a wrong account number, and a corrupted block.
|
||||
*
|
||||
* @return the error that says the block is invalid
|
||||
*/
|
||||
private static AwsException invalidPinBlock() {
|
||||
return new AwsException("ValidationException",
|
||||
"Pin block provided is invalid. Please check your input to ensure all field "
|
||||
+ "values are correct.", 400);
|
||||
}
|
||||
}
|
||||
@@ -101,12 +101,29 @@ public final class Ciphers {
|
||||
/**
|
||||
* The Triple DES encryption of a block under a three-key key, in ECB mode.
|
||||
*
|
||||
* <p>The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
|
||||
* is what the two-key form means. A three-key key is taken as it is.
|
||||
*
|
||||
* @param block8 the eight-byte block to encrypt
|
||||
* @param key24 the twenty-four-byte key
|
||||
* @param key the sixteen- or twenty-four-byte key
|
||||
* @return the encrypted block
|
||||
*/
|
||||
public static byte[] tdes3Encrypt(byte[] block8, byte[] key24) {
|
||||
return block(new DESedeEngine(), true, block8, key24);
|
||||
public static byte[] tdes3Encrypt(byte[] block8, byte[] key) {
|
||||
return block(new DESedeEngine(), true, block8, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Triple DES decryption of a block under a key, in ECB mode.
|
||||
*
|
||||
* <p>The two-key form is K1||K2, and the cipher takes the three keys K1||K2||K1, which
|
||||
* is what the two-key form means. A three-key key is taken as it is.
|
||||
*
|
||||
* @param block8 the eight-byte block to decrypt
|
||||
* @param key the sixteen- or twenty-four-byte key
|
||||
* @return the decrypted block
|
||||
*/
|
||||
public static byte[] tdesEcbDecrypt(byte[] block8, byte[] key) {
|
||||
return block(new DESedeEngine(), false, block8, key);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
/**
|
||||
* The decimalization the Visa PIN Verification Value is made of.
|
||||
*
|
||||
* <p>The digits of the enciphered block are taken first, from left to right, and the letters
|
||||
* are turned into numbers only if there are not enough digits: a letter stands for its own
|
||||
* value less ten, so A is zero, B is one, and F is five.
|
||||
*/
|
||||
public final class Decimalize {
|
||||
|
||||
private Decimalize() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The first n digits of a hexadecimal string, decimalized.
|
||||
*
|
||||
* <p>The digits are taken first, from left to right. When there are not enough of them,
|
||||
* the letters fill the gap, from left to right, each one standing for its own value less
|
||||
* ten.
|
||||
*
|
||||
* @param hex the hexadecimal string
|
||||
* @param n the number of digits wanted
|
||||
* @return the digits, which may be shorter than n when the string holds too few
|
||||
*/
|
||||
public static String of(String hex, int n) {
|
||||
StringBuilder out = new StringBuilder(n);
|
||||
for (int i = 0; i < hex.length() && out.length() < n; i++) {
|
||||
char c = hex.charAt(i);
|
||||
if (c >= '0' && c <= '9') {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
if (out.length() < n) {
|
||||
for (int i = 0; i < hex.length() && out.length() < n; i++) {
|
||||
int v = Character.digit(hex.charAt(i), 16);
|
||||
if (v >= 10) {
|
||||
out.append(v - 10);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import java.util.HexFormat;
|
||||
* <pre>
|
||||
* 1. IPEK derivation BDK + initial KSN -> IPEK
|
||||
* 2. Transaction key IPEK + KSN counter bits -> derived key (one-way)
|
||||
* 3. Working-key variant derived key XOR mask -> MAC-request key
|
||||
* 3. Working-key variants derived key XOR mask -> PIN / MAC-request key
|
||||
* </pre>
|
||||
*
|
||||
* <p>Validated against the vectors ANSI X9.24-1 publishes, which the test holds: the
|
||||
@@ -23,6 +23,7 @@ import java.util.HexFormat;
|
||||
public final class DukptCrypto {
|
||||
|
||||
private static final byte[] KEY_VARIANT = HexFormat.of().parseHex("C0C0C0C000000000C0C0C0C000000000");
|
||||
private static final byte[] PIN_MASK = HexFormat.of().parseHex("00000000000000FF00000000000000FF");
|
||||
private static final byte[] MAC_REQUEST_MASK = HexFormat.of().parseHex("000000000000FF00000000000000FF00");
|
||||
|
||||
private DukptCrypto() {
|
||||
@@ -110,6 +111,11 @@ public final class DukptCrypto {
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The PIN encryption working key. */
|
||||
public static byte[] pinKey(String bdkHex, String ksnHex) {
|
||||
return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), PIN_MASK);
|
||||
}
|
||||
|
||||
/** The MAC-request working key. */
|
||||
public static byte[] macKey(String bdkHex, String ksnHex) {
|
||||
return Ciphers.xor(deriveTransactionKey(bdkHex, ksnHex), MAC_REQUEST_MASK);
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The ISO 9564-1 PIN block formats the service makes.
|
||||
*
|
||||
* <p>Three of the four formats the API names are made: the format 0 and the format 3 are
|
||||
* eight-byte Triple DES blocks, and the format 4 is a sixteen-byte AES block. The format 1
|
||||
* the API also names is a format ISO 9564-1 defines, a block that carries no PAN, but this
|
||||
* service does not make it, so a request that asks for one is refused rather than answered
|
||||
* with a block of some other format.
|
||||
*/
|
||||
public enum PinBlockFormat {
|
||||
|
||||
/** The eight-byte Triple DES block that fills with F. */
|
||||
ISO_FORMAT_0(8, false),
|
||||
|
||||
/** The eight-byte Triple DES block that fills with random nibbles. */
|
||||
ISO_FORMAT_3(8, false),
|
||||
|
||||
/** The sixteen-byte AES block that binds the PIN to the whole account number. */
|
||||
ISO_FORMAT_4(16, true);
|
||||
|
||||
/** The block the format is, in bytes. */
|
||||
private final int blockBytes;
|
||||
|
||||
/** Whether the format is protected by an AES key rather than a Triple DES one. */
|
||||
private final boolean aes;
|
||||
|
||||
PinBlockFormat(int blockBytes, boolean aes) {
|
||||
this.blockBytes = blockBytes;
|
||||
this.aes = aes;
|
||||
}
|
||||
|
||||
/** The block the format is, in bytes. */
|
||||
public int blockBytes() {
|
||||
return blockBytes;
|
||||
}
|
||||
|
||||
/** The block the format is, in hexadecimal characters. */
|
||||
public int blockHexLength() {
|
||||
return blockBytes * 2;
|
||||
}
|
||||
|
||||
/** Whether the format is protected by an AES key rather than a Triple DES one. */
|
||||
public boolean isAes() {
|
||||
return aes;
|
||||
}
|
||||
|
||||
/** How the format is named in a message. */
|
||||
public String label() {
|
||||
return "ISO-" + suffix();
|
||||
}
|
||||
|
||||
/** How the format is named in the translation attributes. */
|
||||
public String translationMember() {
|
||||
return "IsoFormat" + suffix();
|
||||
}
|
||||
|
||||
private String suffix() {
|
||||
return name().substring("ISO_FORMAT_".length());
|
||||
}
|
||||
|
||||
/**
|
||||
* The format a name in {@code PinBlockFormat} names.
|
||||
*
|
||||
* @param wireName the name the request carries
|
||||
* @return the format, or null when the name is one this service does not make
|
||||
*/
|
||||
public static PinBlockFormat from(String wireName) {
|
||||
if (wireName == null) {
|
||||
return null;
|
||||
}
|
||||
for (PinBlockFormat format : values()) {
|
||||
if (format.name().equals(wireName)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The format a name in the translation attributes names.
|
||||
*
|
||||
* @param member the name the request carries
|
||||
* @return the format, or null when the name is one this service does not make
|
||||
*/
|
||||
public static PinBlockFormat fromTranslationMember(String member) {
|
||||
if (member == null) {
|
||||
return null;
|
||||
}
|
||||
for (PinBlockFormat format : values()) {
|
||||
if (format.translationMember().equals(member)) {
|
||||
return format;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The formats this service makes, for a message. */
|
||||
public static String supported() {
|
||||
List<String> names = new ArrayList<>();
|
||||
for (PinBlockFormat format : values()) {
|
||||
names.add(format.name());
|
||||
}
|
||||
return String.join(", ", names);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import java.util.HexFormat;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* Issuer PIN primitives: the ISO 9564-1 PIN blocks and their decoders.
|
||||
*
|
||||
* <p>The account field is the 12 right-most PAN digits <em>excluding the check
|
||||
* digit</em>. The API takes a primary account number, which carries its own
|
||||
* check digit, so the digit is dropped and the twelve right-most of what is
|
||||
* left are the field. A PAN of twelve digits leaves eleven, and the field is
|
||||
* padded with a zero on the left.
|
||||
*
|
||||
* <p>Format 4 is the odd one out. It does not use the account field at all:
|
||||
* it carries the whole PAN, and it is the only format an AES key can protect.
|
||||
*
|
||||
* <p>The blocks are enciphered in ECB mode, which is what ISO 9564-1 defines: one block
|
||||
* goes in and one block comes out. The ciphers are BouncyCastle's, so the block that goes
|
||||
* in and the block that comes out are the ones the standard is written over.
|
||||
*/
|
||||
public final class PinCrypto {
|
||||
|
||||
/** The hexadecimal form the blocks are written in: upper case, no separators. */
|
||||
private static final HexFormat HEX = HexFormat.of().withUpperCase();
|
||||
|
||||
private PinCrypto() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The 12-digit ISO-0 account field.
|
||||
*
|
||||
* <p>The field is the twelve right-most digits of the PAN without its check
|
||||
* digit, so the digit is dropped and the twelve right-most of what is left
|
||||
* are the field. A PAN of twelve digits leaves eleven, and the field is
|
||||
* padded with a zero on the left.
|
||||
*
|
||||
* @throws IllegalArgumentException if the PAN has fewer than twelve digits,
|
||||
* which is fewer than the field holds
|
||||
*/
|
||||
public static String account12(String pan) {
|
||||
String d = digits(pan);
|
||||
if (d.length() < 12) {
|
||||
throw new IllegalArgumentException("the account field is twelve digits, and the PAN "
|
||||
+ "has fewer");
|
||||
}
|
||||
String withoutCheckDigit = d.substring(0, d.length() - 1);
|
||||
if (withoutCheckDigit.length() >= 12) {
|
||||
return withoutCheckDigit.substring(withoutCheckDigit.length() - 12);
|
||||
}
|
||||
return "0" + withoutCheckDigit;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ISO 9564-1 Format-0 clear PIN block, as 16 upper-case hex characters.
|
||||
*
|
||||
* <p>Layout: a filler nibble, the PIN length as one hex digit, the PIN
|
||||
* digits, then {@code F} padding to 16 characters. XOR that against
|
||||
* {@code 0000} followed by the account field.
|
||||
*/
|
||||
public static String iso0PinBlock(String pin, String pan) {
|
||||
String p = digits(pin);
|
||||
if (p.length() < 4 || p.length() > 12) {
|
||||
throw new IllegalArgumentException("PIN length must be 4..12");
|
||||
}
|
||||
StringBuilder pinField = new StringBuilder();
|
||||
pinField.append('0');
|
||||
pinField.append(Integer.toHexString(p.length()).toUpperCase());
|
||||
pinField.append(p);
|
||||
while (pinField.length() < 16) {
|
||||
pinField.append('F');
|
||||
}
|
||||
String panField = "0000" + account12(pan);
|
||||
return HEX.formatHex(Ciphers.xor(
|
||||
HEX.parseHex(pinField.toString()), HEX.parseHex(panField)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Recover the clear PIN digits from a Format-0 or Format-3 block.
|
||||
*
|
||||
* <p>The block is checked before the PIN is read out of it. The format nibble says which
|
||||
* format the block is, the length nibble says how long the PIN is, the digits have to be
|
||||
* digits, and the fill has to be what the format says it is. A block that is not checked
|
||||
* would give a PIN out of a block of another format, and a block that was made up would
|
||||
* pass as one that was not.
|
||||
*
|
||||
* @param blockHex the clear block, as hexadecimal
|
||||
* @param pan the account number the block is bound to
|
||||
* @param format the format the block is in
|
||||
* @return the PIN the block carries
|
||||
*/
|
||||
public static String decodeIso0PinBlock(String blockHex, String pan, PinBlockFormat format) {
|
||||
String panField = "0000" + account12(pan);
|
||||
String pinField = HEX.formatHex(Ciphers.xor(HEX.parseHex(blockHex), HEX.parseHex(panField)));
|
||||
if (pinField.length() != 16) {
|
||||
throw new IllegalArgumentException("the PIN block is " + pinField.length()
|
||||
+ " characters; it is 16");
|
||||
}
|
||||
char formatNibble = pinField.charAt(0);
|
||||
char wanted = format == PinBlockFormat.ISO_FORMAT_3 ? '3' : '0';
|
||||
if (formatNibble != wanted) {
|
||||
throw new IllegalArgumentException("the PIN block is a format " + formatNibble
|
||||
+ " block, and a " + format.label() + " block was expected");
|
||||
}
|
||||
int len = Character.digit(pinField.charAt(1), 16);
|
||||
if (len < 4 || len > 12) {
|
||||
throw new IllegalArgumentException("the PIN block says the PIN is " + len
|
||||
+ " digits; it is 4 to 12");
|
||||
}
|
||||
String pin = pinField.substring(2, 2 + len);
|
||||
for (int i = 0; i < pin.length(); i++) {
|
||||
if (!Character.isDigit(pin.charAt(i))) {
|
||||
throw new IllegalArgumentException("the PIN block does not carry digits");
|
||||
}
|
||||
}
|
||||
for (int i = 2 + len; i < pinField.length(); i++) {
|
||||
char fill = pinField.charAt(i);
|
||||
// Format 0 fills with F, and format 3 with a value in the range A to F.
|
||||
boolean good = format == PinBlockFormat.ISO_FORMAT_3
|
||||
? fill >= 'A' && fill <= 'F'
|
||||
: fill == 'F';
|
||||
if (!good) {
|
||||
throw new IllegalArgumentException("the PIN block does not carry the fill of a "
|
||||
+ format.label() + " block");
|
||||
}
|
||||
}
|
||||
return pin;
|
||||
}
|
||||
|
||||
// ---- ISO 9564-1 Format 3 ------------------------------------------------
|
||||
|
||||
/**
|
||||
* The ISO 9564-1 Format-3 clear PIN block, as 16 upper-case hex characters.
|
||||
*
|
||||
* <p>Format 3 is format 0 with two differences: the control nibble is
|
||||
* {@code 3}, and the fill nibbles are random values in the range A to F
|
||||
* rather than a constant F. The random fill is the point of the format -
|
||||
* it stops the same PIN from producing the same ciphertext twice.
|
||||
*
|
||||
* @param random the source of the fill nibbles
|
||||
*/
|
||||
public static String iso3PinBlock(String pin, String pan, Random random) {
|
||||
String p = digits(pin);
|
||||
if (p.length() < 4 || p.length() > 12) {
|
||||
throw new IllegalArgumentException("PIN length must be 4..12");
|
||||
}
|
||||
StringBuilder pinField = new StringBuilder();
|
||||
pinField.append('3');
|
||||
pinField.append(Integer.toHexString(p.length()).toUpperCase());
|
||||
pinField.append(p);
|
||||
while (pinField.length() < 16) {
|
||||
// 10 to 15, which is A to F.
|
||||
pinField.append(Integer.toHexString(10 + random.nextInt(6)).toUpperCase());
|
||||
}
|
||||
String panField = "0000" + account12(pan);
|
||||
return HEX.formatHex(Ciphers.xor(
|
||||
HEX.parseHex(pinField.toString()), HEX.parseHex(panField)));
|
||||
}
|
||||
|
||||
// ---- ISO 9564-1 Format 4 ------------------------------------------------
|
||||
|
||||
/**
|
||||
* The ISO 9564-1 Format-4 plain-text PIN field: 16 bytes.
|
||||
*
|
||||
* <p>Layout: the control nibble {@code 4}, the PIN length, the PIN digits,
|
||||
* {@code A} fill up to 16 nibbles, then 8 random bytes. The random half is
|
||||
* what makes every block unique, so the same PIN never enciphers to the
|
||||
* same ciphertext twice.
|
||||
*
|
||||
* @param randomPad 8 random bytes
|
||||
*/
|
||||
public static byte[] iso4PinField(String pin, byte[] randomPad) {
|
||||
String p = digits(pin);
|
||||
if (p.length() < 4 || p.length() > 12) {
|
||||
throw new IllegalArgumentException("PIN length must be 4..12");
|
||||
}
|
||||
if (randomPad == null || randomPad.length != 8) {
|
||||
throw new IllegalArgumentException("the random pad must be 8 bytes");
|
||||
}
|
||||
StringBuilder pinField = new StringBuilder();
|
||||
pinField.append('4');
|
||||
pinField.append(Integer.toHexString(p.length()).toUpperCase());
|
||||
pinField.append(p);
|
||||
while (pinField.length() < 16) {
|
||||
pinField.append('A');
|
||||
}
|
||||
pinField.append(HEX.formatHex(randomPad));
|
||||
return HEX.parseHex(pinField.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The ISO 9564-1 Format-4 plain-text PAN field: 16 bytes.
|
||||
*
|
||||
* <p>Layout: the M nibble, which records the PAN length as 12 plus its own
|
||||
* value, then the PAN digits, then zero padding to 32 nibbles. A PAN
|
||||
* shorter than 12 digits is right justified and padded to the left with
|
||||
* zeros, and M is then zero.
|
||||
*
|
||||
* <p>The field carries the whole PAN, the check digit included, which is
|
||||
* what the standard says: the format 4 PAN field is the complete PAN,
|
||||
* where the account field of the formats 0 and 3 is the twelve right-most
|
||||
* digits without the check digit.
|
||||
*
|
||||
* <p>The M nibble is four bits, so the PAN it records may be up to twenty
|
||||
* seven digits, which is what the field holds beside the nibble.
|
||||
*/
|
||||
public static byte[] iso4PanField(String pan) {
|
||||
String d = digits(pan);
|
||||
if (d.isEmpty() || d.length() > 27) {
|
||||
throw new IllegalArgumentException("the PAN field holds up to twenty seven digits");
|
||||
}
|
||||
StringBuilder panField = new StringBuilder();
|
||||
panField.append(Integer.toHexString(Math.max(0, d.length() - 12)));
|
||||
String panDigits = d;
|
||||
while (panDigits.length() < 12) {
|
||||
panDigits = "0" + panDigits;
|
||||
}
|
||||
panField.append(panDigits);
|
||||
while (panField.length() < 32) {
|
||||
panField.append('0');
|
||||
}
|
||||
return HEX.parseHex(panField.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The encrypted ISO 9564-1 Format-4 PIN block, as 32 upper-case hex
|
||||
* characters.
|
||||
*
|
||||
* <p>The PIN field is enciphered, XORed with the PAN field, and the result
|
||||
* enciphered again. Two passes, because one pass over the PIN field alone
|
||||
* would not bind the PIN to the account.
|
||||
*
|
||||
* @param key the AES PIN encryption key
|
||||
* @param randomPad 8 random bytes for the random half of the PIN field
|
||||
*/
|
||||
public static String iso4PinBlock(String pin, String pan, byte[] key, byte[] randomPad) {
|
||||
byte[] intermediateA = Ciphers.aesEcbEncrypt(iso4PinField(pin, randomPad), key);
|
||||
byte[] intermediateB = Ciphers.xor(intermediateA, iso4PanField(pan));
|
||||
return HEX.formatHex(Ciphers.aesEcbEncrypt(intermediateB, key));
|
||||
}
|
||||
|
||||
/**
|
||||
* The encrypted ISO 9564-1 Format-4 PIN block, with the random half drawn
|
||||
* from {@code random}.
|
||||
*/
|
||||
public static String iso4PinBlock(String pin, String pan, byte[] key, Random random) {
|
||||
byte[] randomPad = new byte[8];
|
||||
random.nextBytes(randomPad);
|
||||
return iso4PinBlock(pin, pan, key, randomPad);
|
||||
}
|
||||
|
||||
/**
|
||||
* Recover the clear PIN digits from an encrypted Format-4 block.
|
||||
*
|
||||
* @return the PIN digits, or null when the block does not carry a
|
||||
* well-formed Format-4 PIN field. A wrong key or a wrong PAN
|
||||
* produces exactly that, so the caller reports a failed
|
||||
* verification rather than a bad request.
|
||||
*/
|
||||
public static String decodeIso4PinBlock(String blockHex, String pan, byte[] key) {
|
||||
byte[] intermediateB = Ciphers.aesEcbDecrypt(HEX.parseHex(blockHex), key);
|
||||
byte[] intermediateA = Ciphers.xor(intermediateB, iso4PanField(pan));
|
||||
String pinField = HEX.formatHex(Ciphers.aesEcbDecrypt(intermediateA, key));
|
||||
|
||||
if (pinField.charAt(0) != '4') {
|
||||
return null;
|
||||
}
|
||||
int len = Character.digit(pinField.charAt(1), 16);
|
||||
if (len < 4 || len > 12) {
|
||||
return null;
|
||||
}
|
||||
String pin = pinField.substring(2, 2 + len);
|
||||
if (!pin.matches("[0-9]{4,12}")) {
|
||||
return null;
|
||||
}
|
||||
// The fill between the PIN and the random half is fixed at A.
|
||||
StringBuilder fill = new StringBuilder();
|
||||
for (int i = 0; i < 14 - len; i++) {
|
||||
fill.append('A');
|
||||
}
|
||||
if (!pinField.substring(2 + len, 16).equals(fill.toString())) {
|
||||
return null;
|
||||
}
|
||||
return pin;
|
||||
}
|
||||
|
||||
// ---- format dispatch ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* Encipher a PIN into a PIN block of the given format.
|
||||
*
|
||||
* @param format the ISO 9564-1 format
|
||||
* @param pin the clear PIN
|
||||
* @param pan the PAN in the form the format takes: a whole PAN for format 4,
|
||||
* and anything the account field can be derived from for
|
||||
* formats 0 and 3
|
||||
* @param key the PIN encryption key: TDES for formats 0 and 3, AES for
|
||||
* format 4
|
||||
* @param random the source of the random fill
|
||||
*/
|
||||
public static String encipherPinBlock(PinBlockFormat format, String pin, String pan,
|
||||
byte[] key, Random random) {
|
||||
switch (format) {
|
||||
case ISO_FORMAT_0:
|
||||
return HEX.formatHex(Ciphers.tdes3Encrypt(
|
||||
HEX.parseHex(iso0PinBlock(pin, pan)), key));
|
||||
case ISO_FORMAT_3:
|
||||
return HEX.formatHex(Ciphers.tdes3Encrypt(
|
||||
HEX.parseHex(iso3PinBlock(pin, pan, random)), key));
|
||||
case ISO_FORMAT_4:
|
||||
return iso4PinBlock(pin, pan, key, random);
|
||||
default:
|
||||
throw new IllegalArgumentException("unsupported PIN block format: " + format);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decipher a PIN block of the given format and recover the PIN.
|
||||
*
|
||||
* @param pan the PAN in the form the format takes
|
||||
* @param key the PIN encryption key
|
||||
* @return the PIN digits, or null when the block does not carry a
|
||||
* well-formed PIN field
|
||||
*/
|
||||
public static String decipherPinBlock(PinBlockFormat format, String blockHex, String pan,
|
||||
byte[] key) {
|
||||
switch (format) {
|
||||
case ISO_FORMAT_0:
|
||||
case ISO_FORMAT_3:
|
||||
return decodeIso0PinBlock(
|
||||
HEX.formatHex(Ciphers.tdesEcbDecrypt(HEX.parseHex(blockHex), key)), pan,
|
||||
format);
|
||||
case ISO_FORMAT_4:
|
||||
return decodeIso4PinBlock(blockHex, pan, key);
|
||||
default:
|
||||
throw new IllegalArgumentException("unsupported PIN block format: " + format);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Visa PVV, the standard algorithm.
|
||||
*
|
||||
* <pre>
|
||||
* TSP (16 digits) = 11 rightmost PAN digits excluding the check digit
|
||||
* + 1 PVKI digit + 4 PIN digits
|
||||
* PVV = decimalize(3DES_EDE(PVK, TSP as an 8-byte block), 4)
|
||||
* </pre>
|
||||
*
|
||||
* <p>{@code pvkHex} is a double-length (16-byte) key.
|
||||
*/
|
||||
public static String computePvv(String pan, int pvki, String pin, String pvkHex) {
|
||||
String d = digits(pan);
|
||||
String pan11 = tspDigits(d);
|
||||
String p4 = digits(pin);
|
||||
if (p4.length() != 4) {
|
||||
throw new IllegalArgumentException("Visa PVV uses a 4-digit PIN");
|
||||
}
|
||||
String tsp = pan11 + pvki + p4;
|
||||
if (tsp.length() != 16) {
|
||||
throw new IllegalArgumentException("TSP must be 16 digits, got " + tsp.length());
|
||||
}
|
||||
return Decimalize.of(
|
||||
HEX.formatHex(Ciphers.tdes2Encrypt(HEX.parseHex(tsp), HEX.parseHex(pvkHex))), 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* The 11 digits of the TSP: the 11 right-most digits of the account
|
||||
* number, excluding the check digit.
|
||||
*
|
||||
* <p>The API takes a primary account number, which carries its own check
|
||||
* digit, so the digit is dropped and the eleven right-most of what is left
|
||||
* are the TSP's.
|
||||
*/
|
||||
private static String tspDigits(String pan) {
|
||||
return pan.substring(0, pan.length() - 1)
|
||||
.substring(pan.length() - 1 - 11);
|
||||
}
|
||||
|
||||
/** Strip everything that is not a decimal digit. */
|
||||
public static String digits(String s) {
|
||||
if (s == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
if (c >= '0' && c <= '9') {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user