feat(paymentcryptography): the modes and the keyed hash the reference names (#8984)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-19 13:33:35 -04:00
1 parent 66dbdd2935
commit 09125016fe
12 files changed
+1272 -148

No files matched your search

@@ -1,6 +1,7 @@
package io.floci.aws.services.paymentcryptography;
import io.floci.aws.services.paymentcryptography.crypto.BlockMode;
import io.floci.aws.services.paymentcryptography.crypto.Bytes;
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
@@ -26,6 +27,9 @@ final class PaymentCryptographyCrypto {
private static final byte[] ZERO_BLOCK = new byte[16];
/** The message the check value of a keyed hash key is taken over: none at all. */
private static final byte[] EMPTY_MESSAGE = new byte[0];
/** The hexadecimal the key material is written in. */
private static final HexFormat HEX = HexFormat.of();
@@ -70,22 +74,45 @@ final class PaymentCryptographyCrypto {
*/
static String checkValue(String keyHex, PaymentCryptographyKeyAlgorithm algorithm) {
byte[] key = fromHex(keyHex);
byte[] mac = algorithm.aes
? cmac(key, ZERO_BLOCK)
: tdesEcbEncrypt(new byte[8], key);
return HEX_UPPER.formatHex(checkValueBytes(key, algorithm));
}
/**
* The check value of a key of that algorithm, from the key's bytes.
*
* <p>The value is the leftmost three bytes of the mac the reference's terminology names
* for the key's family: the CMAC of sixteen zero bytes under an AES key, the ANSI X9.24
* value of eight zero bytes under a Triple DES one, and the keyed hash of a zero-length
* message under a keyed hash key, whose kind of check value the reference's model names
* as the hash.
*/
static byte[] checkValueBytes(byte[] key, PaymentCryptographyKeyAlgorithm algorithm) {
byte[] mac = macForCheckValue(key, algorithm);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return HEX_UPPER.formatHex(value);
return value;
}
/**
* The mac the check value of a key is taken from.
*
* <p>The reference's terminology names the message each family's check value is taken
* over: sixteen zero bytes for the CMAC of an AES key, eight zero bytes for the ANSI
* X9.24 value of a Triple DES one, and a zero-length message for the keyed hash of a
* keyed hash key.
*/
private static byte[] macForCheckValue(byte[] key, PaymentCryptographyKeyAlgorithm algorithm) {
if (algorithm.hmac()) {
return Ciphers.hmac(key, EMPTY_MESSAGE, Ciphers.digestOf(algorithm.hash));
}
return algorithm.aes
? cmac(key, ZERO_BLOCK)
: tdesEcbEncrypt(new byte[8], key);
}
/** The check value of a key of that algorithm, from the key's bytes. */
static String checkValue(byte[] key, PaymentCryptographyKeyAlgorithm algorithm) {
byte[] mac = algorithm.aes
? cmac(key, ZERO_BLOCK)
: tdesEcbEncrypt(new byte[8], key);
byte[] value = new byte[3];
System.arraycopy(mac, 0, value, 0, 3);
return HEX_UPPER.formatHex(value);
return HEX_UPPER.formatHex(checkValueBytes(key, algorithm));
}
/** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
@@ -186,6 +213,55 @@ final class PaymentCryptographyCrypto {
return out;
}
/**
* The ciphertext of a plaintext under a key, in the chaining mode.
*
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @return the encrypted bytes
*/
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector) {
return encrypt(key, plaintext, initializationVector, BlockMode.CBC);
}
/**
* The plaintext of a ciphertext the service encrypted, in the chaining mode.
*
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @return the plaintext
*/
static byte[] decryptCbc(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return decrypt(key, ciphertext, initializationVector, BlockMode.CBC);
}
/**
* The ciphertext of a plaintext under a Triple DES key, in the chaining mode.
*
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @return the encrypted bytes
*/
static byte[] tdesCbcEncrypt(byte[] key, byte[] plaintext, byte[] initializationVector) {
return tdesEncrypt(key, plaintext, initializationVector, BlockMode.CBC);
}
/**
* The plaintext of a ciphertext the service encrypted under a Triple DES key, in the
* chaining mode.
*
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @return the plaintext
*/
static byte[] tdesCbcDecrypt(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return tdesDecrypt(key, ciphertext, initializationVector, BlockMode.CBC);
}
/**
* The ciphertext of a plaintext under a key, with the initialization vector the request
* names.
@@ -197,10 +273,13 @@ final class PaymentCryptographyCrypto {
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @param mode the block cipher mode the request names
* @return the encrypted bytes
*/
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector) {
return aesCbcEncrypt(key, vector(initializationVector, IV_LENGTH), plaintext);
static byte[] encrypt(byte[] key, byte[] plaintext, byte[] initializationVector,
BlockMode mode) {
return Ciphers.aesEncrypt(plaintext, key,
vector(initializationVector, IV_LENGTH, mode), mode);
}
/**
@@ -213,10 +292,13 @@ final class PaymentCryptographyCrypto {
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @param mode the block cipher mode the request names
* @return the plaintext
*/
static byte[] decryptCbc(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return aesCbcDecrypt(key, vector(initializationVector, IV_LENGTH), ciphertext);
static byte[] decrypt(byte[] key, byte[] ciphertext, byte[] initializationVector,
BlockMode mode) {
return Ciphers.aesDecrypt(ciphertext, key,
vector(initializationVector, IV_LENGTH, mode), mode);
}
/**
@@ -230,10 +312,13 @@ final class PaymentCryptographyCrypto {
* @param key the key
* @param plaintext the bytes to encrypt
* @param initializationVector the vector to encrypt under, or null for the zero vector
* @param mode the block cipher mode the request names
* @return the encrypted bytes
*/
static byte[] tdesCbcEncrypt(byte[] key, byte[] plaintext, byte[] initializationVector) {
return Ciphers.tdesCbcEncrypt(plaintext, key, vector(initializationVector, TDES_IV_LENGTH));
static byte[] tdesEncrypt(byte[] key, byte[] plaintext, byte[] initializationVector,
BlockMode mode) {
return Ciphers.tdesEncrypt(plaintext, key,
vector(initializationVector, TDES_IV_LENGTH, mode), mode);
}
/**
@@ -242,14 +327,38 @@ final class PaymentCryptographyCrypto {
* @param key the key
* @param ciphertext the encrypted bytes
* @param initializationVector the vector to decrypt under, or null for the zero vector
* @param mode the block cipher mode the request names
* @return the plaintext
*/
static byte[] tdesCbcDecrypt(byte[] key, byte[] ciphertext, byte[] initializationVector) {
return Ciphers.tdesCbcDecrypt(ciphertext, key, vector(initializationVector, TDES_IV_LENGTH));
static byte[] tdesDecrypt(byte[] key, byte[] ciphertext, byte[] initializationVector,
BlockMode mode) {
return Ciphers.tdesDecrypt(ciphertext, key,
vector(initializationVector, TDES_IV_LENGTH, mode), mode);
}
/**
* The AES encryption of data under a key and an initialization vector, without
* padding: the vector is the length of the data's block size already.
*/
static byte[] aesCbcEncrypt(byte[] key, byte[] iv, byte[] data) {
return Ciphers.aesCbcEncrypt(data, key, iv);
}
/** The AES-CBC decryption of data under a key and an initialization vector, without padding. */
static byte[] aesCbcDecrypt(byte[] key, byte[] iv, byte[] data) {
try {
return Ciphers.aesCbcDecrypt(data, key, iv);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("the data did not decrypt under the key", e);
}
}
/** The vector a cipher starts from, the zero vector when the request names none. */
private static byte[] vector(byte[] initializationVector, int length) {
private static byte[] vector(byte[] initializationVector, int length, BlockMode mode) {
if (!mode.takesVector()) {
// The mode enciphers every block on its own, so it has no vector to start from.
return null;
}
if (initializationVector == null) {
return new byte[length];
}
@@ -260,6 +369,11 @@ final class PaymentCryptographyCrypto {
return initializationVector.clone();
}
/** The vector a cipher starts from, the zero vector when the request names none. */
private static byte[] vector(byte[] initializationVector, int length) {
return vector(initializationVector, length, BlockMode.CBC);
}
/**
* The key wrap of RFC 3394: a plaintext wrapped under a key, with the check that says the
* key was the right one.
@@ -330,23 +444,6 @@ final class PaymentCryptographyCrypto {
return out;
}
/**
* The AES-CBC encryption of data under a key and an initialization vector, without
* padding: the vector is the length of the data's block size already.
*/
static byte[] aesCbcEncrypt(byte[] key, byte[] iv, byte[] data) {
return Ciphers.aesCbcEncrypt(data, key, iv);
}
/** The AES-CBC decryption of data under a key and an initialization vector, without padding. */
static byte[] aesCbcDecrypt(byte[] key, byte[] iv, byte[] data) {
try {
return Ciphers.aesCbcDecrypt(data, key, iv);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("the data did not decrypt under the key", e);
}
}
/** One block of AES in ECB mode. */
static byte[] aesEcbEncrypt(byte[] input, byte[] key) {
return Ciphers.aesEcbEncrypt(input, key);
@@ -2,11 +2,13 @@ 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.BlockMode;
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.bouncycastle.crypto.Digest;
import java.security.MessageDigest;
import java.util.HexFormat;
@@ -94,9 +96,10 @@ public class PaymentCryptographyCryptoHandler {
requireCipherFamily(key, "encrypt");
requireUsage(key, DATA_ENCRYPTION_USAGES, "encrypt data");
byte[] plaintext = blob(request, "PlainText");
requireModeOfCipher(encryption, key, "encrypting");
requireBlockAligned(plaintext, key, "PlainText");
byte[] ciphertext = encrypt(material(key), plaintext,
initializationVector(encryption, key, "encrypting"), key);
initializationVector(encryption, key, "encrypting"), encryption.mode(), key);
return answer(key, Map.of("CipherText", encode(ciphertext)));
}
@@ -113,9 +116,10 @@ public class PaymentCryptographyCryptoHandler {
requireCipherFamily(key, "decrypt");
requireUsage(key, DATA_ENCRYPTION_USAGES, "decrypt data");
byte[] ciphertext = blob(request, "CipherText");
requireModeOfCipher(encryption, key, "decrypting");
requireBlockAligned(ciphertext, key, "CipherText");
byte[] plaintext = decrypt(material(key), ciphertext,
initializationVector(encryption, key, "decrypting"), key);
initializationVector(encryption, key, "decrypting"), encryption.mode(), key);
return answer(key, Map.of("PlainText", encode(plaintext)));
}
@@ -140,12 +144,16 @@ public class PaymentCryptographyCryptoHandler {
requireUsage(incoming, DATA_ENCRYPTION_USAGES, "decrypt data");
requireUsage(outgoing, DATA_ENCRYPTION_USAGES, "encrypt data");
byte[] ciphertext = blob(request, "CipherText");
requireModeOfCipher(incomingEncryption, incoming, "decrypting");
requireModeOfCipher(outgoingEncryption, outgoing, "encrypting");
requireBlockAligned(ciphertext, incoming, "CipherText");
byte[] plaintext = decrypt(material(incoming), ciphertext,
initializationVector(incomingEncryption, incoming, "decrypting"), incoming);
initializationVector(incomingEncryption, incoming, "decrypting"),
incomingEncryption.mode(), incoming);
requireBlockAligned(plaintext, outgoing, "the plaintext");
byte[] reEncrypted = encrypt(material(outgoing), plaintext,
initializationVector(outgoingEncryption, outgoing, "encrypting"), outgoing);
initializationVector(outgoingEncryption, outgoing, "encrypting"),
outgoingEncryption.mode(), outgoing);
return answer(outgoing, Map.of("CipherText", encode(reEncrypted)));
}
@@ -157,7 +165,7 @@ public class PaymentCryptographyCryptoHandler {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("GenerateMac", request);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
MacLeg leg = resolveMacLeg(request.get("GenerationAttributes"), key, region, "Generate",
MacLeg leg = resolveMacLeg(request.get("GenerationAttributes"), key, "Generate",
"generating a MAC with");
byte[] message = blob(request, "MessageData");
int length = macLength(request, leg, leg.longest);
@@ -174,7 +182,7 @@ public class PaymentCryptographyCryptoHandler {
// The request is checked against the constraints the model states for it.
PaymentCryptographyDataRequestShapes.check("VerifyMac", request);
PaymentCryptographyKey key = requiredKey(request, region, "KeyIdentifier");
MacLeg leg = resolveMacLeg(request.get("VerificationAttributes"), key, region, "Verify",
MacLeg leg = resolveMacLeg(request.get("VerificationAttributes"), key, "Verify",
"verifying a MAC with");
byte[] message = blob(request, "MessageData");
byte[] mac = blob(request, "Mac");
@@ -242,8 +250,7 @@ public class PaymentCryptographyCryptoHandler {
* The cipher the request asks for.
*
* <p>The attributes name the mode and, for a symmetric cipher, the initialization vector.
* The service encrypts in CBC mode, so a request that names another mode is refused
* rather than answered with a cipher it did not ask for.
* The reference names eight modes, and this service makes them all.
*
* @param attributes the attributes of the request, which may be absent
* @return the cipher the request asks for
@@ -264,11 +271,13 @@ public class PaymentCryptographyCryptoHandler {
+ "(Symmetric)", 400);
}
JsonNode symmetric = attributes.get(variant);
String mode = symmetric == null ? "" : symmetric.path("Mode").asText();
if (!"CBC".equals(mode)) {
String modeName = symmetric == null ? "" : symmetric.path("Mode").asText();
BlockMode mode = BlockMode.from(modeName);
if (mode == null) {
throw new AwsException("ValidationException",
"the encryption mode '" + (mode.isEmpty() ? "(missing)" : mode)
+ "' is not supported by this service (CBC)", 400);
"the encryption mode '" + (modeName.isEmpty() ? "(missing)" : modeName)
+ "' is not supported by this service (" + BlockMode.supported() + ")",
400);
}
if (symmetric != null && symmetric.hasNonNull("PaddingType")) {
throw new AwsException("ValidationException",
@@ -282,7 +291,7 @@ public class PaymentCryptographyCryptoHandler {
iv = HexFormat.of().parseHex(hex);
}
}
return new Encryption(iv);
return new Encryption(mode, iv);
}
/**
@@ -300,6 +309,10 @@ public class PaymentCryptographyCryptoHandler {
*/
private static byte[] initializationVector(Encryption encryption, PaymentCryptographyKey key,
String what) {
if (!encryption.mode().takesVector()) {
// The mode enciphers every block on its own, so it has no vector to start from.
return null;
}
byte[] iv = encryption.initializationVector();
if (iv == null) {
return null;
@@ -313,6 +326,30 @@ public class PaymentCryptographyCryptoHandler {
return iv;
}
/**
* The mode the request names, when the cipher the key's algorithm gives it can take it.
*
* <p>The feedback of the feedback modes is as wide as the cipher's own block at the
* widest, so a request that asks a Triple DES key for the mode whose feedback is a
* hundred and twenty-eight bits is refused here, where the caller can act on it, and
* not by the cipher, where it would be a server error.
*
* @param encryption the attributes of the request
* @param key the key the cipher runs under
* @param what the operation that is refused, for the message
*/
private static void requireModeOfCipher(Encryption encryption, PaymentCryptographyKey key,
String what) {
int block = isAes(key) ? 16 : 8;
int feedback = encryption.mode().feedbackBits(block * 8);
if (feedback > block * 8) {
throw new AwsException("ValidationException",
"the encryption mode " + encryption.mode() + " is not a mode " + what
+ " under a " + (isAes(key) ? "AES" : "Triple DES") + " key takes",
400);
}
}
/**
* The family a key's algorithm belongs to.
*
@@ -342,10 +379,10 @@ public class PaymentCryptographyCryptoHandler {
* @return the encrypted bytes
*/
private byte[] encrypt(byte[] key, byte[] plaintext, byte[] initializationVector,
PaymentCryptographyKey record) {
BlockMode mode, PaymentCryptographyKey record) {
return isAes(record)
? PaymentCryptographyCrypto.encryptCbc(key, plaintext, initializationVector)
: PaymentCryptographyCrypto.tdesCbcEncrypt(key, plaintext, initializationVector);
? PaymentCryptographyCrypto.encrypt(key, plaintext, initializationVector, mode)
: PaymentCryptographyCrypto.tdesEncrypt(key, plaintext, initializationVector, mode);
}
/**
@@ -358,14 +395,14 @@ public class PaymentCryptographyCryptoHandler {
* @return the plaintext
*/
private static byte[] decrypt(byte[] key, byte[] ciphertext, byte[] initializationVector,
PaymentCryptographyKey record) {
BlockMode mode, PaymentCryptographyKey record) {
return isAes(record)
? PaymentCryptographyCrypto.decryptCbc(key, ciphertext, initializationVector)
: PaymentCryptographyCrypto.tdesCbcDecrypt(key, ciphertext, initializationVector);
? PaymentCryptographyCrypto.decrypt(key, ciphertext, initializationVector, mode)
: PaymentCryptographyCrypto.tdesDecrypt(key, ciphertext, initializationVector, mode);
}
/** The cipher a request asks for. */
private record Encryption(byte[] initializationVector) {
private record Encryption(BlockMode mode, byte[] initializationVector) {
}
/** The key the request names, in the member the operation names it in. */
@@ -414,6 +451,57 @@ public class PaymentCryptographyCryptoHandler {
}
}
/**
* The keyed hash leg of a MAC request.
*
* <p>The reference's guide settles the two forms the request takes: "Because the key
* algorithm is an HMAC algorithm, set {@code Algorithm} to {@code HMAC}, and the key
* sets the hash", and "Use {@code HMAC_SHA224}, {@code HMAC_SHA256},
* {@code HMAC_SHA384}, or {@code HMAC_SHA512} only with a TDES or AES key that has
* KeyUsage set to {@code TR31_M7_HMAC_KEY}". So a key that carries a hash is asked for
* by name, and a key of the hash usage that does not carry one is asked for by the hash
* the request names.
*
* @param algorithm the algorithm the request names
* @param key the key the mac is computed under
* @param mode the mode of use the operation needs
* @param what the operation, for the message
* @return the leg of the request
*/
private MacLeg hmacLeg(String algorithm, PaymentCryptographyKey key, String mode, String what) {
requireMode(key, mode, what);
requireUsage(key, MAC_USAGES, what);
PaymentCryptographyKeyAlgorithm keyAlgorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
if (keyAlgorithm == null) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is of the algorithm " + key.getKeyAlgorithm()
+ ", which this service does not make", 400);
}
// The hash the mac is computed with: the one the key carries, or the one the
// request names.
String hash = keyAlgorithm.hmac() ? keyAlgorithm.hash : null;
if ("HMAC".equals(algorithm)) {
if (hash == null) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " does not carry a hash, so the request has "
+ "to name one (HMAC_SHA224, HMAC_SHA256, HMAC_SHA384 or "
+ "HMAC_SHA512)", 400);
}
} else {
hash = algorithm.substring("HMAC_".length());
if (keyAlgorithm.hmac() && !keyAlgorithm.hash.equals(hash)) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " carries the hash " + keyAlgorithm.hash
+ ", and the request asks for the " + hash, 400);
}
}
Digest digest = Ciphers.digestOf(hash);
int size = digest.getDigestSize();
return new MacLeg((keyBytes, message) -> Ciphers.hmac(keyBytes, message, digest),
material(key), size, true);
}
/**
* The MAC a request asks for, and the key it is computed under.
*
@@ -422,8 +510,8 @@ public class PaymentCryptographyCryptoHandler {
* variants. A DUKPT MAC key is derived from the base derivation key, so that is what the
* key has to allow.
*/
private MacLeg resolveMacLeg(JsonNode attributes, PaymentCryptographyKey key, String region,
String mode, String what) {
private MacLeg resolveMacLeg(JsonNode attributes, PaymentCryptographyKey key, String mode,
String what) {
String variant = soleVariant(attributes);
if (variant == null) {
throw new AwsException("ValidationException",
@@ -445,6 +533,9 @@ public class PaymentCryptographyCryptoHandler {
requireFamily(key, false, what);
return new MacLeg(Ciphers::iso9797Alg3, material(key), LONGEST_MAC);
}
if (algorithm.startsWith("HMAC")) {
return hmacLeg(algorithm, key, mode, what);
}
if ("CMAC".equals(algorithm)) {
// The CMAC is the AES-CMAC of RFC 4493, which is a whole block
// wide, so it is cut to a length the caller asks for.
@@ -456,7 +547,8 @@ public class PaymentCryptographyCryptoHandler {
}
throw new AwsException("ValidationException",
"Algorithm '" + algorithm + "' not supported by this service "
+ "(ISO9797_ALGORITHM1, ISO9797_ALGORITHM3, CMAC)", 400);
+ "(ISO9797_ALGORITHM1, ISO9797_ALGORITHM3, CMAC, HMAC, "
+ "HMAC_SHA224, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512)", 400);
}
if ("DukptIso9797Algorithm1".equals(variant) || "DukptIso9797Algorithm3".equals(variant)) {
// A DUKPT MAC key is derived from the base derivation key, so that is what the key
@@ -502,11 +594,18 @@ public class PaymentCryptographyCryptoHandler {
final byte[] keyBytes;
/** The longest MAC this algorithm gives, in bytes. */
final int longest;
/** Whether the length the request asks for is ignored, as it is for the keyed hash. */
final boolean ignoresLength;
MacLeg(MacFunction mac, byte[] keyBytes, int longest) {
this(mac, keyBytes, longest, false);
}
MacLeg(MacFunction mac, byte[] keyBytes, int longest, boolean ignoresLength) {
this.mac = mac;
this.keyBytes = keyBytes;
this.longest = longest;
this.ignoresLength = ignoresLength;
}
}
@@ -527,19 +626,49 @@ public class PaymentCryptographyCryptoHandler {
}
/**
* The length of the MAC the caller asks for, which the service computes.
* The length of the MAC the caller asks for, which the service computes, in bytes.
*
* <p>The model says the length is a whole number of at least four bytes, and the
* request has been checked against it. What the algorithm gives is shorter than the
* model allows, so a length above it is refused here.
* <p>The reference counts the length in hexadecimal characters: "The unit of mac-length
* depends on the MAC algorithm: ISO 9797-1, CMAC, AS2805, and DUKPT – number of hex
* characters. For example, a length of 8 refers to 8 hex characters (4 bytes)". The
* reference names the lengths that hold for each algorithm: eight or sixteen characters
* for the Triple DES macs, and eight, sixteen or thirty-two for the cmac of an aes key,
* so the length is a whole number of four, eight or sixteen bytes and no longer than
* what the algorithm gives.
*
* <p>The keyed hash ignores the length: "The mac-length parameter has no effect for
* HMAC. The output MAC is always the full hash output".
*
* @param request the request, whose MacLength member may be absent
* @param leg the algorithm the mac is computed with
* @param fallback the length to use when the request names none
* @return the length of the mac, in bytes
*/
private static int macLength(JsonNode request, MacLeg leg, int fallback) {
int length = request.path("MacLength").asInt(fallback);
if (length < SHORTEST_MAC || length > leg.longest) {
throw new AwsException("ValidationException",
"MacLength must be between " + SHORTEST_MAC + " and " + leg.longest, 400);
JsonNode declared = request.get("MacLength");
if (declared == null || declared.isNull() || leg.ignoresLength) {
return fallback;
}
return length;
int characters = declared.asInt(-1);
if (characters < 0) {
throw new AwsException("ValidationException", "MacLength must be a number", 400);
}
if (characters % 2 != 0) {
throw new AwsException("ValidationException",
"MacLength is a number of hexadecimal characters, so it is a whole number "
+ "of bytes", 400);
}
int bytes = characters / 2;
if (bytes < SHORTEST_MAC || bytes > leg.longest) {
throw new AwsException("ValidationException",
"MacLength must be between " + (SHORTEST_MAC * 2) + " and "
+ (leg.longest * 2) + " hexadecimal characters", 400);
}
if (bytes != 4 && bytes != 8 && bytes != 16) {
throw new AwsException("ValidationException",
"MacLength must be 8, 16 or 32 hexadecimal characters", 400);
}
return bytes;
}
/** A blob as the protocol carries it: hexadecimal. */
@@ -19,6 +19,20 @@ enum PaymentCryptographyKeyAlgorithm {
AES_128(16, true, false, false),
AES_192(24, true, false, false),
AES_256(32, true, false, false),
/**
* A keyed hash key of SHA-224.
*
* <p>The reference names these four algorithms for the hash based message
* authentication code, and the hash a key carries is fixed at its creation, so the
* algorithm is the hash. The length is the length of the hash's own output.
*/
HMAC_SHA224(28, false, false, false, "SHA-224"),
/** A keyed hash key of SHA-256. */
HMAC_SHA256(32, false, false, false, "SHA-256"),
/** A keyed hash key of SHA-384. */
HMAC_SHA384(48, false, false, false, "SHA-384"),
/** A keyed hash key of SHA-512. */
HMAC_SHA512(64, false, false, false, "SHA-512"),
/**
* An EC key agreement key on NIST P-256, the curve the cardholder-device flow uses.
* The length is the size of the curve, not of a key block.
@@ -52,11 +66,28 @@ enum PaymentCryptographyKeyAlgorithm {
/** Whether the key is an RSA key, which has a key pair and no symmetric material. */
final boolean rsa;
/** The hash the key carries, for a keyed hash key, and null for the others. */
final String hash;
PaymentCryptographyKeyAlgorithm(int bytes, boolean aes, boolean ecc, boolean rsa) {
this(bytes, aes, ecc, rsa, null);
}
PaymentCryptographyKeyAlgorithm(int bytes, boolean aes, boolean ecc, boolean rsa, String hash) {
this.bytes = bytes;
this.aes = aes;
this.ecc = ecc;
this.rsa = rsa;
this.hash = hash;
}
/**
* Whether the key is a keyed hash key, whose algorithm is the hash it carries.
*
* @return whether the key is a keyed hash key
*/
boolean hmac() {
return hash != null;
}
/** Whether the key holds material a symmetric cipher can use. */
@@ -75,6 +106,11 @@ enum PaymentCryptographyKeyAlgorithm {
* never refused for a kind the service would have answered with.
*/
String checkValueAlgorithm() {
if (hmac()) {
// The reference's model names the hash as a kind of check value, so the value of
// a keyed hash key is computed with the hash the key carries.
return "HMAC";
}
return aes ? "CMAC" : "ANSI_X9_24";
}
@@ -92,10 +128,10 @@ enum PaymentCryptographyKeyAlgorithm {
* Whether the key is a Triple DES key rather than an AES one.
*
* <p>A symmetric key is an AES one or a Triple DES one, so the family follows from the
* two.
* two. A keyed hash key is neither: the hash is what runs under it.
*/
boolean isTdes() {
return symmetric() && !aes;
return symmetric() && !aes && !hmac();
}
/** Whether the key is an EC key, which has a key pair rather than key material. */
@@ -148,6 +184,9 @@ enum PaymentCryptographyKeyAlgorithm {
return sb.toString();
}
/** The usage of the keyed hash keys. */
static final String HMAC_USAGE = "TR31_M7_HMAC_KEY";
/** The usages a key pair is made of, and the symmetric ones are the rest. */
private static final List<String> ASYMMETRIC_USAGES = List.of(
"TR31_D1_ASYMMETRIC_KEY_FOR_DATA_ENCRYPTION",
@@ -178,7 +217,15 @@ enum PaymentCryptographyKeyAlgorithm {
// The ISO 9797 MACs are defined over Triple DES.
return List.of(TDES_2KEY, TDES_3KEY);
}
// Every other usage takes every symmetric algorithm.
if (HMAC_USAGE.equals(usage)) {
// The reference's guide: the hash usage takes the keyed hash keys, whose
// algorithm is the hash they carry, and the Triple DES and AES keys a request
// may ask for a hash of by name.
return List.of(TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256,
HMAC_SHA224, HMAC_SHA256, HMAC_SHA384, HMAC_SHA512);
}
// Every other usage takes every symmetric algorithm but the keyed hash ones, which
// are for the hash usage alone.
return List.of(TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256);
}
@@ -0,0 +1,128 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.modes.OFBBlockCipher;
/**
* The block cipher modes the reference names for the symmetric encryption.
*
* <p>The reference's model names eight of them: the ECB, the CBC, the CFB, the CFB1, the
* CFB8, the CFB64, the CFB128 and the OFB. The CFB with no number is the one whose
* feedback is the cipher's own block, so it is the CFB128 over AES and the CFB64 over
* Triple DES, and the numbered ones are the ones whose feedback is that many bits.
*
* <p>BouncyCastle's modes are the ones that run: the ECB, the CBC, the CFB and the OFB. Its
* CFB takes a feedback of whole bytes, so the CFB8 and the CFB64 are its own, and the CFB1,
* whose feedback is a single bit, is {@link Cfb1}.
*/
public enum BlockMode {
/** The cipher's own mode: every block is enciphered on its own. */
ECB,
/** The chaining mode: every block is enciphered under the previous one. */
CBC,
/** The feedback mode over the cipher's own block. */
CFB,
/** The feedback mode over a single bit. */
CFB1,
/** The feedback mode over eight bits. */
CFB8,
/** The feedback mode over sixty-four bits. */
CFB64,
/** The feedback mode over a hundred and twenty-eight bits. */
CFB128,
/** The output feedback mode: every block is enciphered under the vector and the vector
* becomes the enciphered block. */
OFB;
/**
* The mode a name in the request names.
*
* @param wireName the name the request carries
* @return the mode, or null when the name is one this service does not make
*/
public static BlockMode from(String wireName) {
if (wireName == null) {
return null;
}
for (BlockMode mode : values()) {
if (mode.name().equals(wireName)) {
return mode;
}
}
return null;
}
/**
* The names of the modes, for a message that names the ones this service makes.
*
* @return the names, separated by commas
*/
public static String supported() {
StringBuilder sb = new StringBuilder();
for (BlockMode mode : values()) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append(mode.name());
}
return sb.toString();
}
/**
* Whether the mode takes an initialization vector.
*
* <p>The ECB mode enciphers every block on its own, so it has nowhere to put one.
*
* @return whether the mode takes a vector
*/
public boolean takesVector() {
return this != ECB;
}
/**
* The width of the feedback the mode names, in bits.
*
* @param blockBits the width of the cipher's own block, in bits
* @return the feedback width, or zero for a mode that has no feedback
*/
public int feedbackBits(int blockBits) {
return switch (this) {
case CFB -> blockBits;
case CFB1 -> 1;
case CFB8 -> 8;
case CFB64 -> 64;
case CFB128 -> 128;
default -> 0;
};
}
/**
* The cipher of the mode, over the given engine.
*
* @param engine the cipher the mode runs over
* @return the mode's cipher
*/
BlockCipher cipher(BlockCipher engine) {
return switch (this) {
// The cipher's own mode is the cipher itself: there is nothing to wrap it in.
case ECB -> engine;
case CBC -> new CBCBlockCipher(engine);
case CFB -> new CFBBlockCipher(engine, engine.getBlockSize() * 8);
case CFB8 -> new CFBBlockCipher(engine, 8);
case CFB64 -> new CFBBlockCipher(engine, 64);
case CFB128 -> new CFBBlockCipher(engine, 128);
case OFB -> new OFBBlockCipher(engine, engine.getBlockSize() * 8);
case CFB1 -> new Cfb1(engine);
};
}
}
@@ -0,0 +1,127 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.util.Arrays;
/**
* The cipher feedback mode over a single bit.
*
* <p>The standard's feedback mode takes a segment of so many bits, and the register that
* feeds the cipher back is shifted by the segment and takes the cipher text of the segment
* in. A segment of one bit is a bit at a time, so the register is shifted once per bit and
* the cipher is run once per bit, which is why the mode is not one anybody uses often.
*
* <p>BouncyCastle's feedback mode takes a segment of whole bytes, so the one bit segment is
* this class. The construction is the standard's: the cipher text bit of a bit is the
* plain text bit exclusive-ored with the first bit of the enciphered register, and the
* register is shifted left by one bit and takes that cipher text bit in.
*/
final class Cfb1 extends StreamBlockCipher {
/** The cipher the feedback runs over. */
private final BlockCipher cipher;
/** The shift register the cipher text is fed back into. */
private final byte[] register;
/** The enciphered register, whose first bit is the key bit of the bit. */
private final byte[] keystream;
/** Whether the mode enciphers or deciphers. */
private boolean encrypting;
Cfb1(BlockCipher cipher) {
super(cipher);
this.cipher = cipher;
this.register = new byte[cipher.getBlockSize()];
this.keystream = new byte[cipher.getBlockSize()];
}
@Override
public int getBlockSize() {
return cipher.getBlockSize();
}
@Override
public String getAlgorithmName() {
return "CFB1";
}
@Override
public void init(boolean forEncryption, CipherParameters params) {
this.encrypting = forEncryption;
CipherParameters key = params;
byte[] iv = null;
if (params instanceof ParametersWithIV withIv) {
key = withIv.getParameters();
iv = withIv.getIV();
}
// The register is always enciphered, in both directions: the key stream of the mode
// is the enciphered register, and the data's own direction is this class's business.
cipher.init(true, key);
Arrays.fill(register, (byte) 0); if (iv != null) {
System.arraycopy(iv, 0, register, 0, iv.length);
}
}
@Override
public int processBlock(byte[] in, int inOff, byte[] out, int outOff) {
int count = getBlockSize();
for (int i = 0; i < count; i++) {
out[outOff + i] = calculateByte(in[inOff + i]);
}
return count;
}
@Override
public void reset() {
Arrays.fill(register, (byte) 0);
}
/**
* The byte the mode enciphers or deciphers.
*
* <p>The feedback is a bit, so the byte is taken a bit at a time: the cipher runs over
* the register once per bit, and the register is shifted and fed with the cipher text
* bit once per bit.
*
* @param in the byte to encipher or decipher
* @return the byte the mode makes of it
*/
@Override
protected byte calculateByte(byte in) {
int input = in & 0xff;
int out = 0;
for (int bit = 7; bit >= 0; bit--) {
// The key bit of the bit is the first bit of the enciphered register.
cipher.processBlock(register, 0, keystream, 0);
int keyBit = (keystream[0] & 0x80) != 0 ? 1 : 0;
int inputBit = (input & (1 << bit)) != 0 ? 1 : 0;
// The cipher text bit is the plain text bit under the key bit, and the register
// is fed with the cipher text bit, which the cipher text carries in both ways.
int cipherBit = encrypting ? inputBit ^ keyBit : inputBit;
int plainBit = encrypting ? inputBit : cipherBit ^ keyBit;
out |= (encrypting ? cipherBit : plainBit) << bit;
// The register is shifted left by one bit and takes the cipher text bit in.
shift(register);
register[register.length - 1] |= (byte) cipherBit;
}
return (byte) out;
}
/**
* A register shifted left by one bit, whose top bit falls off.
*
* @param register the register to shift
*/
private static void shift(byte[] register) {
for (int i = 0; i < register.length - 1; i++) {
register[i] = (byte) ((register[i] << 1) | ((register[i + 1] & 0x80) >> 7));
}
register[register.length - 1] = (byte) (register[register.length - 1] << 1);
}
}
@@ -1,10 +1,17 @@
package io.floci.aws.services.paymentcryptography.crypto;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.StreamBlockCipher;
import org.bouncycastle.crypto.digests.SHA224Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.digests.SHA384Digest;
import org.bouncycastle.crypto.digests.SHA512Digest;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.engines.DESEngine;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.macs.CBCBlockCipherMac;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.macs.ISO9797Alg3Mac;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
@@ -204,6 +211,134 @@ public final class Ciphers {
return blocks(new DESedeEngine(), false, data, key, iv8);
}
/**
* The AES encryption of data under a key, in the mode the request names.
*
* <p>The cipher pads no data, so the caller supplies whole blocks.
*
* @param data the bytes to encrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @param iv the initialization vector, or null for the mode that takes none
* @param mode the block cipher mode
* @return the encrypted bytes
*/
public static byte[] aesEncrypt(byte[] data, byte[] key, byte[] iv, BlockMode mode) {
return crypt(AESEngine.newInstance(), true, data, key, iv, mode);
}
/**
* The AES decryption of data under a key, in the mode the request names.
*
* @param data the bytes to decrypt
* @param key the sixteen-, twenty-four- or thirty-two-byte key
* @param iv the initialization vector, or null for the mode that takes none
* @param mode the block cipher mode
* @return the decrypted bytes
*/
public static byte[] aesDecrypt(byte[] data, byte[] key, byte[] iv, BlockMode mode) {
return crypt(AESEngine.newInstance(), false, data, key, iv, mode);
}
/**
* The Triple DES encryption of data under a key, in the mode the request names.
*
* <p>The two-key form is K1||K2, and the cipher takes three keys, so it is widened to
* K1||K2||K1, which is what the two-key form means. A three-key key is taken as it is.
*
* @param data the bytes to encrypt
* @param key the sixteen- or twenty-four-byte key
* @param iv the initialization vector, or null for the mode that takes none
* @param mode the block cipher mode
* @return the encrypted bytes
*/
public static byte[] tdesEncrypt(byte[] data, byte[] key, byte[] iv, BlockMode mode) {
return crypt(new DESedeEngine(), true, data, key, iv, mode);
}
/**
* The Triple DES decryption of data under a key, in the mode the request names.
*
* @param data the bytes to decrypt
* @param key the sixteen- or twenty-four-byte key
* @param iv the initialization vector, or null for the mode that takes none
* @param mode the block cipher mode
* @return the decrypted bytes
*/
public static byte[] tdesDecrypt(byte[] data, byte[] key, byte[] iv, BlockMode mode) {
return crypt(new DESedeEngine(), false, data, key, iv, mode);
}
/**
* The keyed hash of a message, as RFC 2104 computes it.
*
* <p>The hash of the key and the hash of the message are combined twice, so the result
* is as long as the hash's own output.
*
* @param key the key of the hash
* @param data the message to authenticate
* @param digest the hash the message is authenticated with
* @return the hash of the message
*/
public static byte[] hmac(byte[] key, byte[] data, Digest digest) {
HMac mac = new HMac(digest);
mac.init(new KeyParameter(key));
mac.update(data, 0, data.length);
byte[] out = new byte[mac.getMacSize()];
mac.doFinal(out, 0);
return out;
}
/** The hash of a name the reference gives a hash by. */
public static Digest digestOf(String name) {
return switch (name) {
case "SHA-224" -> new SHA224Digest();
case "SHA-256" -> new SHA256Digest();
case "SHA-384" -> new SHA384Digest();
case "SHA-512" -> new SHA512Digest();
default -> throw new IllegalArgumentException("the hash " + name + " is not one "
+ "this service makes");
};
}
/**
* The encryption or decryption of data under a key, in the mode the request names.
*
* <p>The mode that chains the blocks and the mode that feeds a block back are the block
* ciphers, and the modes that run as a stream take the data as it comes.
*/
private static byte[] crypt(BlockCipher engine, boolean encrypt, byte[] data, byte[] key,
byte[] iv, BlockMode mode) {
int size = engine.getBlockSize();
if (data == null) {
throw new IllegalArgumentException("the data is missing");
}
if (key == null) {
throw new IllegalArgumentException("key is required");
}
if (mode.takesVector() && (iv == null || iv.length != size)) {
throw new IllegalArgumentException("the initialization vector is "
+ (iv == null ? "missing" : iv.length + " bytes") + "; it is " + size);
}
int feedback = mode.feedbackBits(size * 8);
if (feedback > size * 8) {
throw new IllegalArgumentException(mode.name() + " is not a mode a " + size
+ "-byte block cipher takes");
}
BlockCipher cipher = mode.cipher(engine);
cipher.init(encrypt, mode.takesVector()
? new ParametersWithIV(new KeyParameter(key), iv)
: new KeyParameter(key));
byte[] out = new byte[data.length];
if (cipher instanceof StreamBlockCipher stream) {
stream.processBytes(data, 0, data.length, out, 0);
return out;
}
for (int offset = 0; offset < data.length; offset += size) {
cipher.processBlock(data, offset, out, offset);
}
return out;
}
/**
* The exclusive-or of two byte arrays of the same length.
*
@@ -291,27 +426,18 @@ public final class Ciphers {
/**
* The encryption or decryption of whole blocks under a key, in CBC mode.
*
* <p>The cipher pads no data, so the data has to fill whole blocks, and that is the
* one thing this method adds to the mode it hands the work to.
*/
private static byte[] blocks(BlockCipher cipher, boolean encrypt, byte[] data, byte[] key, byte[] iv) {
private static byte[] blocks(BlockCipher cipher, boolean encrypt, byte[] data, byte[] key,
byte[] iv) {
int size = cipher.getBlockSize();
if (data == null || data.length % size != 0) {
throw new IllegalArgumentException("the data is "
+ (data == null ? "missing" : data.length + " bytes")
+ "; it is a whole number of " + size + "-byte blocks");
}
if (key == null) {
throw new IllegalArgumentException("key is required");
}
if (iv == null || iv.length != size) {
throw new IllegalArgumentException("the initialization vector is "
+ (iv == null ? "missing" : iv.length + " bytes") + "; it is " + size);
}
BlockCipher cbc = CBCBlockCipher.newInstance(cipher);
cbc.init(encrypt, new ParametersWithIV(new KeyParameter(key), iv));
byte[] out = new byte[data.length];
for (int offset = 0; offset < data.length; offset += size) {
cbc.processBlock(data, offset, out, offset);
}
return out;
return crypt(cipher, encrypt, data, key, iv, BlockMode.CBC);
}
}