mirror of
https://github.com/floci-io/floci.git
synced 2026-11-26 23:29:28 -05:00
feat(paymentcryptography): the key algorithms of the control plane (#7395)
This commit is contained in:
1 parent
537e042482
commit
648d363102
10 files changed
+1575
-112
No files matched your search
+333
-45
@@ -1,109 +1,356 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The cryptography a key record needs: its material, and its check value.
|
||||
* The cryptography a key record needs: its material, its check value, and the operations the
|
||||
* data plane performs with it.
|
||||
*
|
||||
* <p>The check value of an AES key is the leftmost three bytes of the CMAC of
|
||||
* sixteen zero bytes under the key. That is what the service computes for a
|
||||
* CMAC check value, and what the reference implementation its samples use
|
||||
* computes.
|
||||
*
|
||||
* <p>The CMAC is the one RFC 4493 gives, so a key's check value is the one
|
||||
* the standard's vectors give and a message of any length is authenticated
|
||||
* the way the standard says.
|
||||
* <p>The data plane encrypts with AES in CBC mode and the padding the service calls PKCS#5,
|
||||
* which is PKCS#7 for a block cipher, and answers with the initialization vector and the
|
||||
* ciphertext in one blob. The MAC is the CMAC of the message under the key, cut to the
|
||||
* length the caller asks for.
|
||||
*/
|
||||
final class PaymentCryptographyCrypto {
|
||||
|
||||
private static final byte[] ZERO_BLOCK = new byte[16];
|
||||
|
||||
/** The block size of AES, in bytes. */
|
||||
private static final int BLOCK_SIZE = 16;
|
||||
private static final int BLOCK = 16;
|
||||
|
||||
private static final byte[] ZERO_BLOCK = new byte[BLOCK_SIZE];
|
||||
/** The initialization vector of a CBC encryption, in bytes. */
|
||||
private static final int IV_LENGTH = 16;
|
||||
|
||||
/** The Rijndael constant the subkey derivation exclusive-oreds in when the shift carries out. */
|
||||
private static final int RB = 0x87;
|
||||
/** The initial value of a key wrap, which the standard gives as it. */
|
||||
private static final byte[] INITIAL_VALUE = {
|
||||
(byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6,
|
||||
(byte) 0xa6, (byte) 0xa6, (byte) 0xa6, (byte) 0xa6};
|
||||
|
||||
private PaymentCryptographyCrypto() {
|
||||
}
|
||||
|
||||
/** Fresh AES-256 material, as hexadecimal. */
|
||||
static String randomAes256Hex(SecureRandom random) {
|
||||
byte[] material = new byte[32];
|
||||
/** Fresh material of the algorithm's length, as hexadecimal. */
|
||||
static String randomMaterialHex(PaymentCryptographyKeyAlgorithm algorithm, SecureRandom random) {
|
||||
byte[] material = new byte[algorithm.bytes];
|
||||
random.nextBytes(material);
|
||||
return toHex(material);
|
||||
}
|
||||
|
||||
/** Fresh AES-256 material, as hexadecimal. */
|
||||
static String randomAes256Hex(SecureRandom random) {
|
||||
return randomMaterialHex(PaymentCryptographyKeyAlgorithm.AES_256, random);
|
||||
}
|
||||
|
||||
/**
|
||||
* The check value of a key of that algorithm.
|
||||
*
|
||||
* <p>A TDES key's value is the ANSI X9.24 one: the leftmost three bytes of encrypting
|
||||
* eight zero bytes with the key. An AES key's value is the leftmost three bytes of the
|
||||
* CMAC of sixteen zero bytes under it.
|
||||
*/
|
||||
static String checkValue(String keyHex, PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
byte[] key = fromHex(keyHex);
|
||||
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 toHex(value).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** 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 toHex(value).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** The check value of an AES key: the leftmost three bytes of the CMAC of sixteen zero bytes. */
|
||||
static String checkValue(String keyHex) {
|
||||
byte[] mac = cmac(fromHex(keyHex), ZERO_BLOCK);
|
||||
return toHex(Arrays.copyOf(mac, 3)).toUpperCase(Locale.ROOT);
|
||||
byte[] value = new byte[3];
|
||||
System.arraycopy(mac, 0, value, 0, 3);
|
||||
return toHex(value).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES-CMAC of a message under a key, as RFC 4493 gives it.
|
||||
* The Triple DES encryption of a block under a key, in ECB mode.
|
||||
*
|
||||
* <p>The message is divided into blocks and chained as CBC-MAC. A last
|
||||
* block of the block size is exclusive-ored with K1, and one shorter is
|
||||
* padded with a single one bit and exclusive-ored with K2, as the RFC
|
||||
* says.
|
||||
* <p>The check value of a Triple DES key is the leftmost three bytes of the encrypted
|
||||
* zeroes, so the block is encrypted and the first three bytes are taken.
|
||||
*
|
||||
* @param data the bytes to encrypt
|
||||
* @param key the key, sixteen or twenty-four bytes
|
||||
* @return the encrypted bytes
|
||||
*/
|
||||
private static byte[] tdesEcbEncrypt(byte[] data, byte[] key) {
|
||||
try {
|
||||
byte[] key24 = key.length == 24 ? key : widenTdesKey(key);
|
||||
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key24, "DESede"));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the Triple DES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** A two-key Triple DES key widened to the three the cipher takes. */
|
||||
private static byte[] widenTdesKey(byte[] key) {
|
||||
byte[] wide = new byte[24];
|
||||
System.arraycopy(key, 0, wide, 0, 16);
|
||||
System.arraycopy(key, 0, wide, 16, 8);
|
||||
return wide;
|
||||
}
|
||||
|
||||
/**
|
||||
* The AES-CMAC of a message under a key, as RFC 4493 computes it.
|
||||
*
|
||||
* <p>The message is split into blocks of sixteen bytes. The last block is the one that is
|
||||
* padded, unless the message fills it exactly, and it is exclusive-ored with the first
|
||||
* subkey when it is whole and with the second when it is padded.
|
||||
*/
|
||||
static byte[] cmac(byte[] key, byte[] message) {
|
||||
try {
|
||||
byte[] k1 = shiftLeft(encrypt(ZERO_BLOCK, key));
|
||||
byte[] k1 = subkeyOne(key);
|
||||
byte[] k2 = shiftLeft(k1);
|
||||
int blocks = (message.length + BLOCK_SIZE - 1) / BLOCK_SIZE;
|
||||
boolean complete = message.length > 0 && message.length % BLOCK_SIZE == 0;
|
||||
if (blocks == 0) {
|
||||
blocks = 1;
|
||||
}
|
||||
byte[] last = new byte[BLOCK_SIZE];
|
||||
int offset = (blocks - 1) * BLOCK_SIZE;
|
||||
if (complete) {
|
||||
System.arraycopy(message, offset, last, 0, BLOCK_SIZE);
|
||||
int blocks = Math.max(1, (message.length + BLOCK - 1) / BLOCK);
|
||||
byte[] last = new byte[BLOCK];
|
||||
int lastLength = message.length - (blocks - 1) * BLOCK;
|
||||
System.arraycopy(message, (blocks - 1) * BLOCK, last, 0, lastLength);
|
||||
if (lastLength == BLOCK) {
|
||||
last = xor(last, k1);
|
||||
} else {
|
||||
int remaining = message.length - offset;
|
||||
System.arraycopy(message, offset, last, 0, remaining);
|
||||
last[remaining] = (byte) 0x80;
|
||||
// The padding of a partial block is a one bit and zeroes, as the standard says.
|
||||
last[lastLength] = (byte) 0x80;
|
||||
last = xor(last, k2);
|
||||
}
|
||||
byte[] chain = ZERO_BLOCK;
|
||||
byte[] state = new byte[BLOCK];
|
||||
for (int i = 0; i < blocks - 1; i++) {
|
||||
byte[] block = new byte[BLOCK_SIZE];
|
||||
System.arraycopy(message, i * BLOCK_SIZE, block, 0, BLOCK_SIZE);
|
||||
chain = encrypt(xor(chain, block), key);
|
||||
byte[] block = new byte[BLOCK];
|
||||
System.arraycopy(message, i * BLOCK, block, 0, BLOCK);
|
||||
state = encrypt(xor(state, block), key);
|
||||
}
|
||||
return encrypt(xor(chain, last), key);
|
||||
return encrypt(xor(state, last), key);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A block shifted left by one bit, with Rijndael's Rb exclusive-ored in
|
||||
* when the shift carried out of the top.
|
||||
* The first CMAC subkey.
|
||||
*
|
||||
* <p>The bit that falls off the top of the block comes from the byte
|
||||
* above it, so the carry travels down the block.
|
||||
* <p>It is the block cipher's output over a zero block, shifted left by one
|
||||
* bit, with Rijndael's Rb exclusive-ored in when the shift carried out of
|
||||
* the top.
|
||||
*/
|
||||
private static byte[] subkeyOne(byte[] key) {
|
||||
try {
|
||||
return shiftLeft(encrypt(ZERO_BLOCK, key));
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The two CMAC subkeys of a key: the first and the second.
|
||||
*
|
||||
* <p>The key derivation of a TR-31 block is seeded with one of them, so they are
|
||||
* wanted on their own.
|
||||
*/
|
||||
static byte[][] cmacSubkeys(byte[] key) {
|
||||
byte[] k1 = subkeyOne(key);
|
||||
return new byte[][] {k1, shiftLeft(k1)};
|
||||
}
|
||||
|
||||
/**
|
||||
* A block shifted left by one bit, with Rijndael's Rb exclusive-ored in when the shift
|
||||
* carried out of the top.
|
||||
*/
|
||||
private static byte[] shiftLeft(byte[] block) {
|
||||
byte[] shifted = new byte[BLOCK_SIZE];
|
||||
byte[] out = new byte[BLOCK];
|
||||
int carry = 0;
|
||||
for (int i = BLOCK_SIZE - 1; i >= 0; i--) {
|
||||
for (int i = BLOCK - 1; i >= 0; i--) {
|
||||
// The bit that falls off the top of the block comes from the
|
||||
// byte above it, so the carry travels down the block.
|
||||
int nextCarry = (block[i] & 0x80) != 0 ? 1 : 0;
|
||||
shifted[i] = (byte) (((block[i] << 1) | carry) & 0xff);
|
||||
out[i] = (byte) (((block[i] << 1) | carry) & 0xff);
|
||||
carry = nextCarry;
|
||||
}
|
||||
if ((block[0] & 0x80) != 0) {
|
||||
shifted[BLOCK_SIZE - 1] ^= (byte) RB;
|
||||
out[BLOCK - 1] ^= (byte) 0x87;
|
||||
}
|
||||
return shifted;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under a key: the initialization vector and the encrypted
|
||||
* bytes in one blob, which is how the service answers.
|
||||
*/
|
||||
static byte[] encryptCbc(byte[] key, byte[] plaintext, SecureRandom random) {
|
||||
return encryptCbc(key, plaintext, null, random);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ciphertext of a plaintext under a key, with the initialization vector the request
|
||||
* names.
|
||||
*
|
||||
* <p>A request that names a vector gets the ciphertext under it, so two parties that
|
||||
* agree on the vector can read each other's ciphertext. A request that names none gets a
|
||||
* fresh one.
|
||||
*
|
||||
* @param key the key
|
||||
* @param plaintext the bytes to encrypt
|
||||
* @param initializationVector the vector to encrypt under, or null for a fresh one
|
||||
* @param random the randomness a fresh vector comes from
|
||||
* @return the vector and the encrypted bytes in one blob
|
||||
*/
|
||||
static byte[] encryptCbc(byte[] key, byte[] plaintext, byte[] initializationVector,
|
||||
SecureRandom random) {
|
||||
try {
|
||||
byte[] iv;
|
||||
if (initializationVector == null) {
|
||||
iv = new byte[IV_LENGTH];
|
||||
random.nextBytes(iv);
|
||||
} else {
|
||||
if (initializationVector.length != IV_LENGTH) {
|
||||
throw new IllegalArgumentException("the initialization vector is "
|
||||
+ initializationVector.length + " bytes; it is " + IV_LENGTH);
|
||||
}
|
||||
iv = initializationVector.clone();
|
||||
}
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
byte[] encrypted = cipher.doFinal(plaintext);
|
||||
byte[] out = new byte[iv.length + encrypted.length];
|
||||
System.arraycopy(iv, 0, out, 0, iv.length);
|
||||
System.arraycopy(encrypted, 0, out, iv.length, encrypted.length);
|
||||
return out;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext of a blob the service encrypted.
|
||||
*
|
||||
* <p>The blob is the initialization vector and the ciphertext, so the vector is read first
|
||||
* and the rest is decrypted under it. A blob that is not the key's does not decrypt, and
|
||||
* the padding does not hold.
|
||||
*/
|
||||
static byte[] decryptCbc(byte[] key, byte[] blob) {
|
||||
if (blob.length <= IV_LENGTH) {
|
||||
throw new IllegalArgumentException("the ciphertext is shorter than the initialization vector");
|
||||
}
|
||||
try {
|
||||
byte[] iv = Arrays.copyOfRange(blob, 0, IV_LENGTH);
|
||||
byte[] encrypted = Arrays.copyOfRange(blob, IV_LENGTH, blob.length);
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(encrypted);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalArgumentException("the ciphertext did not open under the key", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The key wrap of RFC 3394: a plaintext wrapped under a key, with the check that says the
|
||||
* key was the right one.
|
||||
*/
|
||||
static byte[] keyWrap(byte[] key, byte[] plaintext) {
|
||||
try {
|
||||
byte[] a = INITIAL_VALUE.clone();
|
||||
byte[][] r = split(plaintext, 8);
|
||||
int n = r.length;
|
||||
for (int j = 0; j < 6; j++) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
byte[] block = concat(a, r[i]);
|
||||
byte[] encrypted = encrypt(block, key);
|
||||
a = Arrays.copyOfRange(encrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(encrypted, 8, encrypted.length);
|
||||
a = xor(a, counter(j, n, i));
|
||||
}
|
||||
}
|
||||
byte[] out = new byte[8 + plaintext.length];
|
||||
System.arraycopy(a, 0, out, 0, 8);
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, 8 + i * 8, 8);
|
||||
}
|
||||
return out;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The plaintext of a key wrap, or null when the wrapping key was not the right one.
|
||||
*/
|
||||
static byte[] keyUnwrap(byte[] key, byte[] wrapped) {
|
||||
if (wrapped.length < 16 || (wrapped.length - 8) % 8 != 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
byte[] a = Arrays.copyOfRange(wrapped, 0, 8);
|
||||
byte[][] r = split(Arrays.copyOfRange(wrapped, 8, wrapped.length), 8);
|
||||
int n = r.length;
|
||||
for (int j = 5; j >= 0; j--) {
|
||||
for (int i = n - 1; i >= 0; i--) {
|
||||
byte[] block = concat(xor(a, counter(j, n, i)), r[i]);
|
||||
byte[] decrypted = decrypt(block, key);
|
||||
a = Arrays.copyOfRange(decrypted, 0, 8);
|
||||
r[i] = Arrays.copyOfRange(decrypted, 8, decrypted.length);
|
||||
}
|
||||
}
|
||||
byte[] check = INITIAL_VALUE;
|
||||
byte[] out = new byte[wrapped.length - 8];
|
||||
for (int i = 0; i < n; i++) {
|
||||
System.arraycopy(r[i], 0, out, i * 8, 8);
|
||||
}
|
||||
return Arrays.equals(a, check) ? out : null;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrap counter of the block at {@code index} of a wrap of {@code n} blocks: the
|
||||
* standard's {@code t}, which is the round times the number of blocks and the block.
|
||||
*/
|
||||
private static byte[] counter(int round, int n, int index) {
|
||||
byte[] value = new byte[8];
|
||||
value[7] = (byte) (round * n + index + 1);
|
||||
return value;
|
||||
}
|
||||
|
||||
private static byte[][] split(byte[] bytes, int size) {
|
||||
int count = bytes.length / size;
|
||||
byte[][] out = new byte[count][];
|
||||
for (int i = 0; i < count; i++) {
|
||||
out[i] = Arrays.copyOfRange(bytes, i * size, (i + 1) * size);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[] left, byte[] right) {
|
||||
byte[] out = new byte[left.length + right.length];
|
||||
System.arraycopy(left, 0, out, 0, left.length);
|
||||
System.arraycopy(right, 0, out, left.length, right.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] xor(byte[] left, byte[] right) {
|
||||
@@ -114,13 +361,54 @@ final class PaymentCryptographyCrypto {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode, the block cipher the CMAC is built on. */
|
||||
/**
|
||||
* 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) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
|
||||
return cipher.doFinal(data);
|
||||
} catch (GeneralSecurityException 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) {
|
||||
try {
|
||||
return encrypt(input, key);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("the AES key could not be used", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode. */
|
||||
private static byte[] encrypt(byte[] input, byte[] key) throws GeneralSecurityException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
|
||||
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
|
||||
/** One block of AES in ECB mode, the other way round. */
|
||||
private static byte[] decrypt(byte[] input, byte[] key) throws GeneralSecurityException {
|
||||
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
|
||||
return cipher.doFinal(input);
|
||||
}
|
||||
|
||||
static String toHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
|
||||
+24
-7
@@ -86,16 +86,30 @@ public class PaymentCryptographyJsonHandler {
|
||||
declared.put(entry.getKey(), entry.getValue().asText());
|
||||
}
|
||||
});
|
||||
// The check value of an AES key is a CMAC, which is the only algorithm this
|
||||
// service computes, so a request naming another one is refused rather than
|
||||
// answered with a check value of another kind.
|
||||
if (request.hasNonNull("KeyCheckValueAlgorithm")
|
||||
&& !"CMAC".equals(request.get("KeyCheckValueAlgorithm").asText())) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyCheckValueAlgorithm must be CMAC", 400);
|
||||
// The check value follows the key's algorithm: an AES key's is a CMAC and a
|
||||
// TDES key's is the ANSI X9.24 one. A request that names another is refused
|
||||
// rather than answered with a value of another kind.
|
||||
if (request.hasNonNull("KeyCheckValueAlgorithm")) {
|
||||
String wanted = request.get("KeyCheckValueAlgorithm").asText();
|
||||
String algorithmName = declared.get("KeyAlgorithm") == null ? ""
|
||||
: String.valueOf(declared.get("KeyAlgorithm"));
|
||||
// The kind the service will answer with, so a request is never refused for a
|
||||
// kind the service would have given.
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
PaymentCryptographyKeyAlgorithm.from(algorithmName);
|
||||
String expected = algorithm == null ? null : algorithm.checkValueAlgorithm();
|
||||
if (expected != null && !expected.equals(wanted)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyCheckValueAlgorithm must be " + expected + " for a " + algorithmName
|
||||
+ " key", 400);
|
||||
}
|
||||
}
|
||||
// A key may be created disabled, and it may be created with tags.
|
||||
boolean enabled = request.has("Enabled") ? request.path("Enabled").asBoolean(true) : true;
|
||||
if (request.hasNonNull("DeriveKeyUsage")) {
|
||||
// The usage a derivation key derives for sits beside the attributes, not in them.
|
||||
declared.put("DeriveKeyUsage", request.path("DeriveKeyUsage").asText());
|
||||
}
|
||||
PaymentCryptographyKey key = service.createKey(region, declared, modesOfUse(attributes),
|
||||
request.path("Exportable").asBoolean(false), enabled, tagsOf(request));
|
||||
return Map.of("Key", keyObject(key));
|
||||
@@ -334,6 +348,9 @@ public class PaymentCryptographyJsonHandler {
|
||||
attributes.put("KeyUsage", key.getKeyUsage());
|
||||
attributes.put("KeyModesOfUse", answeredModes(key));
|
||||
out.put("KeyAttributes", attributes);
|
||||
if (key.getDeriveKeyUsage() != null && !key.getDeriveKeyUsage().isEmpty()) {
|
||||
out.put("DeriveKeyUsage", key.getDeriveKeyUsage());
|
||||
}
|
||||
out.put("KeyCheckValue", key.getKeyCheckValue());
|
||||
out.put("KeyCheckValueAlgorithm", key.getKeyCheckValueAlgorithm());
|
||||
out.put("KeyState", key.getKeyState());
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The key algorithms this service makes, with each one's key length.
|
||||
*
|
||||
* <p>The length is what tells the two families apart: a TDES key is 16 or 24 bytes and an
|
||||
* AES key is 16, 24 or 32 bytes. The PIN block formats need the family, because a format 0
|
||||
* or 3 block is a TDES block and a format 4 block is an AES one.
|
||||
*
|
||||
* <p>A real enum rather than a list of names, so the service, the check value and the
|
||||
* operations all read the same definition.
|
||||
*/
|
||||
enum PaymentCryptographyKeyAlgorithm {
|
||||
|
||||
TDES_2KEY(16, false, false, false),
|
||||
TDES_3KEY(24, false, false, false),
|
||||
AES_128(16, true, false, false),
|
||||
AES_192(24, true, false, false),
|
||||
AES_256(32, true, false, false),
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
ECC_NIST_P256(32, false, true, false),
|
||||
/** An EC key agreement key on NIST P-384. */
|
||||
ECC_NIST_P384(48, false, true, false),
|
||||
/** An EC key agreement key on NIST P-521. */
|
||||
ECC_NIST_P521(66, false, true, false),
|
||||
/**
|
||||
* An RSA key pair with a 2048-bit modulus.
|
||||
*
|
||||
* <p>A TR-34 exchange needs one: the authority that certifies the signing key is an RSA
|
||||
* certificate.
|
||||
*/
|
||||
RSA_2048(256, false, false, true),
|
||||
/** An RSA key pair with a 3072-bit modulus. */
|
||||
RSA_3072(384, false, false, true),
|
||||
/** An RSA key pair with a 4096-bit modulus. */
|
||||
RSA_4096(512, false, false, true);
|
||||
|
||||
/** How many bytes of material the key holds. */
|
||||
final int bytes;
|
||||
|
||||
/** Whether the key is an AES key rather than a TDES one. */
|
||||
final boolean aes;
|
||||
|
||||
/** Whether the key is an EC key, which has a key pair rather than key material. */
|
||||
final boolean ecc;
|
||||
|
||||
/** Whether the key is an RSA key, which has a key pair and no symmetric material. */
|
||||
final boolean rsa;
|
||||
|
||||
PaymentCryptographyKeyAlgorithm(int bytes, boolean aes, boolean ecc, boolean rsa) {
|
||||
this.bytes = bytes;
|
||||
this.aes = aes;
|
||||
this.ecc = ecc;
|
||||
this.rsa = rsa;
|
||||
}
|
||||
|
||||
/** Whether the key holds material a symmetric cipher can use. */
|
||||
boolean symmetric() {
|
||||
return !ecc && !rsa;
|
||||
}
|
||||
|
||||
/**
|
||||
* The kind of check value a key of this algorithm carries.
|
||||
*
|
||||
* <p>An AES key's check value is a CMAC, and a TDES key's is the ANSI X9.24 one. An
|
||||
* asymmetric key has no material a check value could be computed from, so it reports the
|
||||
* fixed placeholder and the same kind as a TDES key.
|
||||
*
|
||||
* <p>The service and the request that asks for a key agree on this, so a request is
|
||||
* never refused for a kind the service would have answered with.
|
||||
*/
|
||||
String checkValueAlgorithm() {
|
||||
return aes ? "CMAC" : "ANSI_X9_24";
|
||||
}
|
||||
|
||||
/** The generated key length in bytes. */
|
||||
int bytes() {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** Whether the key is an AES key rather than a TDES one. */
|
||||
boolean isAes() {
|
||||
return aes;
|
||||
}
|
||||
|
||||
/** Whether the key is an EC key, which has a key pair rather than key material. */
|
||||
boolean isEcc() {
|
||||
return ecc;
|
||||
}
|
||||
|
||||
/** Whether the key is an RSA key, which has a key pair and no symmetric material. */
|
||||
boolean isRsa() {
|
||||
return rsa;
|
||||
}
|
||||
|
||||
/** The algorithm of that name, or null when the service does not make it. */
|
||||
static PaymentCryptographyKeyAlgorithm from(String name) {
|
||||
if (name == null) {
|
||||
return null;
|
||||
}
|
||||
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
|
||||
if (algorithm.name().equals(name)) {
|
||||
return algorithm;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The algorithms of that family, for a message that names the family. */
|
||||
static String supportedOf(boolean aes) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
|
||||
if (algorithm.aes != aes || !algorithm.symmetric()) {
|
||||
continue;
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(algorithm.name());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** Every algorithm the service makes, for a message that names them all. */
|
||||
static String supportedAll() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (PaymentCryptographyKeyAlgorithm algorithm : values()) {
|
||||
if (sb.length() > 0) {
|
||||
sb.append(", ");
|
||||
}
|
||||
sb.append(algorithm.name());
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** 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",
|
||||
"TR31_K2_TR34_ASYMMETRIC_KEY",
|
||||
"TR31_K3_ASYMMETRIC_KEY_FOR_KEY_AGREEMENT",
|
||||
"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
|
||||
|
||||
/**
|
||||
* The algorithms a key of a usage may be made of.
|
||||
*
|
||||
* <p>The service refuses a key whose algorithm its usage does not allow, because the usage
|
||||
* is what binds the key to its purpose, and a MAC key made of AES is a key whose purpose
|
||||
* its own algorithm does not serve.
|
||||
*
|
||||
* @param usage the TR-31 usage name of the key
|
||||
* @return the algorithms the usage allows
|
||||
*/
|
||||
static List<PaymentCryptographyKeyAlgorithm> allowedOf(String usage) {
|
||||
if (ASYMMETRIC_USAGES.contains(usage)) {
|
||||
// The asymmetric usages are the ones a key pair is made of: the data
|
||||
// encryption key, the key agreement key, the TR-34 key and the signing key.
|
||||
return List.of(RSA_2048, RSA_3072, RSA_4096, ECC_NIST_P256, ECC_NIST_P384,
|
||||
ECC_NIST_P521);
|
||||
}
|
||||
if ("TR31_M1_ISO_9797_1_MAC_KEY".equals(usage)
|
||||
|| "TR31_M3_ISO_9797_3_MAC_KEY".equals(usage)
|
||||
|| "TR31_M0_ISO_16609_MAC_KEY".equals(usage)) {
|
||||
// The ISO 9797 MACs are defined over Triple DES.
|
||||
return List.of(TDES_2KEY, TDES_3KEY);
|
||||
}
|
||||
// Every other usage takes every symmetric algorithm.
|
||||
return List.of(TDES_2KEY, TDES_3KEY, AES_128, AES_192, AES_256);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason an algorithm is refused for a usage, in words a caller can act on.
|
||||
*
|
||||
* <p>An algorithm is refused for a usage the usage does not allow, whether it is symmetric
|
||||
* or not: 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. A key that claims a purpose its own
|
||||
* material cannot serve is not a key the service makes.
|
||||
*
|
||||
* @param usage the TR-31 usage name of the key
|
||||
* @param algorithm the algorithm of the key
|
||||
* @return the message, or null when the combination is allowed
|
||||
*/
|
||||
static String refusal(String usage, PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
if (algorithm == null) {
|
||||
return null;
|
||||
}
|
||||
if (allowedOf(usage).contains(algorithm)) {
|
||||
return null;
|
||||
}
|
||||
return "a key of the usage " + usage + " may not be made of " + algorithm.name()
|
||||
+ ": the usage allows " + allowedOf(usage);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyPair;
|
||||
import java.security.KeyPairGenerator;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.spec.ECGenParameterSpec;
|
||||
|
||||
/**
|
||||
* The key pairs the service makes.
|
||||
*
|
||||
* <p>An RSA key pair is made for the key exchange and for the TR-34 block, and an EC one
|
||||
* for the key agreement the exchange does. The certificates over them are the exchange's
|
||||
* own business.
|
||||
*/
|
||||
final class PaymentCryptographyKeyPairs {
|
||||
|
||||
private PaymentCryptographyKeyPairs() {
|
||||
}
|
||||
|
||||
/** An RSA key pair of the requested modulus size. */
|
||||
static KeyPair rsa(int bits, SecureRandom random) {
|
||||
if (bits != 2048 && bits != 3072 && bits != 4096) {
|
||||
throw new IllegalArgumentException(
|
||||
"unsupported key size " + bits + " (2048, 3072, 4096)");
|
||||
}
|
||||
try {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(bits, random);
|
||||
return generator.generateKeyPair();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("cannot generate an RSA key pair", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** An EC key pair on the curve the algorithm names. */
|
||||
static KeyPair ec(PaymentCryptographyKeyAlgorithm algorithm, SecureRandom random) {
|
||||
String curve = curveOf(algorithm);
|
||||
try {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
|
||||
generator.initialize(new ECGenParameterSpec(curve), random);
|
||||
return generator.generateKeyPair();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("cannot generate an EC key pair", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The curve an algorithm names.
|
||||
*
|
||||
* <p>The curve is the NIST one the cardholder-device flow uses.
|
||||
*/
|
||||
private static String curveOf(PaymentCryptographyKeyAlgorithm algorithm) {
|
||||
return switch (algorithm) {
|
||||
case ECC_NIST_P256 -> "secp256r1";
|
||||
case ECC_NIST_P384 -> "secp384r1";
|
||||
case ECC_NIST_P521 -> "secp521r1";
|
||||
default -> throw new IllegalArgumentException(
|
||||
algorithm.name() + " is not an elliptic curve algorithm");
|
||||
};
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package io.github.hectorvent.floci.services.paymentcryptography;
|
||||
|
||||
import java.security.interfaces.ECKey;
|
||||
|
||||
/**
|
||||
* The minimum key strengths the PCI standards set, and the rule they make of them.
|
||||
*
|
||||
* <p>A key that protects another one has to be at least as strong as the key it
|
||||
* protects, because a weaker protector buys nothing: the protected key is then
|
||||
* only as safe as the key that wraps it. The service enforces this on export
|
||||
* and on import, and the reference does the same.
|
||||
*
|
||||
* <p>The strengths are the ones the PCI HSM standards count, not the length of
|
||||
* the material: a two-key Triple DES key is 128 bits of material but 80 bits of
|
||||
* strength, and a three-key one is 192 bits of material and 112 bits of
|
||||
* strength. A length would call the two-key key the stronger one, which is the
|
||||
* opposite of the truth.
|
||||
*/
|
||||
final class PaymentCryptographyKeyStrength {
|
||||
|
||||
private PaymentCryptographyKeyStrength() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The strength of a key of an algorithm, in bits, as the PCI standards
|
||||
* count it. A key of an algorithm this service does not have a strength
|
||||
* for has none, and cannot protect anything.
|
||||
*/
|
||||
static int bitsOf(String algorithm) {
|
||||
if (algorithm == null) {
|
||||
return 0;
|
||||
}
|
||||
return switch (algorithm) {
|
||||
case "TDES_2KEY" -> 80;
|
||||
case "TDES_3KEY" -> 112;
|
||||
case "AES_128" -> 128;
|
||||
case "AES_192" -> 192;
|
||||
case "AES_256" -> 256;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The strength of an RSA key of a modulus size, in bits.
|
||||
*
|
||||
* <p>An RSA key is as strong as factoring its modulus is hard. The standards count a
|
||||
* 2048-bit modulus as 112 bits, a 3072-bit one as 128 bits and a 4096-bit one as 152
|
||||
* bits.
|
||||
*
|
||||
* @param modulusBits the size of the modulus, in bits
|
||||
* @return the strength, in bits, or zero for a size this service has none for
|
||||
*/
|
||||
static int rsaBitsOf(int modulusBits) {
|
||||
if (modulusBits >= 4096) {
|
||||
return 152;
|
||||
}
|
||||
if (modulusBits >= 3072) {
|
||||
return 128;
|
||||
}
|
||||
if (modulusBits >= 2048) {
|
||||
return 112;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The strength of an EC key on a curve, in bits.
|
||||
*
|
||||
* <p>A curve is as strong as the discrete logarithm on it is hard. The standards count
|
||||
* P-256 as 128 bits, P-384 as 192 bits and P-521 as 256 bits.
|
||||
*
|
||||
* @param algorithm the curve, as the key algorithm names it
|
||||
* @return the strength, in bits, or zero for a curve this service has none for
|
||||
*/
|
||||
static int eccBitsOf(String algorithm) {
|
||||
if (algorithm == null) {
|
||||
return 0;
|
||||
}
|
||||
return switch (algorithm) {
|
||||
case "ECC_NIST_P256" -> 128;
|
||||
case "ECC_NIST_P384" -> 192;
|
||||
case "ECC_NIST_P521" -> 256;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The strength of an EC public key, from the curve it is on.
|
||||
*
|
||||
* <p>The curve is read from the key itself, because a certificate may name a curve the
|
||||
* service does not have a strength for, and a key agreement is only as strong as the
|
||||
* weaker of the two curves it was agreed on.
|
||||
*
|
||||
* @param key the public key, or null when there is none
|
||||
* @return the strength, in bits, or zero for a curve this service has none for
|
||||
*/
|
||||
static int eccBitsOf(ECKey key) {
|
||||
if (key == null) {
|
||||
return 0;
|
||||
}
|
||||
int fieldBits = key.getParams().getCurve().getField().getFieldSize();
|
||||
return switch (fieldBits) {
|
||||
case 256 -> 128;
|
||||
case 384 -> 192;
|
||||
case 521 -> 256;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key of one algorithm may protect a key of another.
|
||||
*
|
||||
* <p>The protecting key has to be at least as strong as the key it
|
||||
* protects. A key of the same strength is allowed: the rule is that the
|
||||
* protector is not weaker, not that it is stronger.
|
||||
*
|
||||
* @param protecting the algorithm of the key that protects the other
|
||||
* @param protectedKey the algorithm of the key that is protected
|
||||
* @return whether the combination is one the standards allow
|
||||
*/
|
||||
static boolean mayProtect(String protecting, String protectedKey) {
|
||||
int protector = bitsOf(protecting);
|
||||
int protectedBits = bitsOf(protectedKey);
|
||||
if (protector == 0 || protectedBits == 0) {
|
||||
return false;
|
||||
}
|
||||
return protector >= protectedBits;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason a combination is refused, in words a caller can act on.
|
||||
*
|
||||
* @param protecting the algorithm of the key that protects the other
|
||||
* @param protectedKey the algorithm of the key that is protected
|
||||
* @return the message, or null when the combination is allowed
|
||||
*/
|
||||
static String refusal(String protecting, String protectedKey) {
|
||||
return refusal(bitsOf(protecting), bitsOf(protectedKey), protecting, protectedKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* The reason a combination is refused, in words a caller can act on.
|
||||
*
|
||||
* <p>This is the form for a protector whose strength comes from the size of its modulus or
|
||||
* its curve rather than from a name.
|
||||
*
|
||||
* @param protectorBits the strength of the protecting key, in bits
|
||||
* @param protectedBits the strength of the protected key, in bits
|
||||
* @param protectingName what to call the protecting key
|
||||
* @param protectedName what to call the protected key
|
||||
* @return the message, or null when the combination is allowed
|
||||
*/
|
||||
static String refusal(int protectorBits, int protectedBits, String protectingName,
|
||||
String protectedName) {
|
||||
if (protectorBits == 0 || protectedBits == 0) {
|
||||
return "a " + (protectedName == null ? "the key" : protectedName)
|
||||
+ " key may not be protected by a "
|
||||
+ (protectingName == null ? "the wrapping key" : protectingName)
|
||||
+ " key: the wrapping key has to be at least as strong as the key it protects";
|
||||
}
|
||||
if (protectorBits >= protectedBits) {
|
||||
return null;
|
||||
}
|
||||
String name = protectedName == null ? "the key" : protectedName;
|
||||
String protector = protectingName == null ? "the wrapping key" : protectingName;
|
||||
return "a " + name + " key may not be protected by a " + protector
|
||||
+ " key: the wrapping key has to be at least as strong as the key it protects";
|
||||
}
|
||||
}
|
||||
+389
-24
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.Pagination;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.Resettable;
|
||||
import io.github.hectorvent.floci.core.common.StoredResourceArns;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryptographyAlias;
|
||||
@@ -15,13 +16,17 @@ import io.github.hectorvent.floci.services.paymentcryptography.model.PaymentCryp
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.security.KeyPair;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
@@ -50,14 +55,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
/** The error a bad page size or a bad token is refused with. */
|
||||
private static final String PAGINATION_ERROR = "ValidationException";
|
||||
|
||||
/** The only algorithm this service makes material for. */
|
||||
private static final String SUPPORTED_ALGORITHM = "AES_256";
|
||||
|
||||
/** The only class this service makes material for. */
|
||||
private static final String SUPPORTED_CLASS = "SYMMETRIC_KEY";
|
||||
|
||||
/** The class of a key pair, which has a public half and a private one. */
|
||||
private static final String ASYMMETRIC_CLASS = "ASYMMETRIC_KEY_PAIR";
|
||||
|
||||
/** The class of a key that is only a public half. */
|
||||
private static final String PUBLIC_KEY_CLASS = "PUBLIC_KEY";
|
||||
|
||||
private final StorageBackend<String, PaymentCryptographyKey> keyStore;
|
||||
private final StorageBackend<String, PaymentCryptographyAlias> aliasStore;
|
||||
|
||||
private final RegionResolver regionResolver;
|
||||
private final SecureRandom secureRandom;
|
||||
private final PaymentCryptographyRequestContext requestContext;
|
||||
@@ -81,6 +90,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
this(keyStore, aliasStore, regionResolver, new SecureRandom(), requestContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* The service over two stores, with a request context of its own.
|
||||
*
|
||||
* <p>The context belongs to a request in the running service, so a caller that is not
|
||||
* one, such as a test, is given one that resolves its aliases itself.
|
||||
*/
|
||||
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
|
||||
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
|
||||
RegionResolver regionResolver) {
|
||||
this(keyStore, aliasStore, regionResolver, new SecureRandom(),
|
||||
new PaymentCryptographyRequestContext());
|
||||
}
|
||||
|
||||
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
|
||||
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
|
||||
RegionResolver regionResolver,
|
||||
@@ -99,45 +121,130 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
public PaymentCryptographyKey createKey(String region, Map<String, Object> attributes,
|
||||
Map<String, Boolean> modesOfUse, boolean exportable,
|
||||
boolean enabled, Map<String, String> tags) {
|
||||
String algorithm = string(attributes, "KeyAlgorithm", "AES_256");
|
||||
return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a key, with the material it is given rather than with fresh material.
|
||||
*
|
||||
* <p>An imported key holds the material that came in with it, so the material is a
|
||||
* parameter of the key that is made.
|
||||
*/
|
||||
private PaymentCryptographyKey makeKey(String region, Map<String, Object> attributes,
|
||||
Map<String, Boolean> modesOfUse, boolean exportable,
|
||||
boolean enabled, Map<String, String> tags,
|
||||
String materialHex) {
|
||||
return makeKey(region, attributes, modesOfUse, exportable, enabled, tags, materialHex,
|
||||
null, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a key, with the material it is given rather than with fresh material.
|
||||
*
|
||||
* <p>An imported key holds the material that came in with it, so the material is a
|
||||
* parameter of the key that is made. An asymmetric key holds a key pair rather than
|
||||
* material, so its halves are parameters too.
|
||||
*
|
||||
* @param publicKeyBase64 the public half of an asymmetric key, or null
|
||||
* @param privateKeyBase64 the private half of an asymmetric key, or null
|
||||
* @param certificatePem the certificate an imported public key arrived with, or null
|
||||
*/
|
||||
private PaymentCryptographyKey makeKey(String region, Map<String, Object> attributes,
|
||||
Map<String, Boolean> modesOfUse, boolean exportable,
|
||||
boolean enabled, Map<String, String> tags,
|
||||
String materialHex, String publicKeyBase64,
|
||||
String privateKeyBase64, String certificatePem) {
|
||||
String algorithmName = string(attributes, "KeyAlgorithm", "AES_256");
|
||||
String keyClass = string(attributes, "KeyClass", "SYMMETRIC_KEY");
|
||||
// The material is AES-256 and symmetric, so a key that says otherwise would be a key
|
||||
// The material has to be the algorithm's, so a key that says otherwise would be a key
|
||||
// whose attributes do not describe it.
|
||||
if (!SUPPORTED_ALGORITHM.equals(algorithm)) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm = PaymentCryptographyKeyAlgorithm.from(algorithmName);
|
||||
if (algorithm == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyAlgorithm '" + algorithm + "' is not supported, this service makes "
|
||||
+ SUPPORTED_ALGORITHM + " keys", 400);
|
||||
"KeyAlgorithm '" + algorithmName + "' is not supported, this service makes "
|
||||
+ PaymentCryptographyKeyAlgorithm.supportedAll() + " keys", 400);
|
||||
}
|
||||
if (!SUPPORTED_CLASS.equals(keyClass)) {
|
||||
if (!SUPPORTED_CLASS.equals(keyClass) && !ASYMMETRIC_CLASS.equals(keyClass)
|
||||
&& !PUBLIC_KEY_CLASS.equals(keyClass)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyClass '" + keyClass + "' is not supported, this service makes "
|
||||
+ SUPPORTED_CLASS + " keys", 400);
|
||||
+ SUPPORTED_CLASS + ", " + ASYMMETRIC_CLASS + " and " + PUBLIC_KEY_CLASS
|
||||
+ " keys", 400);
|
||||
}
|
||||
// The class says what shape the key has, and the algorithm says what material it
|
||||
// has, so the two must agree: a symmetric algorithm cannot make a key pair, and an
|
||||
// asymmetric one cannot make a symmetric key.
|
||||
boolean symmetric = algorithm.symmetric();
|
||||
if (symmetric && !SUPPORTED_CLASS.equals(keyClass)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyAlgorithm '" + algorithmName + "' is a symmetric algorithm, so the key is a "
|
||||
+ SUPPORTED_CLASS + " and not a " + keyClass, 400);
|
||||
}
|
||||
if (!symmetric && SUPPORTED_CLASS.equals(keyClass)) {
|
||||
throw new AwsException("ValidationException",
|
||||
"KeyAlgorithm '" + algorithmName + "' is an asymmetric algorithm, so the key is a "
|
||||
+ ASYMMETRIC_CLASS + " or a " + PUBLIC_KEY_CLASS + " and not a "
|
||||
+ SUPPORTED_CLASS, 400);
|
||||
}
|
||||
// The usage says what the key is for, so a key without one is not a key: the service
|
||||
// refuses it rather than guessing a purpose for it.
|
||||
String usage = usage(attributes);
|
||||
// The usage binds the key to its purpose, and a key whose algorithm does not serve
|
||||
// that purpose is not one the service makes.
|
||||
String badAlgorithm = PaymentCryptographyKeyAlgorithm.refusal(usage, algorithm);
|
||||
if (badAlgorithm != null) {
|
||||
throw new AwsException("ValidationException", badAlgorithm, 400);
|
||||
}
|
||||
PaymentCryptographyKey key = new PaymentCryptographyKey();
|
||||
key.setKeyId(UUID.randomUUID().toString().replace("-", ""));
|
||||
key.setRegion(region);
|
||||
key.setArn(regionResolver.buildArn(SERVICE, region, "key/" + key.getKeyId()));
|
||||
key.setKeyAlgorithm(algorithm);
|
||||
key.setKeyAlgorithm(algorithm.name());
|
||||
key.setKeyClass(keyClass);
|
||||
key.setKeyUsage(usage(attributes));
|
||||
key.setKeyUsage(usage);
|
||||
key.setDeriveKeyUsage(string(attributes, "DeriveKeyUsage", ""));
|
||||
key.setKeyModesOfUse(modesOfUse);
|
||||
key.setExportable(exportable);
|
||||
key.setEnabled(enabled);
|
||||
key.setTags(new LinkedHashMap<>(tags));
|
||||
key.setKeyState("CREATE_COMPLETE");
|
||||
key.setKeyMaterialHex(PaymentCryptographyCrypto.randomAes256Hex(secureRandom));
|
||||
key.setKeyCheckValue(PaymentCryptographyCrypto.checkValue(key.getKeyMaterialHex()));
|
||||
key.setKeyCheckValueAlgorithm("CMAC");
|
||||
key.setKeyMaterialHex(materialHex);
|
||||
key.setKeyPublicKeyBase64(publicKeyBase64);
|
||||
key.setKeyPrivateKeyBase64(privateKeyBase64);
|
||||
key.setKeyCertificatePem(certificatePem);
|
||||
if (algorithm.symmetric()) {
|
||||
key.setKeyMaterialHex(materialHex != null
|
||||
? materialHex
|
||||
: PaymentCryptographyCrypto.randomMaterialHex(algorithm, secureRandom));
|
||||
key.setKeyCheckValue(
|
||||
PaymentCryptographyCrypto.checkValue(key.getKeyMaterialHex(), algorithm));
|
||||
key.setKeyCheckValueAlgorithm(algorithm.checkValueAlgorithm());
|
||||
} else {
|
||||
// An asymmetric key has no material a check value could be computed from, so it
|
||||
// reports the fixed placeholder a public key does.
|
||||
key.setKeyCheckValue("000000");
|
||||
key.setKeyCheckValueAlgorithm(algorithm.checkValueAlgorithm());
|
||||
if (key.getKeyPublicKeyBase64() == null) {
|
||||
KeyPair pair = algorithm.rsa
|
||||
? PaymentCryptographyKeyPairs.rsa(algorithm.bytes * 8, secureRandom)
|
||||
: PaymentCryptographyKeyPairs.ec(algorithm, secureRandom);
|
||||
key.setKeyPublicKeyBase64(Base64.getEncoder()
|
||||
.encodeToString(pair.getPublic().getEncoded()));
|
||||
if (!PUBLIC_KEY_CLASS.equals(keyClass)) {
|
||||
key.setKeyPrivateKeyBase64(Base64.getEncoder()
|
||||
.encodeToString(pair.getPrivate().getEncoded()));
|
||||
}
|
||||
}
|
||||
}
|
||||
long now = Instant.now().getEpochSecond();
|
||||
key.setCreateTimestamp(now);
|
||||
key.setUsageStartTimestamp(now);
|
||||
keyStore.put(key.getKeyId(), key);
|
||||
keyStore.put(storageKey(region, key.getKeyId()), key);
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The key an identifier names, or null when there is none. */
|
||||
public PaymentCryptographyKey findKey(String region, String identifier) {
|
||||
if (identifier == null || identifier.isEmpty()) {
|
||||
public PaymentCryptographyKey findKey(String region, String identifier) { if (identifier == null || identifier.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
if (identifier.startsWith("alias/")) {
|
||||
@@ -161,7 +268,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
}
|
||||
return null;
|
||||
}
|
||||
PaymentCryptographyKey byId = keyStore.get(identifier).orElse(null);
|
||||
PaymentCryptographyKey byId = findKeyRecord(keyStore, region, identifier);
|
||||
return byId != null && region.equals(byId.getRegion()) ? byId : null;
|
||||
}
|
||||
|
||||
@@ -211,6 +318,10 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
key.setKeyState("DELETE_PENDING");
|
||||
key.setEnabled(false);
|
||||
key.setDeletePendingTimestamp(now);
|
||||
keyStore.delete(storageKey(key.getRegion(), key.getKeyId()));
|
||||
// A key saved before the region became part of its name is under that name too,
|
||||
// and it goes with the key: a record left behind would be a key that was deleted
|
||||
// and still there.
|
||||
keyStore.delete(key.getKeyId());
|
||||
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
|
||||
if (key.getKeyId().equals(alias.getKeyId())) {
|
||||
@@ -229,7 +340,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
* by name and region together.
|
||||
*/
|
||||
public PaymentCryptographyAlias findAlias(String region, String aliasName) {
|
||||
return aliasStore.get(aliasKey(aliasName, region)).orElse(null);
|
||||
return findAliasRecord(region, aliasName);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,7 +358,9 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
keyId = alias == null || alias.getKeyId() == null ? "" : alias.getKeyId();
|
||||
requestContext.pinAliasKeyId(region, aliasName, keyId);
|
||||
}
|
||||
return keyId.isEmpty() ? null : keyStore.get(keyId).orElse(null);
|
||||
// A key saved before the region became part of its name is still found under that
|
||||
// name, so an alias written then keeps working.
|
||||
return keyId.isEmpty() ? null : findKeyRecord(keyStore, region, keyId);
|
||||
}
|
||||
|
||||
/** Points a name at a key. The name must be free in the key's region. */
|
||||
@@ -342,7 +455,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
public synchronized void tag(PaymentCryptographyKey key, Map<String, String> tags) {
|
||||
PaymentCryptographyKey current = liveKey(key);
|
||||
current.getTags().putAll(tags);
|
||||
keyStore.put(current.getKeyId(), current);
|
||||
storeKey(current);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -354,7 +467,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
* read again under the lock and the request fails if it is not there.
|
||||
*/
|
||||
private PaymentCryptographyKey liveKey(PaymentCryptographyKey key) {
|
||||
PaymentCryptographyKey current = keyStore.get(key.getKeyId()).orElse(null);
|
||||
PaymentCryptographyKey current =
|
||||
findKeyRecord(keyStore, key.getRegion(), key.getKeyId());
|
||||
if (current == null) {
|
||||
throw new AwsException("ResourceNotFoundException",
|
||||
"Key " + key.getArn() + " is not found", 400);
|
||||
@@ -362,13 +476,29 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a key back, under the name the store holds it under now.
|
||||
*
|
||||
* <p>A record that was found under the older name is moved to the current one, so the
|
||||
* store holds one record of the key and not two.
|
||||
*
|
||||
* @param key the key to write
|
||||
*/
|
||||
private void storeKey(PaymentCryptographyKey key) {
|
||||
String current = storageKey(key.getRegion(), key.getKeyId());
|
||||
keyStore.put(current, key);
|
||||
if (!key.getKeyId().equals(current)) {
|
||||
keyStore.delete(key.getKeyId());
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes tags from a key, in this region only. */
|
||||
public synchronized void untag(PaymentCryptographyKey key, List<String> tagKeys) {
|
||||
PaymentCryptographyKey current = liveKey(key);
|
||||
for (String tagKey : tagKeys) {
|
||||
current.getTags().remove(tagKey);
|
||||
}
|
||||
keyStore.put(current.getKeyId(), current);
|
||||
storeKey(current);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -393,6 +523,190 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
|
||||
}
|
||||
|
||||
// ---- the replication ------------------------------------------------------
|
||||
|
||||
// ---- the key exchange ----------------------------------------------------
|
||||
|
||||
/**
|
||||
* The usages a key block may carry, and the modes of use each of them has.
|
||||
*
|
||||
* <p>A key block carries the usage of the key it carries, so every usage the service
|
||||
* makes has to have a code, or a key of that usage cannot leave the service and the
|
||||
* counterparty cannot tell what it has.
|
||||
*/
|
||||
private static final Map<String, String> USAGE_NAMES = Map.ofEntries(
|
||||
Map.entry("B0", "TR31_B0_BASE_DERIVATION_KEY"),
|
||||
Map.entry("C0", "TR31_C0_CARD_VERIFICATION_KEY"),
|
||||
Map.entry("D0", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY"),
|
||||
Map.entry("E0", "TR31_E0_EMV_MKEY_APP_CRYPTOGRAMS"),
|
||||
Map.entry("E1", "TR31_E1_EMV_MKEY_CONFIDENTIALITY"),
|
||||
Map.entry("E2", "TR31_E2_EMV_MKEY_INTEGRITY"),
|
||||
Map.entry("E4", "TR31_E4_EMV_MKEY_DYNAMIC_NUMBERS"),
|
||||
Map.entry("E5", "TR31_E5_EMV_MKEY_CARD_PERSONALIZATION"),
|
||||
Map.entry("E6", "TR31_E6_EMV_MKEY_OTHER"),
|
||||
Map.entry("K0", "TR31_K0_KEY_ENCRYPTION_KEY"),
|
||||
Map.entry("K1", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"),
|
||||
Map.entry("M0", "TR31_M0_ISO_16609_MAC_KEY"),
|
||||
Map.entry("M1", "TR31_M1_ISO_9797_1_MAC_KEY"),
|
||||
Map.entry("M3", "TR31_M3_ISO_9797_3_MAC_KEY"),
|
||||
Map.entry("M6", "TR31_M6_ISO_9797_5_CMAC_KEY"),
|
||||
Map.entry("M7", "TR31_M7_HMAC_KEY"),
|
||||
Map.entry("P0", "TR31_P0_PIN_ENCRYPTION_KEY"),
|
||||
Map.entry("P1", "TR31_P1_PIN_GENERATION_KEY"),
|
||||
Map.entry("V1", "TR31_V1_IBM3624_PIN_VERIFICATION_KEY"),
|
||||
Map.entry("V2", "TR31_V2_VISA_PIN_VERIFICATION_KEY"),
|
||||
Map.entry("S0", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE"));
|
||||
|
||||
/** The TR-31 usage code of a usage name, such as {@code D0}. */
|
||||
static String usageCode(String usageName) {
|
||||
for (Map.Entry<String, String> entry : USAGE_NAMES.entrySet()) {
|
||||
if (entry.getValue().equals(usageName)) {
|
||||
return entry.getKey();
|
||||
}
|
||||
}
|
||||
throw new AwsException("ValidationException",
|
||||
"the usage " + usageName + " cannot leave the service: a key block carries one of "
|
||||
+ USAGE_NAMES.keySet(), 400);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a key is an AES key rather than a TDES one.
|
||||
*
|
||||
* <p>The key record knows its algorithm, so the family is read from there and not guessed
|
||||
* from the length of the material, because a 16-byte key is a two-key TDES one and an
|
||||
* AES-128 one, and a 24-byte key is a three-key TDES one and an AES-192 one.
|
||||
*/
|
||||
static boolean isAes(PaymentCryptographyKey key) {
|
||||
PaymentCryptographyKeyAlgorithm algorithm =
|
||||
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
|
||||
return algorithm != null && algorithm.aes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The algorithm byte of a key: {@code A} for an AES key and {@code T} for a TDES one.
|
||||
*
|
||||
* <p>The key record knows its algorithm, so the byte is read from there and not guessed from
|
||||
* the length of the material, because a TDES key and an AES key of the same length are
|
||||
* different keys.
|
||||
*/
|
||||
static String algorithmByte(PaymentCryptographyKey key) {
|
||||
return "AES_256".equals(key.getKeyAlgorithm()) || "AES_192".equals(key.getKeyAlgorithm())
|
||||
|| "AES_128".equals(key.getKeyAlgorithm()) ? "A" : "T";
|
||||
}
|
||||
|
||||
/** The usage name of a TR-31 usage code, such as {@code TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY}. */
|
||||
static String usageName(String usageCode) {
|
||||
String usage = USAGE_NAMES.get(usageCode);
|
||||
if (usage == null) {
|
||||
throw new AwsException("ValidationException",
|
||||
"the usage " + usageCode + " of the key block is not one this service serves: "
|
||||
+ USAGE_NAMES.keySet(), 400);
|
||||
}
|
||||
return usage;
|
||||
}
|
||||
|
||||
/**
|
||||
* The modes of use a mode of use code of a key block stands for.
|
||||
*
|
||||
* <p>A key encryption key wraps and unwraps rather than encrypts and decrypts, so the
|
||||
* same character means the other modes for one.
|
||||
*
|
||||
* @param mode the mode of use character of the block
|
||||
* @param isKek true when the block carries a key encryption key
|
||||
*/
|
||||
static Map<String, Boolean> modesFor(String mode, boolean isKek) {
|
||||
return switch (mode) {
|
||||
case "B" -> isKek
|
||||
? Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE)
|
||||
: Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE);
|
||||
case "E" -> isKek
|
||||
? Map.of("Wrap", Boolean.TRUE)
|
||||
: Map.of("Encrypt", Boolean.TRUE);
|
||||
case "D" -> isKek
|
||||
? Map.of("Unwrap", Boolean.TRUE)
|
||||
: Map.of("Decrypt", Boolean.TRUE);
|
||||
case "G" -> Map.of("Generate", Boolean.TRUE);
|
||||
case "V" -> Map.of("Verify", Boolean.TRUE);
|
||||
case "C" -> Map.of("Generate", Boolean.TRUE, "Verify", Boolean.TRUE);
|
||||
case "X" -> Map.of("DeriveKey", Boolean.TRUE);
|
||||
case "N" -> Map.of("NoRestrictions", Boolean.TRUE);
|
||||
default -> throw new AwsException("ValidationException",
|
||||
"the mode of use " + mode + " of the key block is not one this service serves", 400);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode of use character a key block carries.
|
||||
*
|
||||
* <p>The character is read off the key's own modes, because that is what it says: a key
|
||||
* that encrypts and decrypts is a {@code B}, one that only encrypts is an {@code E}. A key
|
||||
* encryption key wraps and unwraps rather than encrypts and decrypts, so its modes are read
|
||||
* that way.
|
||||
*
|
||||
* @param key the key the block carries
|
||||
* @return the character
|
||||
*/
|
||||
static String modeCode(PaymentCryptographyKey key) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
boolean isKek = isKeyEncryptionKey(key.getKeyUsage());
|
||||
boolean encrypt = isKek
|
||||
? enabled(modes, "Wrap") || enabled(modes, "Encrypt")
|
||||
: enabled(modes, "Encrypt");
|
||||
boolean decrypt = isKek
|
||||
? enabled(modes, "Unwrap") || enabled(modes, "Decrypt")
|
||||
: enabled(modes, "Decrypt");
|
||||
boolean generate = enabled(modes, "Generate");
|
||||
boolean verify = enabled(modes, "Verify");
|
||||
boolean derive = enabled(modes, "DeriveKey");
|
||||
if (encrypt && decrypt) {
|
||||
return "B";
|
||||
}
|
||||
if (encrypt) {
|
||||
return "E";
|
||||
}
|
||||
if (decrypt) {
|
||||
return "D";
|
||||
}
|
||||
if (generate && verify) {
|
||||
return "C";
|
||||
}
|
||||
if (generate) {
|
||||
return "G";
|
||||
}
|
||||
if (verify) {
|
||||
return "V";
|
||||
}
|
||||
if (derive) {
|
||||
return "X";
|
||||
}
|
||||
return "N";
|
||||
}
|
||||
|
||||
/** Whether a mode of use is on. A key with no modes at all has every one of them. */
|
||||
private static boolean enabled(Map<String, Boolean> modes, String mode) {
|
||||
return modes == null || Boolean.TRUE.equals(modes.get(mode));
|
||||
}
|
||||
|
||||
/** Whether a usage is a key encryption key's, whose modes wrap and unwrap. */
|
||||
static boolean isKeyEncryptionKey(String usageName) {
|
||||
return "TR31_K0_KEY_ENCRYPTION_KEY".equals(usageName)
|
||||
|| "TR31_K1_KEY_BLOCK_PROTECTION_KEY".equals(usageName);
|
||||
}
|
||||
|
||||
/** Whether a key may wrap another key. */
|
||||
static boolean mayWrap(PaymentCryptographyKey key) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
return modes == null || Boolean.TRUE.equals(modes.get("Wrap"))
|
||||
|| Boolean.TRUE.equals(modes.get("Encrypt"));
|
||||
}
|
||||
|
||||
/** Whether a key may unwrap another key. */
|
||||
static boolean mayUnwrap(PaymentCryptographyKey key) {
|
||||
Map<String, Boolean> modes = key.getKeyModesOfUse();
|
||||
return modes == null || Boolean.TRUE.equals(modes.get("Unwrap"))
|
||||
|| Boolean.TRUE.equals(modes.get("Decrypt"));
|
||||
}
|
||||
|
||||
// ---- helpers ------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -437,6 +751,52 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
return regionResolver.buildArn(SERVICE, region, "alias/" + alias);
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage key of a key.
|
||||
*
|
||||
* <p>The region is part of it, because a multi-region key has one identifier in several
|
||||
* regions, and each of them is a key of its own region.
|
||||
*/
|
||||
private static String storageKey(String region, String keyId) {
|
||||
return region + "\u0000" + keyId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a store holds under the name it was saved under.
|
||||
*
|
||||
* <p>A store written before the region became part of the name holds its keys under
|
||||
* their identifier alone, and its aliases under their name alone. A record saved then is
|
||||
* still found here, so a store that was not emptied keeps working.
|
||||
*
|
||||
* @param store the store to look in
|
||||
* @param region the region the key is in
|
||||
* @param keyId the key's identifier
|
||||
* @param <T> what the store holds
|
||||
* @return the key, or null when the store holds none
|
||||
*/
|
||||
private static <T> T findKeyRecord(StorageBackend<String, T> store, String region,
|
||||
String keyId) {
|
||||
Optional<T> current = store.get(storageKey(region, keyId));
|
||||
if (current.isPresent()) {
|
||||
return current.get();
|
||||
}
|
||||
return store.get(keyId).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The alias a store holds under the name it was saved under.
|
||||
*
|
||||
* <p>An alias saved before the region became part of the name is still found here.
|
||||
*
|
||||
* @param region the region the alias is in
|
||||
* @param aliasName the alias's name
|
||||
* @return the alias, or null when the store holds none
|
||||
*/
|
||||
private PaymentCryptographyAlias findAliasRecord(String region, String aliasName) {
|
||||
PaymentCryptographyAlias current = aliasStore.get(aliasKey(aliasName, region)).orElse(null);
|
||||
return current != null ? current : aliasStore.get(aliasName).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The storage key of an alias.
|
||||
*
|
||||
@@ -471,4 +831,9 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
|
||||
keyStore.clear();
|
||||
aliasStore.clear();
|
||||
}
|
||||
|
||||
/** The key store, for the tests. */
|
||||
Optional<PaymentCryptographyKey> storedKey(String region, String keyId) {
|
||||
return keyStore.get(storageKey(region, keyId));
|
||||
}
|
||||
}
|
||||
+57
@@ -29,6 +29,11 @@ public class PaymentCryptographyKey {
|
||||
private String keyAlgorithm;
|
||||
private String keyClass;
|
||||
private String keyUsage;
|
||||
/**
|
||||
* The usage a key derives other keys for, when the key is a derivation key.
|
||||
* Empty for a key that derives nothing.
|
||||
*/
|
||||
private String deriveKeyUsage;
|
||||
private Map<String, Boolean> keyModesOfUse = new HashMap<>();
|
||||
private String keyOrigin = "AWS_PAYMENT_CRYPTOGRAPHY";
|
||||
private String keyCheckValue;
|
||||
@@ -37,11 +42,38 @@ public class PaymentCryptographyKey {
|
||||
private boolean exportable;
|
||||
private boolean enabled = true;
|
||||
private String keyMaterialHex;
|
||||
/**
|
||||
* The public half of an asymmetric key, base64 of the DER of its
|
||||
* SubjectPublicKeyInfo. Empty for a symmetric key, which has one blob of
|
||||
* material instead.
|
||||
*/
|
||||
private String keyPublicKeyBase64;
|
||||
/**
|
||||
* The private half of an asymmetric key, base64 of the DER of its PKCS#8
|
||||
* encoding. Empty for a public key, which has no private half.
|
||||
*
|
||||
* <p>It is not written to the store, for the same reason the symmetric
|
||||
* material is not: a private key in clear in the data directory is a
|
||||
* secret on disk.
|
||||
*/
|
||||
private String keyPrivateKeyBase64;
|
||||
/**
|
||||
* The certificate an imported public key arrived with, in PEM. A key the
|
||||
* service made has none, and gets a self-signed one when one is asked for.
|
||||
*/
|
||||
private String keyCertificatePem;
|
||||
private long createTimestamp;
|
||||
private long usageStartTimestamp;
|
||||
private long deletePendingTimestamp;
|
||||
private long deleteTimestamp;
|
||||
private Map<String, String> tags = new HashMap<>();
|
||||
/** The region of the primary of a multi-region key, and its own region otherwise. */
|
||||
|
||||
/** The regions a multi-region key is in, besides the primary's. */
|
||||
|
||||
/** Whether this record is the primary of a multi-region key or a replica of one. */
|
||||
|
||||
/** Whether the key took the account's default replication regions. */
|
||||
|
||||
public String getKeyId() { return keyId; }
|
||||
public void setKeyId(String keyId) { this.keyId = keyId; }
|
||||
@@ -61,6 +93,9 @@ public class PaymentCryptographyKey {
|
||||
public String getKeyUsage() { return keyUsage; }
|
||||
public void setKeyUsage(String keyUsage) { this.keyUsage = keyUsage; }
|
||||
|
||||
public String getDeriveKeyUsage() { return deriveKeyUsage; }
|
||||
public void setDeriveKeyUsage(String deriveKeyUsage) { this.deriveKeyUsage = deriveKeyUsage; }
|
||||
|
||||
public Map<String, Boolean> getKeyModesOfUse() { return keyModesOfUse; }
|
||||
public void setKeyModesOfUse(Map<String, Boolean> keyModesOfUse) { this.keyModesOfUse = keyModesOfUse; }
|
||||
|
||||
@@ -89,6 +124,28 @@ public class PaymentCryptographyKey {
|
||||
public String getKeyMaterialHex() { return keyMaterialHex; }
|
||||
public void setKeyMaterialHex(String keyMaterialHex) { this.keyMaterialHex = keyMaterialHex; }
|
||||
|
||||
public String getKeyPublicKeyBase64() { return keyPublicKeyBase64; }
|
||||
public void setKeyPublicKeyBase64(String keyPublicKeyBase64) {
|
||||
this.keyPublicKeyBase64 = keyPublicKeyBase64;
|
||||
}
|
||||
|
||||
/**
|
||||
* The private half of an asymmetric key.
|
||||
*
|
||||
* <p>It is held by the key and never written to the store, like the
|
||||
* symmetric material.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getKeyPrivateKeyBase64() { return keyPrivateKeyBase64; }
|
||||
public void setKeyPrivateKeyBase64(String keyPrivateKeyBase64) {
|
||||
this.keyPrivateKeyBase64 = keyPrivateKeyBase64;
|
||||
}
|
||||
|
||||
public String getKeyCertificatePem() { return keyCertificatePem; }
|
||||
public void setKeyCertificatePem(String keyCertificatePem) {
|
||||
this.keyCertificatePem = keyCertificatePem;
|
||||
}
|
||||
|
||||
public long getCreateTimestamp() { return createTimestamp; }
|
||||
public void setCreateTimestamp(long createTimestamp) { this.createTimestamp = createTimestamp; }
|
||||
|
||||
|
||||
Reference in new issue
Block a user