diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java index cf834b8ba4..93a5e682de 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyDataPlaneTest.java @@ -197,6 +197,67 @@ class PaymentCryptographyDataPlaneTest { .build())); } + @Test + void aHashedMacIsMadeUnderAKeyThatCarriesTheHash() { + // The reference's guide: a key whose algorithm is a keyed hash carries the hash, and + // the request names the mac by the name of the family. + String hmacKeyArn = TestFixtures.paymentCryptographyClient().createKey(r -> r + .keyAttributes(a -> a + .keyAlgorithm(KeyAlgorithm.HMAC_SHA256) + .keyClass(KeyClass.SYMMETRIC_KEY) + .keyUsage(KeyUsage.TR31_M7_HMAC_KEY) + .keyModesOfUse(m -> m.generate(true).verify(true))) + .exportable(true)) + .key().keyArn(); + + String value = client.generateMac(r -> r + .keyIdentifier(hmacKeyArn) + .messageData(MESSAGE) + .generationAttributes(MacAttributes.builder() + .algorithm(MacAlgorithm.HMAC) + .build())) + .mac(); + + // The length is ignored for the keyed hash, so the mac is the whole hash: sixty-four + // hexadecimal characters of SHA-256. + assertThat(value).hasSize(64); + + client.verifyMac(r -> r + .keyIdentifier(hmacKeyArn) + .messageData(MESSAGE) + .mac(value) + .verificationAttributes(MacAttributes.builder() + .algorithm(MacAlgorithm.HMAC) + .build())); + } + + @Test + void aKeyEncryptsInEveryModeTheReferenceNames() { + for (EncryptionMode mode : new EncryptionMode[] {EncryptionMode.ECB, EncryptionMode.CBC, + EncryptionMode.CFB, EncryptionMode.CFB1, EncryptionMode.CFB8, EncryptionMode.CFB64, + EncryptionMode.CFB128, EncryptionMode.OFB}) { + String cipherText = client.encryptData(r -> r + .keyIdentifier(keyArn) + .plainText(PLAIN_TEXT) + .encryptionAttributes(EncryptionDecryptionAttributes.builder() + .symmetric(SymmetricEncryptionAttributes.builder().mode(mode).build()) + .build())) + .cipherText(); + + assertThat(cipherText).hasSize(PLAIN_TEXT.length()); + + String plainText = client.decryptData(r -> r + .keyIdentifier(keyArn) + .cipherText(cipherText) + .decryptionAttributes(EncryptionDecryptionAttributes.builder() + .symmetric(SymmetricEncryptionAttributes.builder().mode(mode).build()) + .build())) + .plainText(); + + assertThat(plainText).isEqualTo(PLAIN_TEXT); + } + } + @Test void aMacOfAnotherMessageIsRefused() { String value = client.generateMac(r -> r diff --git a/docs/services/payment-cryptography-data.md b/docs/services/payment-cryptography-data.md index 6ac07e2c69..4addbfdd67 100644 --- a/docs/services/payment-cryptography-data.md +++ b/docs/services/payment-cryptography-data.md @@ -29,34 +29,55 @@ client that talks to the control plane does not reach it by accident. ## Emulation Behavior -- **The encryption is AES or Triple DES in CBC mode without padding**, so the caller supplies - whole blocks: sixteen bytes under an AES key and eight under a Triple DES one, as the reference +- **The encryption is AES or Triple DES without padding**, so the caller supplies whole + blocks: sixteen bytes under an AES key and eight under a Triple DES one, as the reference says. A plaintext that does not fill them is refused. A key of another family is refused rather than read as a key of one of these. The ciphertext is the encrypted bytes alone and is as long as the plaintext it holds: the initialization vector travels in the request's attributes, and a request that names none gets a zero vector. The blobs of the data plane are hexadecimal, which is what the reference says they are. -- **Only the CBC mode is made.** The reference's model names eight block cipher modes for the - symmetric encryption, and the reference's page for the attributes names them as the valid - values. This service makes the CBC one, so a request that names the ECB, the CFB, the CFB1, the - CFB8, the CFB64, the CFB128 or the OFB mode is refused with `ValidationException` rather than - answered with a cipher of another kind. The padding of the symmetric attributes belongs to the - RSA cipher, so a request that names one is refused as well. +- **Every mode the reference names is made.** The model names eight block cipher modes for the + symmetric encryption, and the page for the attributes names them as the valid values: 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 under an + AES key and the CFB64 under a Triple DES one. A mode whose feedback is wider than the + cipher's own block is not one that cipher takes, so a Triple DES key is refused for the + CFB128. The electronic code book mode takes no vector, so the vector of a request that + names one is not read. The padding of the symmetric attributes belongs to the RSA cipher, + so a request that names one is refused as well. +- **The symmetric cipher is the only shape of the attributes that is made.** The reference's + model names four shapes of the encryption attributes: the symmetric one, the asymmetric one, + the DUKPT one and the EMV one. This service makes the symmetric one, so a request that names + the asymmetric attributes, the DUKPT attributes or the EMV attributes is refused with + `ValidationException`. The RSA padding types the asymmetric attributes carry, PKCS1, OAEP + SHA-1, OAEP SHA-256 and OAEP SHA-512, are therefore never reached, and neither are the DUKPT + encryption mode or the EMV encryption mode, which the model names as ECB and CBC. - **The MAC is the one the request asks for.** The ISO 9797-1 algorithms 1 and 3 are the ones - defined over Triple DES, and 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. The service fails the request when the + defined over Triple DES, the CMAC is the AES-CMAC of RFC 4493, which is a whole block + wide, and the keyed hash is the hash of RFC 2104. The service fails the request when the MAC is not the one over the message, because the answer of a verification has no verdict in it. -- **The MAC algorithms this service makes are the three the model names beside the DUKPT ones.** - The ISO 9797-1 algorithms 1 and 3, the CMAC, and the DUKPT derivations of the two ISO 9797 - algorithms are made. The HMAC family, the EMV MAC, the DUKPT CMAC and the AS 2805 4.1 MAC - are not, so a request that names one of them is refused with `ValidationException`. The - reference makes them, and the reference's page for the operation says a HMAC can be asked - for, so this is a deviation and not a rule of the model. -- **The length of a MAC is the one the algorithm gives.** The model states the range of four to - thirty-two bytes, and the length a request asks for is refused when the algorithm gives a - shorter one. The reference names the lengths that hold for each algorithm, and this service - takes any length the algorithm can give. +- **The keyed hash takes the hash the key carries.** The reference's guide settles the two + forms the request takes: a key whose algorithm is one of the `HMAC_SHA` ones carries its + hash, and the request names the family, so the key sets the hash; and a key of the + `TR31_M7_HMAC_KEY` usage that is a Triple DES or an AES key is asked for by the hash the + request names, so the request carries the hash of SHA-224, SHA-256, SHA-384 or SHA-512. A + request that names a hash the key does not carry is refused. +- **The MAC algorithms this service does not make are refused.** The EMV MAC, the DUKPT CMAC + and the AS 2805 4.1 MAC are not made, so a request that names one of them is refused with + `ValidationException` rather than answered with a mac of another kind. +- **The length of a MAC is a number of hexadecimal characters.** The reference counts it that + way: "a length of 8 refers to 8 hex characters (4 bytes)". The lengths the reference names + for each algorithm are the ones this service takes: eight or sixteen characters for the + Triple DES macs, and eight, sixteen or thirty-two for the CMAC of an AES key. A length that + is not a whole number of bytes, or one the algorithm cannot give, is refused. The keyed + hash ignores the length: "The mac-length parameter has no effect for HMAC. The output MAC + is always the full hash output", so the mac of a keyed hash is the whole hash. +- **The MAC attributes are the algorithm or a DUKPT derivation.** The reference's model names + five shapes for them: the algorithm, the EMV MAC, and the DUKPT derivations of the ISO 9797-1 + algorithm 1, of the algorithm 3 and of the CMAC. This service makes the algorithm and the two + DUKPT derivations of the ISO 9797-1 algorithms, so a request that names the EMV MAC or the + DUKPT CMAC is refused with `ValidationException`. - **The modes of use of a key decide what it may be used for.** A key without the `Encrypt` mode is refused for an encryption, and a key with `NoRestrictions` is refused for nothing. - **The usage of a key decides what it may be used for.** The modes say whether a key may be @@ -75,6 +96,11 @@ client that talks to the control plane does not reach it by accident. over is a four-digit one and a longer PIN has no verification value. A PIN that does not verify fails the request with `VerificationFailedException`, because the answer of a verification has no verdict in it. +- **The PIN block formats this service makes are the three the model names beside the format 1.** + The reference's model names four formats for the PIN data: the format 0, the format 1, the + format 3 and the format 4. This service makes the format 0, the format 3 and the format 4, so + a request that names the format 1, whether it generates a block, verifies one or translates + one, is refused with `ValidationException`. - **A verification reads the two Triple DES formats.** The reference's page for `VerifyPinData` says "AWS Payment Cryptography supports `ISO_Format_0` and `ISO_Format_3`", while the generation reads the format 4 as well, so a verification that names the format 4 or the @@ -147,6 +173,15 @@ client that talks to the control plane does not reach it by accident. `TR31_E6_EMV_MKEY_OTHER` usage. The dynamic card verification code, which is the Mastercard counterpart over the track data, is refused rather than approximated: it is a proprietary construction and there is nothing published to check a derivation against. +- **The card validation values this service makes are the two card verification values and the + dynamic value.** The reference's model names seven shapes for the generation and eight for the + verification: the American Express card security codes of the two versions, the card + verification values of the two versions, the cardholder verification value, the dynamic card + verification code, the dynamic card verification value, and the Discover dynamic card + verification code on the verification side. This service makes the card verification value of + the two versions and the dynamic card verification value, so a request that names an American + Express card security code, the cardholder verification value or the Discover dynamic card + verification code is refused with `ValidationException`. - **The authorization cryptogram is the ARQC of the transaction.** It is the ISO 9797-1 algorithm 3 retail MAC over the transaction data, cut to eight bytes, under a session key the request's derivation produces. Three derivations are served: the EMV common session key, diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index 7ab3267e47..cd5c7858a1 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -83,13 +83,19 @@ value is a CMAC under an AES key and the ANSI X9.24 value under a Triple DES one, and a request that names another one is refused. - **The key attributes this service makes.** The algorithms are the Triple DES, the AES, - the RSA and the ECC ones, so the HMAC algorithms the reference's model names, which fix - the hash of the key at its creation, are refused. The SHA-1 check value the reference's - model also names is refused as well. The classes are the symmetric key, the asymmetric - key pair and the public key, so the private key class the reference's model also names is - refused. The usage says what the key is for and the algorithm has to serve it, so a key - of a MAC usage may not be made of an AES key, and the asymmetric usages take the key - pairs the reference's table gives them. + the RSA, the ECC and the keyed hash ones, so the hash a key carries is fixed at its + creation, as the reference's guide says. The keyed hash algorithms are for the + `TR31_M7_HMAC_KEY` usage alone, and the SHA-1 check value the reference's model also + names is refused. The classes are the symmetric key, the asymmetric key pair and the + public key, so the private key class the reference's model also names is refused. The + usage says what the key is for and the algorithm has to serve it, so a key of a MAC + usage may not be made of an AES key, and the asymmetric usages take the key pairs the + reference's table gives them. +- **The usage is not checked against the reference's list.** The reference's page for the key + attributes lists the usages a key may have and says that it prevents the creation of a key + that is not valid. This service requires a usage and checks that the algorithm serves it, but + it does not check the usage itself, so a key of a usage the reference does not list is made + here and refused by the reference. - **Which key a request may name:** `KeyIdentifier` takes the ARN of a key, the ARN of an alias or the name of an alias, while `KeyArn` and `ResourceArn` take the ARN of a key alone, as the reference states them. A request naming a key another way is diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCrypto.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCrypto.java index 87126d9c6f..95ec925771 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCrypto.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCrypto.java @@ -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. + * + *
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. + * + *
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); diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java index 86fd9f3fa7..25071c8a6c 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandler.java @@ -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. * *
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. + * + *
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. + * + *
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. * - *
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. + *
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. + * + *
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. */ diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java index 582d592795..09d5717adf 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyKeyAlgorithm.java @@ -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. + * + *
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. * *
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 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.
+ *
+ * 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.
+ *
+ * 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);
+ };
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Cfb1.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Cfb1.java
new file mode 100644
index 0000000000..2978a999e3
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Cfb1.java
@@ -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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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);
+ }
+}
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
index 6db226f350..9bda40c8f5 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/crypto/Ciphers.java
@@ -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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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);
}
}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyBlockModeTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyBlockModeTest.java
new file mode 100644
index 0000000000..74e5603987
--- /dev/null
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyBlockModeTest.java
@@ -0,0 +1,173 @@
+package io.floci.aws.services.paymentcryptography;
+
+import io.floci.aws.services.paymentcryptography.crypto.BlockMode;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * The block cipher modes the reference names, and the bytes each of them produces.
+ *
+ * The values are the ones the standard's own examples give: the key, the vector and the
+ * plain text are the ones NIST SP 800-38A uses for its AES-128 examples, so a mode that
+ * agrees with them agrees with every other implementation of the standard.
+ */
+class PaymentCryptographyBlockModeTest {
+
+ /** The key the standard's AES-128 examples use. */
+ private static final String KEY = "2b7e151628aed2a6abf7158809cf4f3c";
+
+ /** The vector the standard's AES-128 examples use. */
+ private static final String VECTOR = "000102030405060708090a0b0c0d0e0f";
+
+ /** The plain text the standard's AES-128 examples use. */
+ private static final String PLAIN_TEXT = "6bc1bee22e409f96e93d7e117393172a"
+ + "ae2d8a571e03ac9c9eb76fac45af8e51"
+ + "30c81c46a35ce411e5fbc1191a0a52ef"
+ + "f69f2445df4f9b17ad2b417be66c3710";
+
+ /** The cipher text the standard's example for the electronic code book gives. */
+ private static final String ECB = "3ad77bb40d7a3660a89ecaf32466ef97"
+ + "f5d3d58503b9699de785895a96fdbaaf"
+ + "43b1cd7f598ece23881b00e3ed0306887b"
+ + "0c785e27e8ad3f8223207104725dd4";
+
+ /** The cipher text the standard's example for the chaining mode gives. */
+ private static final String CBC = "7649abac8119b246cee98e9b12e9197d"
+ + "5086cb9b507219ee95db113a917678b2"
+ + "73bed6b8e3c1743b7116e69e222295163"
+ + "ff1caa1681fac09120eca307586e1a7";
+
+ /** The cipher text of the feedback mode over the cipher's own block. */
+ private static final String CFB128 = "3b3fd92eb72dad20333449f8e83cfb4a"
+ + "c8a64537a0b3a93fcde3cdad9f1ce58b"
+ + "26751f67a3cbb140b1808cf187a4f4df"
+ + "c04b05357c5d1c0eeac4c66f9ff7f2e6";
+
+ /** The cipher text of the output feedback mode. */
+ private static final String OFB = "3b3fd92eb72dad20333449f8e83cfb4a"
+ + "7789508d16918f03f53c52dac54ed825"
+ + "9740051e9c5fecf64344f7a82260edcc"
+ + "304c6528f659c77866a510d9c1d6ae5e";
+
+ /** The cipher text of the feedback mode over eight bits. */
+ private static final String CFB8 = "3b79424c9c0dd436bace9e0ed4586a4f"
+ + "32b9ded50ae3ba69d472e88267fb5052"
+ + "70cbad1e257691f7c47c5038297edda32"
+ + "ff26d0ed19174096161ecc14086dd62";
+
+ /** The cipher text of the feedback mode over sixty-four bits. */
+ private static final String CFB64 = "3b3fd92eb72dad20764bc8b40ee0de40"
+ + "f857ab76f3e7bc33332265ff0594b12e"
+ + "6c8bf2f3fc1ba87b2f124a56f7fe88d23"
+ + "41f1d0535f0d56e58287bbec2952b2a";
+
+ /** The cipher text of the feedback mode over a single bit. */
+ private static final String CFB1 = "68b3a264f838f5f8c3101070d1ab4c2e"
+ + "22e7f950383a0b71ade4fad0095cb188"
+ + "a57972c3c1882615f7511411fbebf1193"
+ + "997069704fc1d1f27028434c99e60f4";
+
+ @Test
+ void everyModeTheReferenceNamesIsMade() {
+ for (String name : new String[] {"ECB", "CBC", "CFB", "CFB1", "CFB8", "CFB64", "CFB128",
+ "OFB"}) {
+ assertEquals(name, BlockMode.from(name).name());
+ }
+ assertEquals(null, BlockMode.from("ROT13"));
+ }
+
+ @Test
+ void theElectronicCodeBookModeIsTheOneTheStandardGives() {
+ assertEquals(ECB, cipherText(BlockMode.ECB, null));
+ }
+
+ @Test
+ void theChainingModeIsTheOneTheStandardGives() {
+ assertEquals(CBC, cipherText(BlockMode.CBC, VECTOR));
+ }
+
+ @Test
+ void theFeedbackModeOverTheBlockIsTheOneTheStandardGives() {
+ assertEquals(CFB128, cipherText(BlockMode.CFB128, VECTOR));
+ // The feedback mode with no number is the one over the cipher's own block.
+ assertEquals(CFB128, cipherText(BlockMode.CFB, VECTOR));
+ }
+
+ @Test
+ void theOutputFeedbackModeIsTheOneTheStandardGives() {
+ assertEquals(OFB, cipherText(BlockMode.OFB, VECTOR));
+ }
+
+ @Test
+ void theFeedbackModeOverEightBitsIsTheOneAnotherImplementationComputes() {
+ assertEquals(CFB8, cipherText(BlockMode.CFB8, VECTOR));
+ }
+
+ @Test
+ void theFeedbackModeOverSixtyFourBitsIsTheOneAnotherImplementationComputes() {
+ assertEquals(CFB64, cipherText(BlockMode.CFB64, VECTOR));
+ }
+
+ @Test
+ void theFeedbackModeOverOneBitIsTheOneTheStandardGives() {
+ assertEquals(CFB1, cipherText(BlockMode.CFB1, VECTOR));
+ }
+
+ @Test
+ void everyModeDecryptsWhatItEncrypted() {
+ for (BlockMode mode : BlockMode.values()) {
+ byte[] key = PaymentCryptographyCrypto.fromHex(KEY);
+ byte[] vector = PaymentCryptographyCrypto.fromHex(VECTOR);
+ byte[] plain = PaymentCryptographyCrypto.fromHex(PLAIN_TEXT);
+ byte[] cipherText = mode.takesVector()
+ ? PaymentCryptographyCrypto.encrypt(key, plain, vector, mode)
+ : PaymentCryptographyCrypto.encrypt(key, plain, null, mode);
+ byte[] back = mode.takesVector()
+ ? PaymentCryptographyCrypto.decrypt(key, cipherText, vector, mode)
+ : PaymentCryptographyCrypto.decrypt(key, cipherText, null, mode);
+ assertArrayEquals(plain, back, mode.name());
+ }
+ }
+
+ @Test
+ void theModeThatFeedsABlockBackIsTheOneTheBlockHolds() {
+ // The feedback mode over the block enciphers the first block under the vector, so
+ // the first cipher text block is the vector enciphered.
+ byte[] key = PaymentCryptographyCrypto.fromHex(KEY);
+ byte[] vector = PaymentCryptographyCrypto.fromHex(VECTOR);
+ byte[] cipherText = PaymentCryptographyCrypto.encrypt(key,
+ PaymentCryptographyCrypto.fromHex(PLAIN_TEXT), vector, BlockMode.CFB128);
+ assertEquals("3b3fd92eb72dad20333449f8e83cfb4a",
+ PaymentCryptographyCrypto.toHex(cipherText).substring(0, 32));
+ }
+
+ @Test
+ void aModeThatTakesNoVectorIsEncryptedWithoutOne() {
+ byte[] key = PaymentCryptographyCrypto.fromHex(KEY);
+ byte[] plain = PaymentCryptographyCrypto.fromHex(PLAIN_TEXT);
+ assertArrayEquals(plain,
+ PaymentCryptographyCrypto.decrypt(key,
+ PaymentCryptographyCrypto.encrypt(key, plain, null, BlockMode.ECB),
+ null, BlockMode.ECB));
+ }
+
+ @Test
+ void aVectorOfTheWrongLengthIsRefused() {
+ byte[] key = PaymentCryptographyCrypto.fromHex(KEY);
+ byte[] plain = PaymentCryptographyCrypto.fromHex(PLAIN_TEXT);
+ assertThrows(IllegalArgumentException.class, () -> PaymentCryptographyCrypto.encrypt(key,
+ plain, PaymentCryptographyCrypto.fromHex("00112233"), BlockMode.CBC));
+ }
+
+ /** The cipher text of the plain text under the key, in the mode. */
+ private static String cipherText(BlockMode mode, String vector) {
+ byte[] key = PaymentCryptographyCrypto.fromHex(KEY);
+ byte[] plain = PaymentCryptographyCrypto.fromHex(PLAIN_TEXT);
+ byte[] iv = vector == null ? null : PaymentCryptographyCrypto.fromHex(vector);
+ return PaymentCryptographyCrypto.toHex(
+ PaymentCryptographyCrypto.encrypt(key, plain, iv, mode));
+ }
+}
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java
index 42700a3081..070eea3146 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyCryptoHandlerTest.java
@@ -230,7 +230,9 @@ class PaymentCryptographyCryptoHandlerTest {
"GenerationAttributes", iso9797())), "us-east-1");
String value = (String) mac.get("Mac");
- assertEquals(8, hexBytes(value).length);
+ // The reference counts the length of a mac in hexadecimal characters, so a length of
+ // eight is four bytes.
+ assertEquals(4, hexBytes(value).length);
Map The reference makes the keyed hash of the four hashes it names, and the values here are
+ * the ones the standard's own test cases give, so a hash that agrees with them agrees with
+ * every other implementation of the standard.
+ */
+class PaymentCryptographyHmacTest {
+
+ /** The key the standard's first test case uses: twenty bytes of the same byte. */
+ private static final String KEY = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b";
+
+ /** The message the standard's first test case uses. */
+ private static final String MESSAGE = "4869205468657265";
+
+ @Test
+ void theHashOfSha224IsTheOneTheStandardGives() {
+ assertEquals("896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22",
+ mac(new SHA224Digest()));
+ }
+
+ @Test
+ void theHashOfSha256IsTheOneTheStandardGives() {
+ assertEquals("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7",
+ mac(new SHA256Digest()));
+ }
+
+ @Test
+ void theHashOfSha384IsTheOneTheStandardGives() {
+ assertEquals("afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59c"
+ + "faea9ea9076ede7f4af152e8b2fa9cb6",
+ mac(new SHA384Digest()));
+ }
+
+ @Test
+ void theHashOfSha512IsTheOneTheStandardGives() {
+ assertEquals("87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde"
+ + "daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854",
+ mac(new SHA512Digest()));
+ }
+
+ @Test
+ void theHashOfTheMessageIsAsLongAsTheHash() {
+ assertEquals(32, Ciphers.hmac(PaymentCryptographyCrypto.fromHex(KEY),
+ PaymentCryptographyCrypto.fromHex(MESSAGE), new SHA256Digest()).length);
+ assertEquals(64, Ciphers.hmac(PaymentCryptographyCrypto.fromHex(KEY),
+ PaymentCryptographyCrypto.fromHex(MESSAGE), new SHA512Digest()).length);
+ }
+
+ @Test
+ void theCheckValueOfAKeyedHashKeyIsTheHashOfNothing() {
+ // The reference's terminology: "For HMAC keys, the KCV is computed using the hash
+ // selected at key creation on a zero-length message, taking the leftmost 3 bytes."
+ PaymentCryptographyKeyAlgorithm algorithm =
+ PaymentCryptographyKeyAlgorithm.HMAC_SHA256;
+ String checkValue = PaymentCryptographyCrypto.checkValue(
+ PaymentCryptographyCrypto.fromHex(KEY), algorithm);
+ String expected = PaymentCryptographyCrypto.toHex(
+ Arrays.copyOf(Ciphers.hmac(PaymentCryptographyCrypto.fromHex(KEY),
+ new byte[0], new SHA256Digest()), 3)).toUpperCase(Locale.ROOT);
+ assertEquals(expected, checkValue);
+ }
+
+ /** The keyed hash of the message under the key, in the hash. */
+ private static String mac(Digest digest) {
+ return PaymentCryptographyCrypto.toHex(Ciphers.hmac(
+ PaymentCryptographyCrypto.fromHex(KEY),
+ PaymentCryptographyCrypto.fromHex(MESSAGE), digest));
+ }
+}