feat(paymentcryptography): the key algorithms of the control plane (#7395)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-03 10:35:43 -04:00
1 parent 537e042482
commit 648d363102
10 files changed
+1575 -112

No files matched your search

@@ -2,63 +2,155 @@ package io.github.hectorvent.floci.services.paymentcryptography;
import org.junit.jupiter.api.Test;
import java.security.SecureRandom;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* The AES-CMAC of RFC 4493, against the examples the RFC gives.
* The cryptography of the key record and of the data plane, against values another
* implementation computed.
*
* <p>The examples cover the three cases the algorithm has: a message of no
* length, which is padded and masked with K2; a message of whole blocks, which
* is masked with K1; and a message of blocks and a part, whose last block is
* padded and masked with K2.
* <p>The CMAC vectors are the ones RFC 4493 uses, and the key wrap is the one RFC 3394
* publishes. The CBC vector was computed with the same padding the service uses, so a
* difference in it is a difference in the encryption rather than in the padding.
*/
class PaymentCryptographyCryptoTest {
/** The key of every example the RFC gives. */
private static final String KEY = "2B7E151628AED2A6ABF7158809CF4F3C";
/** The key of the RFC 4493 examples. */
private static final String RFC4493_KEY = "2b7e151628aed2a6abf7158809cf4f3c";
/** The CMAC of a message under {@link #KEY}, as hexadecimal. */
private static String cmac(String message) {
return PaymentCryptographyCrypto.toHex(
PaymentCryptographyCrypto.cmac(PaymentCryptographyCrypto.fromHex(KEY),
PaymentCryptographyCrypto.fromHex(message)));
private static final String M1 = "6bc1bee22e409f96e93d7e117393172a";
private static final String M2 = "ae2d8a571e03ac9c9eb76fac45af8e51";
private static final String M3 = "30c81c46a35ce411e5fbc1191a0a52ef";
private static final String M4 = "f69f2445df4f9b17ad2b417be66c3710";
@Test
void theCmacIsTheOneOfTheStandard() {
assertEquals("bb1d6929e95937287fa37d129b756746", mac(""));
assertEquals("070a16b46b4d4144f79bdd9dd04a287c", mac(M1));
assertEquals("ce0cbf1738f4df6428b1d93bf12081c9", mac(M1 + M2));
assertEquals("dfa66747de9ae63030ca32611497c827", mac(M1 + M2 + M3.substring(0, 16)));
assertEquals("c47c4d9d64588f67fb9de6fe745d7fbf", mac(M1 + M2 + M3));
assertEquals("51f0bebf7e3b9d92fc49741779363cfe", mac(M1 + M2 + M3 + M4));
}
/** RFC 4493's example 1: a message of no length. */
@Test
void anEmptyMessageIsTheMacTheRfcGives() {
assertEquals("bb1d6929e95937287fa37d129b756746", cmac(""));
void theCmacOfAPartialBlockUsesTheSecondSubkey() {
// The last block is padded here, so the second subkey is the one that is used.
assertEquals("41ccdefead58e63835d7582e9f2e5b62", mac(M1 + M2 + M3 + M4.substring(0, 26)));
assertEquals("71c5a229ba6db8c471075ac5b9c64ffe", mac(M1.substring(0, 8)));
}
/** RFC 4493's example 2: a message of one whole block. */
@Test
void aWholeBlockIsTheMacTheRfcGives() {
assertEquals("070a16b46b4d4144f79bdd9dd04a287c", cmac("6bc1bee22e409f96e93d7e117393172a"));
void theCheckValueIsTheLeftmostThreeBytesOfTheCmacOfZeroes() {
// The check value is the CMAC of a whole block of zeroes, which is not the CMAC of
// the empty message: a whole block is exclusive-ored with the first subkey.
byte[] mac = PaymentCryptographyCrypto.cmac(
PaymentCryptographyCrypto.fromHex(RFC4493_KEY), new byte[16]);
assertEquals("7ad386c3760fb3498361a1cb5563bd70", PaymentCryptographyCrypto.toHex(mac));
assertEquals("7AD386", PaymentCryptographyCrypto.checkValue(RFC4493_KEY));
}
/** RFC 4493's example 3: two whole blocks and a padded one. */
@Test
void wholeBlocksAndAPaddedOneAreTheMacTheRfcGives() {
assertEquals("dfa66747de9ae63030ca32611497c827", cmac(
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
+ "30c81c46a35ce411"));
void theKeyWrapIsTheOneOfTheStandard() {
byte[] kek = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
byte[] keyData = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
byte[] wrapped = PaymentCryptographyCrypto.keyWrap(kek, keyData);
assertEquals("1fa68b0a8112b447aef34bd8fb5a7b829d3e862371d2cfe5",
PaymentCryptographyCrypto.toHex(wrapped));
assertArrayEquals(keyData, PaymentCryptographyCrypto.keyUnwrap(kek, wrapped));
}
/** RFC 4493's example 4: four whole blocks. */
@Test
void severalWholeBlocksAreTheMacTheRfcGives() {
assertEquals("51f0bebf7e3b9d92fc49741779363cfe", cmac(
"6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
+ "30c81c46a35ce411e5fbc1191a0a52ef"
+ "f69f2445df4f9b17ad2b417be66c3710"));
void aKeyWrapUnderTheWrongKeyDoesNotOpen() {
byte[] kek = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
byte[] other = PaymentCryptographyCrypto.fromHex("0f0e0d0c0b0a09080706050403020100");
byte[] keyData = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
byte[] wrapped = PaymentCryptographyCrypto.keyWrap(kek, keyData);
assertNull(PaymentCryptographyCrypto.keyUnwrap(other, wrapped));
}
/**
* The check value of a key is the leftmost three bytes of the CMAC of
* sixteen zero bytes under it, which is the CMAC of one whole block.
*/
@Test
void theCheckValueIsTheLeftmostThreeBytesOfTheMacOfSixteenZeroBytes() {
assertEquals("7AD386", PaymentCryptographyCrypto.checkValue(KEY));
void theEncryptionIsTheOneAnotherImplementationComputed() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] plaintext = PaymentCryptographyCrypto.fromHex(
"54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67");
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, new FixedRandom(
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
assertEquals("101112131415161718191a1b1c1d1e1fb746e4f1bce2352d20440b8a2e0eb8fd6"
+ "8c1fcd0d00fcac779ecaadacde7e51a41da205eac66749510362db1c9f3e6d5",
PaymentCryptographyCrypto.toHex(blob));
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob));
}
@Test
void aCiphertextOfAnotherKeyDoesNotOpen() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] other = PaymentCryptographyCrypto.fromHex(
"1f1e1d1c1b1a19181716151413121110f0e0d0c0b0a09080706050403020100");
// The vector is fixed, so the answer is fixed: with a random one the padding of the
// wrong key's plaintext can happen to be valid, and the test would fail now and then
// for no reason.
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, "hello".getBytes(),
new FixedRandom(PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
// The right key opens it, so the refusal below is about the key and not the blob.
assertArrayEquals("hello".getBytes(), PaymentCryptographyCrypto.decryptCbc(key, blob));
assertThrows(IllegalArgumentException.class,
() -> PaymentCryptographyCrypto.decryptCbc(other, blob));
}
@Test
void theEncryptionOfAnEmptyPlaintextIsTheVectorAndThePadding() {
byte[] key = PaymentCryptographyCrypto.fromHex(
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, new byte[0], new FixedRandom(
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
assertEquals(32, blob.length);
assertArrayEquals(new byte[0], PaymentCryptographyCrypto.decryptCbc(key, blob));
}
@Test
void theMaterialIsThirtyTwoBytesAndTheCheckValueIsSixCharacters() {
String material = PaymentCryptographyCrypto.randomAes256Hex(new SecureRandom());
assertEquals(64, material.length());
assertEquals(6, PaymentCryptographyCrypto.checkValue(material).length());
assertNotNull(PaymentCryptographyCrypto.checkValue(material));
}
private static String mac(String messageHex) {
return PaymentCryptographyCrypto.toHex(PaymentCryptographyCrypto.cmac(
PaymentCryptographyCrypto.fromHex(RFC4493_KEY),
PaymentCryptographyCrypto.fromHex(messageHex)));
}
/** A random that answers the same bytes every time, so a vector is a vector. */
private static final class FixedRandom extends SecureRandom {
private final byte[] bytes;
private int used;
FixedRandom(byte[] bytes) {
this.bytes = bytes;
}
@Override
public void nextBytes(byte[] target) {
System.arraycopy(bytes, 0, target, 0, Math.min(bytes.length, target.length));
used += target.length;
}
}
}
@@ -65,6 +65,36 @@ class PaymentCryptographyIntegrationTest {
.body("Key.KeyAttributes.KeyAlgorithm", equalTo("AES_256"));
}
@Test
void aDerivationKeySaysWhatItDerivesFor() {
// The usage a derivation key derives for sits beside the attributes, and it comes
// back with the key.
String arn = call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\","
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_B0_BASE_DERIVATION_KEY\","
+ "\"KeyModesOfUse\":{\"DeriveKey\":true}},"
+ "\"DeriveKeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ "\"Exportable\":true}")
.then().statusCode(200)
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"))
.extract().path("Key.KeyArn");
call("GetKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200)
.body("Key.DeriveKeyUsage", equalTo("TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"));
}
@Test
void aKeyThatAsksForACheckValueOfAnotherKindIsRefused() {
// The kind follows the algorithm, so a request that names another is refused
// rather than answered with a value of another kind.
call("CreateKey", "{\"KeyAttributes\":{\"KeyAlgorithm\":\"TDES_2KEY\","
+ "\"KeyClass\":\"SYMMETRIC_KEY\",\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},"
+ "\"KeyCheckValueAlgorithm\":\"CMAC\"}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"));
}
@Test
void theKeysOfARegionAreListed() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
@@ -9,6 +9,11 @@ import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryp
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -16,6 +21,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
@@ -34,6 +40,16 @@ class PaymentCryptographyServiceTest {
new PaymentCryptographyRequestContext());
}
/** A key of the given algorithm and class, for the tests that need one. */
private PaymentCryptographyKey createKey(String region, String algorithm, String keyClass,
String usage, Map<String, Boolean> modes) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", algorithm);
attributes.put("KeyClass", keyClass);
attributes.put("KeyUsage", usage);
return service.createKey(region, attributes, modes, true, true, Map.of());
}
private PaymentCryptographyKey createKey(String region) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
@@ -57,6 +73,141 @@ class PaymentCryptographyServiceTest {
assertEquals(6, key.getKeyCheckValue().length());
}
@Test
void aTdesKeyCarriesTheAnsiCheckValueOfItsAlgorithm() {
// The ANSI X9.24 check value is the leftmost three bytes of the encrypted zeroes
// under the key, so it is the same for the two algorithms of different length only
// when the keys are the same.
PaymentCryptographyKey two = createKey("us-east-1", "TDES_2KEY", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE,
"Decrypt", Boolean.TRUE));
assertEquals("ANSI_X9_24", two.getKeyCheckValueAlgorithm());
assertEquals(32, two.getKeyMaterialHex().length());
PaymentCryptographyKey three = createKey("us-east-1", "TDES_3KEY", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE,
"Decrypt", Boolean.TRUE));
assertEquals("ANSI_X9_24", three.getKeyCheckValueAlgorithm());
assertEquals(48, three.getKeyMaterialHex().length());
}
@Test
void theCheckValueOfATdesKeyIsTheOneTheStandardGives() {
// The key of the vector, so the check value is the one of the standard.
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "TDES_2KEY");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
PaymentCryptographyKey key = service.createKey("us-east-1", attributes,
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE), true, true, Map.of());
// The check value is the one the standard gives for the material the key carries.
assertEquals("ANSI_X9_24", key.getKeyCheckValueAlgorithm());
assertEquals(6, key.getKeyCheckValue().length());
assertEquals(checkValueOf(key.getKeyMaterialHex()), key.getKeyCheckValue());
// And the standard gives this value for the material of the vector.
assertEquals("08D7B4", checkValueOf("0123456789ABCDEFFEDCBA9876543210"));
}
@Test
void anEllipticCurveKeyIsAKeyPair() {
PaymentCryptographyKey key = createKey("us-east-1", "ECC_NIST_P256", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE,
"Verify", Boolean.TRUE));
assertEquals("ASYMMETRIC_KEY_PAIR", key.getKeyClass());
assertNotNull(key.getKeyPublicKeyBase64());
assertNotNull(key.getKeyPrivateKeyBase64());
// An asymmetric key has no material a check value could be computed from, so it
// reports the fixed placeholder.
assertEquals("000000", key.getKeyCheckValue());
assertEquals("ANSI_X9_24", key.getKeyCheckValueAlgorithm());
}
@Test
void aUsageThatTheAlgorithmCannotServeIsRefused() {
// A key pair has no material a symmetric usage would bind it to, and a symmetric
// key has no pair a key pair's usage would bind it to.
assertValidation(() -> createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
"TR31_M1_ISO_9797_1_MAC_KEY", Map.of("Generate", Boolean.TRUE)),
"may not be made of");
assertValidation(() -> createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Sign", Boolean.TRUE)),
"may not be made of");
}
@Test
void aKeyPairCarriesItsOwnHalves() {
// An RSA key is made of a pair, and the halves are kept with it.
PaymentCryptographyKey rsa = createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE));
assertNotNull(rsa.getKeyPublicKeyBase64());
assertNotNull(rsa.getKeyPrivateKeyBase64());
assertTrue(rsa.getKeyPublicKeyBase64().length() > 256,
"the public half of an RSA-2048 key is a long DER encoding");
// And an EC one is made of a pair on the curve the algorithm names.
PaymentCryptographyKey ec = createKey("us-east-1", "ECC_NIST_P256", "ASYMMETRIC_KEY_PAIR",
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
Map.of("DeriveKey", Boolean.TRUE));
assertNotNull(ec.getKeyPublicKeyBase64());
assertNotNull(ec.getKeyPrivateKeyBase64());
assertNotEquals(rsa.getKeyPublicKeyBase64(), ec.getKeyPublicKeyBase64(),
"the two pairs are different");
}
@Test
void everyAsymmetricUsageTakesAKeyPair() {
// The usages the model names for a key pair, each of which is made.
for (String usage : List.of("TR31_D1_ASYMMETRIC_KEY_FOR_DATA_ENCRYPTION",
"TR31_K2_TR34_ASYMMETRIC_KEY",
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE")) {
PaymentCryptographyKey key = createKey("us-east-1", "RSA_2048", "ASYMMETRIC_KEY_PAIR",
usage, Map.of("Sign", Boolean.TRUE, "Verify", Boolean.TRUE));
assertEquals("RSA_2048", key.getKeyAlgorithm());
assertEquals(usage, key.getKeyUsage());
}
// And the key agreement one takes a curve as well.
PaymentCryptographyKey agreed = createKey("us-east-1", "ECC_NIST_P256",
"ASYMMETRIC_KEY_PAIR", "TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
Map.of("DeriveKey", Boolean.TRUE));
assertEquals("ECC_NIST_P256", agreed.getKeyAlgorithm());
}
@Test
void aClassThatContradictsTheAlgorithmIsRefused() {
assertValidation(() -> createKey("us-east-1", "AES_256", "ASYMMETRIC_KEY_PAIR",
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE", Map.of("Verify", Boolean.TRUE)),
"a symmetric algorithm");
assertValidation(() -> createKey("us-east-1", "RSA_2048", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", Map.of("Encrypt", Boolean.TRUE)),
"an asymmetric algorithm");
}
/** The ANSI X9.24 check value of a key's material, computed the way the standard says. */
private static String checkValueOf(String materialHex) {
byte[] material = HexFormat.of().parseHex(materialHex);
byte[] wide = new byte[24];
System.arraycopy(material, 0, wide, 0, 16);
System.arraycopy(material, 0, wide, 16, 8);
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(wide, "DESede"));
return HexFormat.of().withUpperCase().formatHex(cipher.doFinal(new byte[8]))
.substring(0, 6);
} catch (GeneralSecurityException e) {
throw new IllegalStateException("the Triple DES key could not be used", e);
}
}
private void assertValidation(Runnable refused, String message) {
AwsException failure = assertThrows(AwsException.class, refused::run);
assertEquals("ValidationException", failure.getErrorCode());
assertTrue(failure.getMessage().contains(message), failure.getMessage());
}
@Test
void theCheckValueIsTheLeftmostThreeBytesOfTheCmac() {
PaymentCryptographyKey key = createKey("us-east-1");
@@ -96,6 +247,39 @@ class PaymentCryptographyServiceTest {
// legitimately share one. Only the material has to differ.
}
@Test
void aKeySavedBeforeTheRegionWasPartOfItsNameIsStillFound() {
// A store written before the region became part of the name holds its keys under
// their identifier alone, so an alias written then keeps working.
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyKey key = createKey("us-east-1");
// The key under the name it was saved under before the region was part of it.
store.put(key.getKeyId(), key);
old.createAlias("alias/team/old-key", key);
PaymentCryptographyKey found = old.findKey("us-east-1", "alias/team/old-key");
assertNotNull(found, "the alias names the key that was saved under the old name");
assertEquals(key.getKeyId(), found.getKeyId());
}
@Test
void aDeletedKeyIsGoneUnderTheNameItWasSavedUnder() {
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyKey key = createKey("us-east-1");
store.put(key.getKeyId(), key);
old.deleteKey(key);
assertNull(store.get(key.getKeyId()).orElse(null),
"the key is gone under the name it was saved under too");
}
@Test
void theAliasNameIsUniqueInARegion() {
PaymentCryptographyKey key = createKey("us-east-1");
@@ -196,7 +380,9 @@ class PaymentCryptographyServiceTest {
@Test
void aKeyThatAsksForMaterialTheServiceDoesNotMakeIsRefused() {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_128");
// The service makes the AES sizes, so the algorithm it does not make is one it has
// no material for.
attributes.put("KeyAlgorithm", "DES");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");