mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(paymentcryptography): the data plane as a service of its own (#7396)
* feat(paymentcryptography): the data plane as a service of its own docs(paymentcryptography): the data plane has a page of its own fix(paymentcryptography): a MAC under a three-key Triple DES key is computed test(paymentcryptography): a key of another purpose does not encrypt data feat(paymentcryptography): the data plane's IAM is generated fix(paymentcryptography): a DUKPT MAC needs a base derivation key fix(paymentcryptography): a key whose material is not held is refused docs(paymentcryptography): the data plane's example runs test(paymentcryptography): the data plane through the AWS SDK test(paymentcryptography): the data plane through the AWS CLI fix(paymentcryptography): the CLI test removes the keys it makes docs(compat): the AWS CLI suite names the data plane test(paymentcryptography): the route is read as the registry reads it test(paymentcryptography): the request names its method and its URI fix(paymentcryptography): the cipher pads no data fix(paymentcryptography): the data plane takes the service scope fix(paymentcryptography): a MAC length that is not a number is refused docs(paymentcryptography): the data plane says the cipher pads no data fix(paymentcryptography): the data plane ciphers with Triple DES as well fix(paymentcryptography): the scope alias names the model's scope fix(paymentcryptography): the Triple DES cipher is BouncyCastle's fix(paymentcryptography): the usage and the blob keep their comments fix(paymentcryptography): a key's family is read from its algorithm fix(paymentcryptography): the cipher reads the vector through one helper test(paymentcryptography): the keys are built by one builder fix(paymentcryptography): the data plane checks the model's rules fix(paymentcryptography): the Triple DES check value is BouncyCastle's fix(paymentcryptography): the SDK names it TDES_2_KEY docs(contributing): the ciphers come from BouncyCastle refactor(paymentcryptography): the model owns the request shapes refactor(paymentcryptography): the ciphers are BouncyCastle's test(compat): one helper makes a key of either algorithm docs(contributing): the cipher rule comes out fix(paymentcryptography): the refusals are the model's refactor(paymentcryptography): the ciphers are one helper each refactor(paymentcryptography): the generators share the helper docs(paymentcryptography): the javadocs name both ciphers test(aws): the moved constants read from the shared helper fix(paymentcryptography): the deprecated cipher constructors go chore(paymentcryptography): the duplicate import goes test(paymentcryptography): the DUKPT vectors the standard publishes fix(paymentcryptography): the DUKPT refusal is the derivation's docs(paymentcryptography): the retail MAC is over a double-length key fix(paymentcryptography): the ISO 9797-1 MAC pads only a partial block refactor(paymentcryptography): the refusals the model already makes chore(aws): the routes are generated from the models again * chore(aws): the IAM resources are generated again
This commit is contained in:
1 parent
ae196fb9ac
commit
4617e4a4f8
45 files changed
+3942
-356
No files matched your search
@@ -57,6 +57,15 @@ class CredentialScopeAliasTest {
|
||||
assertEquals("sso", catalog.canonicalCredentialScope("awsssoportal"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void paymentCryptographyDataAliasNormalisesToPaymentCryptography() {
|
||||
// The Payment Cryptography data plane signs as payment-cryptography-data, but its actions
|
||||
// live under the payment-cryptography: namespace (payment-cryptography:EncryptData and
|
||||
// peers in the Service Authorization Reference), so enforcement has to resolve it there
|
||||
// rather than invent payment-cryptography-data:.
|
||||
assertEquals("payment-cryptography", catalog.canonicalCredentialScope("payment-cryptography-data"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalScopeIsUnchanged() {
|
||||
assertEquals("s3", catalog.canonicalCredentialScope("s3"));
|
||||
@@ -89,7 +98,8 @@ class CredentialScopeAliasTest {
|
||||
.filter(scope -> !scope.equals(catalog.canonicalCredentialScope(scope)))
|
||||
.collect(Collectors.toMap(scope -> scope, catalog::canonicalCredentialScope));
|
||||
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso", "monitoring", "cloudwatch"), rewritten);
|
||||
assertEquals(Map.of("s3express", "s3", "iot-jobs-data", "iot", "awsssoportal", "sso",
|
||||
"monitoring", "cloudwatch", "payment-cryptography-data", "payment-cryptography"), rewritten);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -88,6 +89,22 @@ class IamRestRoutesTest {
|
||||
assertEquals(Optional.of("GetThingVersion"), get("/things/web:3"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The values the path holds are read under the names the route gives its labels, so that a
|
||||
* service which names a resource in the path reads the resource from it. A label holding an
|
||||
* ARN spans the slashes the ARN holds, so the route names it with a {@code +}.
|
||||
*/
|
||||
@Test
|
||||
void theValuesThePathHoldsAreReadUnderTheNamesItsLabelsCarry() {
|
||||
IamRestRoutes table = routes(ROUTES.replace("\"/things/{ThingName}\"", "\"/keys/{KeyIdentifier+}\"")
|
||||
.replace("\"GetThing\"", "\"GetKey\""));
|
||||
assertEquals(Map.of("KeyIdentifier", "arn:aws:service:region:account:key/abc"),
|
||||
table.match("svc", "GET", "/keys/arn:aws:service:region:account:key/abc", null)
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of()));
|
||||
assertEquals(Map.of(), table.match("svc", "GET", "/things/web", null)
|
||||
.map(IamRestRoutes.Match::labels).orElse(Map.of()));
|
||||
}
|
||||
|
||||
/** A greedy label takes the rest of the path, one segment or more, and ranks below a literal there. */
|
||||
@Test
|
||||
void aGreedyLabelTakesTheRestOfThePath() {
|
||||
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The data plane's requests are authorized by the action of their route, and a policy that
|
||||
* denies that action is enforced however the key is named.
|
||||
*
|
||||
* <p>The key of a data-plane request may be named by its identifier or by its ARN, and a
|
||||
* client sends an ARN with its colon and slash encoded. The router rewrites the request onto
|
||||
* the internal prefix, and the IAM rules are matched on the rewritten path, which is decoded.
|
||||
* So the ARN arrives as a path that holds a real slash, and a rule that stopped at the first
|
||||
* slash would not match it: the request would resolve to no action, and the denial would not
|
||||
* be enforced.
|
||||
*
|
||||
* <p>The rest of the repository holds a request to its standard: a request is refused however
|
||||
* it is sent. This is that standard for the data plane.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class PaymentCryptographyDataPlaneIamEnforcementTest {
|
||||
|
||||
/** The key every test works with. */
|
||||
private String keyArn;
|
||||
|
||||
private String keyId;
|
||||
|
||||
/** The caller whose policy the test writes. */
|
||||
private UserCredentials caller;
|
||||
|
||||
/** The account the administrator acts in. */
|
||||
private static final String ADMIN = "test";
|
||||
|
||||
/** The caller of each test, with a name of its own. */
|
||||
private String callerName;
|
||||
|
||||
/** The key the MAC operations use, which is a MAC key and not a data-encryption one. */
|
||||
private String macKeyArn;
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
private final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@BeforeEach
|
||||
void createTheKeyAndTheCaller() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
keyArn = given().contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
|
||||
.header("Authorization", auth(ADMIN, "payment-cryptography"))
|
||||
.body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Encrypt\":true,\"Decrypt\":true}},\"Exportable\":true}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
keyId = keyArn.substring(keyArn.lastIndexOf('/') + 1);
|
||||
macKeyArn = given().contentType("application/x-amz-json-1.0")
|
||||
.header("X-Amz-Target", "PaymentCryptographyControlPlane.CreateKey")
|
||||
.header("Authorization", auth(ADMIN, "payment-cryptography"))
|
||||
.body("{\"KeyAttributes\":{\"KeyAlgorithm\":\"AES_256\",\"KeyClass\":\"SYMMETRIC_KEY\","
|
||||
+ "\"KeyUsage\":\"TR31_M6_ISO_9797_5_CMAC_KEY\","
|
||||
+ "\"KeyModesOfUse\":{\"Generate\":true,\"Verify\":true}},\"Exportable\":true}")
|
||||
.when().post("/")
|
||||
.then().statusCode(200)
|
||||
.extract().path("Key.KeyArn");
|
||||
callerName = "payment-cryptography-data-" + Long.toString(System.nanoTime(), 36);
|
||||
caller = EnforcementFixtures.createUser(cleanup, port(), auth(ADMIN, "iam"), callerName);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsIdentifier() {
|
||||
denyEncryptData();
|
||||
assertEquals(403, encrypt("/keys/" + keyId + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsArn() {
|
||||
denyEncryptData();
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialIsEnforcedWhenTheKeyIsNamedByItsEncodedArn() {
|
||||
denyEncryptData();
|
||||
String encoded = keyArn.replace(":", "%3A").replace("/", "%2F");
|
||||
assertEquals(403, encrypt("/keys/" + encoded + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallerWithNoPermissionIsRefused() {
|
||||
// A policy with no statement at all: the caller may do nothing.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":[]}");
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestIsServedWhenTheActionIsAllowed() {
|
||||
// The action is allowed, so the request is served and the answer carries the ciphertext.
|
||||
allowEncryptData();
|
||||
ValidatableResponse response = encrypt("/keys/" + keyArn + "/encrypt");
|
||||
assertEquals(200, response.extract().statusCode());
|
||||
response.body("CipherText", notNullValue());
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse encrypt(String path) {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"PlainText\":\"" + "00".repeat(16) + "\","
|
||||
+ "\"EncryptionAttributes\":{\"Symmetric\":{\"Mode\":\"CBC\"}}}")
|
||||
.when().post(path)
|
||||
.then();
|
||||
}
|
||||
|
||||
/** A policy that allows the one action of the route. */
|
||||
private void allowEncryptData() {
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
}
|
||||
|
||||
/** A policy that allows everything and denies the one action of the route. */
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenThatKeyIsNamed() {
|
||||
// The request names the key, so the action is checked on that key and a denial
|
||||
// limited to it holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt").extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnOneKeyIsEnoughWhenThatKeyIsNamed() {
|
||||
// The policy allows the one key and nothing else, and the request names it.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:*\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
ValidatableResponse response = encrypt("/keys/" + keyArn + "/encrypt");
|
||||
assertEquals(200, response.extract().statusCode());
|
||||
response.body("CipherText", notNullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIsReadFromThePathWhicheverWayTheRouteIsSpelled() {
|
||||
// The route may end in a slash, and the key is named in the path either way, so the
|
||||
// action is checked on the key and a denial limited to it holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, encrypt("/keys/" + keyArn + "/encrypt/").extract().statusCode());
|
||||
}
|
||||
|
||||
private void denyEncryptData() {
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:EncryptData\","
|
||||
+ "\"Resource\":\"*\"}]}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenTheMacNamesIt() {
|
||||
// The MAC names its key in the body, and the action is checked on that key.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:GenerateMac\","
|
||||
+ "\"Resource\":\"" + macKeyArn + "\"}]}");
|
||||
|
||||
assertEquals(403, generateMac().extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowOnOneKeyIsEnoughWhenTheMacNamesIt() {
|
||||
// The policy allows the one key and nothing else, and the MAC names it.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"payment-cryptography:*\","
|
||||
+ "\"Resource\":\"" + macKeyArn + "\"}]}");
|
||||
|
||||
assertEquals(200, generateMac().extract().statusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenialOnOneKeyIsEnforcedWhenTheReEncryptionNamesIt() {
|
||||
// The re-encryption names the incoming key in the path and the outgoing one in the body,
|
||||
// and the action is checked on both, so a denial on either of them holds.
|
||||
EnforcementFixtures.putUserPolicy(port(), auth(ADMIN, "iam"), callerName, "p",
|
||||
"{\"Version\":\"2012-10-17\",\"Statement\":["
|
||||
+ "{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"payment-cryptography:ReEncryptData\","
|
||||
+ "\"Resource\":\"" + keyArn + "\"}]}");
|
||||
|
||||
// The denied key is the one the path names, and the body names another.
|
||||
assertEquals(403, reEncrypt("/keys/" + keyArn + "/reencrypt", macKeyArn).extract().statusCode());
|
||||
// The denied key is the one the body names, and the path names another.
|
||||
assertEquals(403, reEncrypt("/keys/" + macKeyArn + "/reencrypt", keyArn).extract().statusCode());
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse generateMac() {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"KeyIdentifier\":\"" + macKeyArn + "\",\"MessageData\":\"" + "00".repeat(16) + "\","
|
||||
+ "\"GenerationAttributes\":{\"Algorithm\":\"CMAC\"}}")
|
||||
.when().post("/mac/generate")
|
||||
.then();
|
||||
}
|
||||
|
||||
/** The request is made as the caller, whose policy is what is under test. */
|
||||
private ValidatableResponse reEncrypt(String path, String outgoingKeyArn) {
|
||||
return given().contentType("application/json")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "payment-cryptography"))
|
||||
.body("{\"OutgoingKeyIdentifier\":\"" + outgoingKeyArn + "\",\"CipherText\":\"" + "00".repeat(16) + "\"}")
|
||||
.when().post(path)
|
||||
.then();
|
||||
}
|
||||
|
||||
private static int port() {
|
||||
return baseUri.getPort();
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The data plane's routes are checked as the actions AWS checks them for, however the key is
|
||||
* named.
|
||||
*
|
||||
* <p>The key of a data-plane request may be named by its identifier or by its ARN, and an ARN
|
||||
* carries a slash that a client sends encoded. The router rewrites the request onto the
|
||||
* internal prefix, and the IAM rules are matched on the rewritten path, which is decoded. So
|
||||
* the ARN arrives as a path that holds a real slash, and a rule that stops at the first slash
|
||||
* would not match it: the request would resolve to no action, and a policy that denies the
|
||||
* action would not be enforced.
|
||||
*
|
||||
* <p>The rest of the repository holds a request to its standard: a request is refused however
|
||||
* it is sent. This is that standard for the data plane.
|
||||
*/
|
||||
class PaymentCryptographyDataPlaneIamRouteTest {
|
||||
|
||||
private final IamActionRegistry registry = new IamActionRegistry();
|
||||
|
||||
private static final String KEY_ID = "1234abcd-12ab-34cd-56ef-1234567890ab";
|
||||
|
||||
private static final String KEY_ARN =
|
||||
"arn:aws:payment-cryptography:us-east-1:000000000000:key/" + KEY_ID;
|
||||
|
||||
@Test
|
||||
void theKeyIdentifierResolvesToItsAction() {
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeyArnResolvesToTheSameAction() {
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEncodedKeyArnResolvesToTheSameAction() {
|
||||
// The router matches the rewritten path decoded, so the encoded slash of the ARN is a
|
||||
// real slash by the time the rule is matched.
|
||||
String encoded = KEY_ARN.replace(":", "%3A").replace("/", "%2F");
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/encrypt"));
|
||||
assertEquals("payment-cryptography:DecryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/decrypt"));
|
||||
assertEquals("payment-cryptography:ReEncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + encoded + "/reencrypt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOtherOperationsResolveToTheirActions() {
|
||||
assertEquals("payment-cryptography:GenerateMac", resolve("/_paymentcryptography/mac/generate"));
|
||||
assertEquals("payment-cryptography:VerifyMac", resolve("/_paymentcryptography/mac/verify"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRoutesAreReadUnderTheServicesScope() {
|
||||
// A client of the data plane signs for the service, which is one scope for both of
|
||||
// its planes, and a client that signs for the data plane's own scope is served under
|
||||
// that scope too (see CredentialScopeAliasTest), so the routes are read under the one
|
||||
// scope the actions live in.
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ID + "/encrypt"));
|
||||
assertEquals("payment-cryptography:EncryptData",
|
||||
resolve("/_paymentcryptography/keys/" + KEY_ARN + "/encrypt"));
|
||||
}
|
||||
|
||||
/** The action the registry resolves for a POST to the path, for the service's scope. */
|
||||
private String resolve(String path) {
|
||||
return resolve("payment-cryptography", path);
|
||||
}
|
||||
|
||||
/** The action the registry resolves for a POST to the path. */
|
||||
private String resolve(String scope, String path) {
|
||||
ContainerRequestContext ctx = mock(ContainerRequestContext.class);
|
||||
UriInfo uriInfo = mock(UriInfo.class);
|
||||
when(uriInfo.getPath()).thenReturn(path);
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566" + path));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(ctx.getUriInfo()).thenReturn(uriInfo);
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
return registry.resolveRoute(scope, ctx);
|
||||
}
|
||||
}
|
||||
@@ -1285,6 +1285,11 @@ class ResourceArnBuilderTest {
|
||||
void paymentCryptographyResolvesAnAliasToTheKeyItPointsAt() {
|
||||
ResourceArnBuilder reading = reading(stored("payment-cryptography", "key", "alias/team/card-key", PC_KEY_ARN));
|
||||
|
||||
// The route its resources are read from is the one the request's path matches, so the
|
||||
// request names its method and its URI.
|
||||
when(ctx.getMethod()).thenReturn("POST");
|
||||
when(uriInfo.getRequestUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
when(uriInfo.getBaseUri()).thenReturn(URI.create("http://localhost:4566/"));
|
||||
setJsonBody("{\"KeyIdentifier\":\"alias/team/card-key\"}");
|
||||
assertEquals(List.of(PC_KEY_ARN),
|
||||
reading.buildResources("payment-cryptography", "payment-cryptography:GetKey", ctx,
|
||||
|
||||
+553
@@ -0,0 +1,553 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.storage.InMemoryStorage;
|
||||
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PaymentCryptographyCryptoHandlerTest {
|
||||
|
||||
private PaymentCryptographyService service;
|
||||
private PaymentCryptographyCryptoHandler handler;
|
||||
private InMemoryStorage<String, PaymentCryptographyKey> keys;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
keys = new InMemoryStorage<>();
|
||||
service = new PaymentCryptographyService(
|
||||
keys,
|
||||
new InMemoryStorage<>(),
|
||||
new RegionResolver("us-east-1", "000000000000"));
|
||||
handler = new PaymentCryptographyCryptoHandler(service);
|
||||
}
|
||||
|
||||
/** A TDES key, which is what the ISO 9797-1 MAC is computed under. */
|
||||
private PaymentCryptographyKey createTdesKey(String... modes) {
|
||||
return createKeyOf("TDES_2KEY", "TR31_M6_ISO_9797_5_CMAC_KEY", modes);
|
||||
}
|
||||
|
||||
private PaymentCryptographyKey createTdesKeyOf(String algorithm, String... modes) {
|
||||
return createKeyOf(algorithm, "TR31_M6_ISO_9797_5_CMAC_KEY", modes);
|
||||
}
|
||||
|
||||
/** A Triple DES key of the data encryption usage, which the data plane ciphers with. */
|
||||
private PaymentCryptographyKey createTdesDataKey(String algorithm, String... modes) {
|
||||
return createKeyOf(algorithm, "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", modes);
|
||||
}
|
||||
|
||||
private PaymentCryptographyKey createKey(String... modes) {
|
||||
return createKeyOf("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", modes);
|
||||
}
|
||||
|
||||
/** A key of the algorithm and the usage a test asks for. */
|
||||
private PaymentCryptographyKey createKeyOf(String algorithm, String usage, String... modes) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", usage);
|
||||
Map<String, Boolean> declared = new LinkedHashMap<>();
|
||||
for (String mode : modes) {
|
||||
declared.put(mode, Boolean.TRUE);
|
||||
}
|
||||
return service.createKey("us-east-1", attributes, declared, true, true, Map.of());
|
||||
}
|
||||
|
||||
private static byte[] hexBytes(String hex) {
|
||||
return PaymentCryptographyCrypto.fromHex(hex);
|
||||
}
|
||||
|
||||
/** The MAC attributes of the ISO 9797-1 algorithm 3, the retail MAC. */
|
||||
private static JsonNode iso9797() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.put("Algorithm", "ISO9797_ALGORITHM3");
|
||||
return attributes;
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
return PaymentCryptographyCrypto.toHex(bytes).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
/** A request body, built as a map so the test says what it means. */
|
||||
private JsonNode request(Map<String, Object> members) {
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
members.forEach((name, value) -> {
|
||||
if (value instanceof JsonNode json) {
|
||||
node.set(name, json);
|
||||
} else if (value instanceof Integer number) {
|
||||
node.put(name, number);
|
||||
} else {
|
||||
node.put(name, String.valueOf(value));
|
||||
}
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
/** The encryption attributes of a request that encrypts in CBC mode. */
|
||||
private JsonNode cbc() {
|
||||
ObjectNode symmetric = mapper.createObjectNode();
|
||||
symmetric.put("Mode", "CBC");
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set("Symmetric", symmetric);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** The CBC attributes with the vector the request names. */
|
||||
private JsonNode cbcWithVector(String vector) {
|
||||
ObjectNode symmetric = mapper.createObjectNode();
|
||||
symmetric.put("Mode", "CBC");
|
||||
symmetric.put("InitializationVector", vector);
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set("Symmetric", symmetric);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyEncryptsAndDecrypts() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"PlainText", hex("hello, world!!!!".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(key.getArn(), encrypted.get("KeyArn"));
|
||||
assertEquals(key.getKeyCheckValue(), encrypted.get("KeyCheckValue"));
|
||||
String cipherText = (String) encrypted.get("CipherText");
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(hex("hello, world!!!!".getBytes()), decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCiphertextIsNotThePlaintextAndTheVectorTravelsBesideIt() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
String plain = hex("the same data!!!".getBytes());
|
||||
|
||||
String first = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
String second = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
assertNotEquals(plain, first);
|
||||
// The vector is not in the ciphertext, so two encryptions under the same vector are
|
||||
// the same ciphertext, and two under different vectors are not.
|
||||
assertEquals(first, second, "the same vector gives the same ciphertext");
|
||||
String other = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plain,
|
||||
"EncryptionAttributes", cbcWithVector("00112233445566778899aabbccddeeff"))),
|
||||
"us-east-1").get("CipherText");
|
||||
assertNotEquals(first, other, "another vector gives another ciphertext");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatMayNotEncryptRefuses() {
|
||||
PaymentCryptographyKey key = createKey("Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyOfAnotherPurposeRefuses() {
|
||||
// A PIN encryption key may encrypt a PIN block and nothing else, so it does not encrypt
|
||||
// arbitrary data, and a MAC key does not either.
|
||||
PaymentCryptographyKey pin =
|
||||
createKeyOf("AES_256", "TR31_P0_PIN_ENCRYPTION_KEY", "Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", pin.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
|
||||
PaymentCryptographyKey mac = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refusedMac = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", mac.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refusedMac.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyIdentifierThatNamesNoKeyIsRefused() {
|
||||
// The identifier of a key on its own is not the ARN of a key nor an alias, and the
|
||||
// model says so, so the request is refused before it looks for the key.
|
||||
PaymentCryptographyKey key = createTdesKey("Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getKeyId(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyThatIsNotThereIsNotFound() {
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", "arn:aws:payment-cryptography:us-east-1:000000000000:key/"
|
||||
+ "1234abcd1234abcd",
|
||||
"PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ResourceNotFoundException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacIsComputedAndVerified() {
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", iso9797())), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", iso9797())), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacUnderAThreeKeyTdesKeyIsComputedAndVerified() {
|
||||
// The ISO 9797 MACs are defined over Triple DES, and the cipher takes the three keys
|
||||
// a three-key key holds, so such a key computes a MAC rather than failing.
|
||||
PaymentCryptographyKey key = createTdesKeyOf("TDES_3KEY", "Generate", "Verify");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", iso9797())), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", iso9797())), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacOfAnotherMessageIsNotValid() {
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
String mac = (String) handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"MessageData", hex("a message".getBytes()),
|
||||
"GenerationAttributes", iso9797())), "us-east-1").get("Mac");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(),
|
||||
"MessageData", hex("another message".getBytes()),
|
||||
"Mac", mac,
|
||||
"VerificationAttributes", iso9797())), "us-east-1"));
|
||||
|
||||
assertEquals("VerificationFailedException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTripleDesKeyEncryptsAndDecrypts() {
|
||||
// The reference ciphers with Triple DES as well as with AES, and the block follows the
|
||||
// key's cipher: eight bytes for Triple DES.
|
||||
PaymentCryptographyKey key = createTdesDataKey("TDES_2KEY", "Encrypt", "Decrypt");
|
||||
String plaintext = "0011223344556677";
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plaintext,
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
String cipherText = (String) encrypted.get("CipherText");
|
||||
|
||||
assertEquals(plaintext.length(), cipherText.length());
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(plaintext, decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTripleDesPlaintextThatDoesNotFillWholeBlocksIsRefused() {
|
||||
// The block of a Triple DES key is eight bytes, so twelve bytes do not fill one.
|
||||
PaymentCryptographyKey key = createTdesDataKey("TDES_2KEY", "Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00112233445566778899ab",
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("8 bytes (one TDES block)"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlaintextThatDoesNotFillWholeBlocksIsRefused() {
|
||||
// The cipher pads no data, so the caller supplies whole blocks: a plaintext of
|
||||
// fifteen bytes does not fill an AES block and is refused rather than padded.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00".repeat(15),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("16 bytes"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCipherTextIsAsLongAsThePlainTextItHolds() {
|
||||
// The cipher pads no data, so a ciphertext is as long as its plaintext.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
String plaintext = "00".repeat(32);
|
||||
|
||||
Map<String, Object> answer = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", plaintext,
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertEquals(plaintext.length(), ((String) answer.get("CipherText")).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacLengthThatIsNotANumberIsRefused() {
|
||||
// The protocol carries the length as a number, so a member that is not one is a
|
||||
// malformed request, and not the length the service would compute.
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", "00".repeat(16),
|
||||
"GenerationAttributes", iso9797(), "MacLength", "abc")), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWhoseMaterialIsNotHeldIsRefusedRatherThanFailing() {
|
||||
// The material is held by the key while the emulator runs and is not written to the
|
||||
// store, so a key read back after a restart has none. A request that needs it is then
|
||||
// refused with an error that says so, and not with a server error.
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
key.setKeyMaterialHex(null);
|
||||
keys.put("us-east-1\u0000" + key.getKeyId(), key);
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", "00".repeat(16),
|
||||
"EncryptionAttributes", cbc())), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("material"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMacLengthTheServiceDoesNotComputeIsRefused() {
|
||||
PaymentCryptographyKey key = createKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", "", "MacLength", 7)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
/** The MAC attributes of a DUKPT MAC, derived from a base derivation key. */
|
||||
private static JsonNode dukpt(String variant) {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
ObjectNode dukpt = mapper.createObjectNode();
|
||||
// The model asks for at least sixteen hexadecimal digits, and a KSN is ten bytes.
|
||||
dukpt.put("KeySerialNumber", "98765432109876543210");
|
||||
dukpt.put("DukptKeyVariant", "REQUEST");
|
||||
dukpt.put("DukptDerivationType", "TDES_2KEY");
|
||||
ObjectNode attributes = mapper.createObjectNode();
|
||||
attributes.set(variant, dukpt);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
/** The base derivation key the DUKPT MAC is derived from. */
|
||||
private PaymentCryptographyKey createBaseDerivationKey(String algorithm, String... modes) {
|
||||
Map<String, Object> attributes = new LinkedHashMap<>();
|
||||
attributes.put("KeyAlgorithm", algorithm);
|
||||
attributes.put("KeyClass", "SYMMETRIC_KEY");
|
||||
attributes.put("KeyUsage", "TR31_B0_BASE_DERIVATION_KEY");
|
||||
Map<String, Boolean> declared = new LinkedHashMap<>();
|
||||
for (String mode : modes) {
|
||||
declared.put(mode, Boolean.TRUE);
|
||||
}
|
||||
return service.createKey("us-east-1", attributes, declared, true, true, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacIsComputedAndVerifiedUnderABaseDerivationKey() {
|
||||
// The DUKPT MAC key is derived from the base derivation key, so that is the key the
|
||||
// request names, and it derives rather than computes the MAC itself.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
String message = hex("a message".getBytes());
|
||||
|
||||
Map<String, Object> mac = handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1");
|
||||
String value = (String) mac.get("Mac");
|
||||
|
||||
assertEquals(8, hexBytes(value).length);
|
||||
|
||||
Map<String, Object> verified = handler.verifyMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", message, "Mac", value, "MacLength", 8,
|
||||
"VerificationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1");
|
||||
assertEquals(key.getArn(), verified.get("KeyArn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAKeyThatMayNotDeriveRefuses() {
|
||||
// The key is named by the request but may only compute MACs of its own, so it cannot
|
||||
// be the base a DUKPT MAC key is derived from.
|
||||
PaymentCryptographyKey key = createTdesKey("Generate", "Verify");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAKeyOfAnotherPurposeRefuses() {
|
||||
// The key may derive, but it is a data encryption key rather than a base derivation
|
||||
// key, so it is not one a DUKPT MAC key is derived from.
|
||||
PaymentCryptographyKey key =
|
||||
createKeyOf("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY", "DeriveKey");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderAnAesKeyRefuses() {
|
||||
// The derivation is over Triple DES, so a key of another family is not one.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("AES_256", "DeriveKey");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", dukpt("DukptIso9797Algorithm1"))), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptDerivationTypeTheServiceDoesNotDeriveByRefuses() {
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
JsonNode attributes = dukpt("DukptIso9797Algorithm1");
|
||||
((ObjectNode) attributes.path("DukptIso9797Algorithm1")).put("DukptDerivationType", "AES_256");
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", attributes)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDukptMacUnderASerialNumberTheDerivationDoesNotTakeRefuses() {
|
||||
// The model takes a serial number of sixteen, twenty or twenty-four hexadecimal
|
||||
// digits, and the derivation takes one of ten bytes, so a longer one is refused by
|
||||
// the derivation and not by the model.
|
||||
PaymentCryptographyKey key = createBaseDerivationKey("TDES_2KEY", "DeriveKey");
|
||||
JsonNode attributes = dukpt("DukptIso9797Algorithm1");
|
||||
((ObjectNode) attributes.path("DukptIso9797Algorithm1"))
|
||||
.put("KeySerialNumber", "987654321098765432109876");
|
||||
|
||||
AwsException refused = assertThrows(AwsException.class, () -> handler.generateMac(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "MessageData", hex("a message".getBytes()), "MacLength", 8,
|
||||
"GenerationAttributes", attributes)), "us-east-1"));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
assertTrue(refused.getMessage().contains("DUKPT derivation failed"), refused.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyReEncryptsUnderAnotherKey() {
|
||||
PaymentCryptographyKey incoming = createKey("Encrypt", "Decrypt");
|
||||
PaymentCryptographyKey outgoing = createKey("Encrypt", "Decrypt");
|
||||
String cipherText = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", incoming.getArn(),
|
||||
"PlainText", hex("moved over there".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
Map<String, Object> reEncrypted = handler.reEncryptData(request(Map.of(
|
||||
"IncomingKeyIdentifier", incoming.getArn(),
|
||||
"OutgoingKeyIdentifier", outgoing.getArn(),
|
||||
"CipherText", cipherText,
|
||||
"IncomingEncryptionAttributes", cbc(),
|
||||
"OutgoingEncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
Map<String, Object> decrypted = handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", outgoing.getArn(),
|
||||
"CipherText", (String) reEncrypted.get("CipherText"),
|
||||
"DecryptionAttributes", cbc())), "us-east-1");
|
||||
assertEquals(hex("moved over there".getBytes()), decrypted.get("PlainText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOperationsThatNeedAMaterialTheServiceDoesNotHaveAreRefused() {
|
||||
// The translation of a key's material is the one operation of these that the service
|
||||
// does not serve: the byte layout of the cryptogram is in the standard and is not
|
||||
// published, so a cryptogram the service produced would not open here.
|
||||
for (Runnable refused : new Runnable[] {
|
||||
() -> handler.translateKeyMaterial(request(Map.of()), "us-east-1")}) {
|
||||
AwsException refusal = assertThrows(AwsException.class, refused::run);
|
||||
assertEquals("ValidationException", refusal.getErrorCode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyWithNoRestrictionsMayBeUsedForAnything() {
|
||||
PaymentCryptographyKey key = createKey("NoRestrictions");
|
||||
|
||||
Map<String, Object> encrypted = handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex("xxxxxxxxxxxxxxxx".getBytes()),
|
||||
"EncryptionAttributes", cbc())), "us-east-1");
|
||||
|
||||
assertTrue(encrypted.containsKey("CipherText"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePlainTextIsTheBytesTheCallerGave() {
|
||||
PaymentCryptographyKey key = createKey("Encrypt", "Decrypt");
|
||||
byte[] plain = "a longer plaintext that spans a block boundary!!".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
String cipherText = (String) handler.encryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "PlainText", hex(plain),
|
||||
"EncryptionAttributes", cbc())), "us-east-1").get("CipherText");
|
||||
|
||||
assertEquals(hex(plain), handler.decryptData(request(Map.of(
|
||||
"KeyIdentifier", key.getArn(), "CipherText", cipherText,
|
||||
"DecryptionAttributes", cbc())), "us-east-1").get("PlainText"));
|
||||
}
|
||||
}
|
||||
+118
-22
@@ -1,11 +1,15 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import io.floci.aws.services.paymentcryptography.crypto.Ciphers;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
@@ -82,16 +86,18 @@ class PaymentCryptographyCryptoTest {
|
||||
void theEncryptionIsTheOneAnotherImplementationComputed() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex(
|
||||
"54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67");
|
||||
// The cipher pads no data, so the plaintext is a whole number of blocks.
|
||||
byte[] plaintext = "The quick brown fox jumps over!!".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, new FixedRandom(
|
||||
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
|
||||
assertEquals("101112131415161718191a1b1c1d1e1fb746e4f1bce2352d20440b8a2e0eb8fd6"
|
||||
+ "8c1fcd0d00fcac779ecaadacde7e51a41da205eac66749510362db1c9f3e6d5",
|
||||
// The ciphertext is the encrypted bytes alone: the vector travels beside it, in the
|
||||
// request's attributes. The value is the one BouncyCastle computes for the same key,
|
||||
// vector and plaintext.
|
||||
assertEquals("b746e4f1bce2352d20440b8a2e0eb8fdf67504d7488d1792588f220540ed23b4",
|
||||
PaymentCryptographyCrypto.toHex(blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -99,28 +105,106 @@ class PaymentCryptographyCryptoTest {
|
||||
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")));
|
||||
"1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100");
|
||||
// The vector is fixed, so the answer is fixed.
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
byte[] plaintext = "a whole block ok".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
|
||||
// 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));
|
||||
// The right key opens it.
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
// The other key does not: the cipher pads no data, so it reads as the bytes the
|
||||
// ciphertext holds and nothing says they are the plaintext.
|
||||
assertFalse(Arrays.equals(plaintext,
|
||||
PaymentCryptographyCrypto.decryptCbc(other, blob, vector)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theEncryptionOfAnEmptyPlaintextIsTheVectorAndThePadding() {
|
||||
void theTripleDesCipherIsTheOneAnotherImplementationComputed() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f0001020304050607");
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("0102030405060708");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
|
||||
|
||||
byte[] blob = PaymentCryptographyCrypto.tdesCbcEncrypt(key, plaintext, vector);
|
||||
|
||||
// The value is the one another implementation computes for the same key, vector and
|
||||
// plaintext.
|
||||
assertEquals("2ccf87b33cad11b72eb3ead4b7385053", PaymentCryptographyCrypto.toHex(blob));
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.tdesCbcDecrypt(key, blob, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacsAreTheOnesFipsPub113Publishes() {
|
||||
// The ISO 9797-1 worked example, with equal key halves: both algorithms collapse to
|
||||
// the single-DES CBC-MAC, so one published value pins both chains and the padding.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEF0123456789ABCDEF");
|
||||
byte[] message = "7654321 Now is the time for ".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, message)));
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, message)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacOfAMessageThatFillsItsBlocksIsTheOneFipsPub113Publishes() {
|
||||
// The published example pads its text with zeroes to a whole block, and that padded
|
||||
// text is the example's own fourth block. A text that already fills its blocks is
|
||||
// padded with nothing, so the two give one MAC.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEF0123456789ABCDEF");
|
||||
byte[] padded = PaymentCryptographyCrypto.fromHex(
|
||||
"37363534333231204e6f77206973207468652074696d6520666f722000000000");
|
||||
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, padded)));
|
||||
assertEquals("f1d30f6849312ca4",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, padded)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theIso9797MacsAreTheOnesAnotherImplementationComputed() {
|
||||
// The two-key regression locks, which are the distinct-halves path the published
|
||||
// example does not reach.
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex("0123456789ABCDEFFEDCBA9876543210");
|
||||
byte[] message = "7654321 Now is the time for ".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
assertEquals("e5e7a413c3e3f4b5",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg1(key, message)));
|
||||
assertEquals("ae4b45b1b527642f",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, message)));
|
||||
// Over an empty message the algorithm 3 MAC is the Triple DES of a zero block, whose
|
||||
// leftmost three bytes are the independently documented X9.24 check value of the key.
|
||||
assertEquals("08d7b4fb629d0885",
|
||||
PaymentCryptographyCrypto.toHex(Ciphers.iso9797Alg3(key, new byte[0])));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTwoKeyTripleDesKeyIsUsedUnderTheThreeKeysItHolds() {
|
||||
byte[] two = PaymentCryptographyCrypto.fromHex("000102030405060708090a0b0c0d0e0f");
|
||||
byte[] three = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f0001020304050607");
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("0102030405060708");
|
||||
byte[] plaintext = PaymentCryptographyCrypto.fromHex("00112233445566778899aabbccddeeff");
|
||||
|
||||
assertArrayEquals(PaymentCryptographyCrypto.tdesCbcEncrypt(three, plaintext, vector),
|
||||
PaymentCryptographyCrypto.tdesCbcEncrypt(two, plaintext, vector));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCipherPadsNoData() {
|
||||
byte[] key = PaymentCryptographyCrypto.fromHex(
|
||||
"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, new byte[0], new FixedRandom(
|
||||
PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f")));
|
||||
byte[] vector = PaymentCryptographyCrypto.fromHex("101112131415161718191a1b1c1d1e1f");
|
||||
|
||||
assertEquals(32, blob.length);
|
||||
assertArrayEquals(new byte[0], PaymentCryptographyCrypto.decryptCbc(key, blob));
|
||||
// A ciphertext is as long as the plaintext it holds, and the vector is not in it.
|
||||
byte[] plaintext = "a whole block ok".getBytes(StandardCharsets.UTF_8);
|
||||
byte[] blob = PaymentCryptographyCrypto.encryptCbc(key, plaintext, vector);
|
||||
assertEquals(plaintext.length, blob.length);
|
||||
assertArrayEquals(plaintext, PaymentCryptographyCrypto.decryptCbc(key, blob, vector));
|
||||
|
||||
// An empty plaintext is an empty ciphertext: there is no padding to add.
|
||||
assertEquals(0, PaymentCryptographyCrypto.encryptCbc(key, new byte[0], vector).length);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -132,6 +216,18 @@ class PaymentCryptographyCryptoTest {
|
||||
assertNotNull(PaymentCryptographyCrypto.checkValue(material));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTripleDesCheckValueIsTheLeftmostThreeBytesOfTheEncryptedZeroes() {
|
||||
// The check value of a Triple DES key is the ANSI X9.24 one: the leftmost three
|
||||
// bytes of encrypting eight zero bytes with the key. The two-key form is widened to
|
||||
// K1||K2||K1 first, which is what the three-key cipher takes.
|
||||
assertEquals("08D7B4", PaymentCryptographyCrypto.checkValue(
|
||||
"0123456789ABCDEFFEDCBA9876543210", PaymentCryptographyKeyAlgorithm.TDES_2KEY));
|
||||
assertEquals("3FD539", PaymentCryptographyCrypto.checkValue(
|
||||
"0123456789ABCDEFFEDCBA987654321089ABCDEF01234567",
|
||||
PaymentCryptographyKeyAlgorithm.TDES_3KEY));
|
||||
}
|
||||
|
||||
private static String mac(String messageHex) {
|
||||
return PaymentCryptographyCrypto.toHex(PaymentCryptographyCrypto.cmac(
|
||||
PaymentCryptographyCrypto.fromHex(RFC4493_KEY),
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package io.floci.aws.services.paymentcryptography;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AwsException;
|
||||
import io.floci.aws.core.common.AwsPartition;
|
||||
import io.floci.aws.core.common.AwsPartitions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/**
|
||||
* The members that name a key, checked against the vendored constraints in every published region.
|
||||
*
|
||||
* <p>The data plane's identifier names a key by its ARN or by an alias, and the identifier of a
|
||||
* key on its own names none of them, so a request that carries one is refused.
|
||||
*/
|
||||
class PaymentCryptographyDataRequestShapesTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String KEY_ID = "0123456789abcdef0123456789abcdef";
|
||||
|
||||
/** An encryption request, which the model asks for the identifier, the plaintext and the attributes of. */
|
||||
private static ObjectNode request(String identifier) {
|
||||
ObjectNode request = MAPPER.createObjectNode();
|
||||
request.put("KeyIdentifier", identifier);
|
||||
request.put("PlainText", "00112233445566778899aabbccddeeff");
|
||||
request.putObject("EncryptionAttributes").putObject("Symmetric").put("Mode", "CBC");
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPublishedRegionIsTaken() {
|
||||
assertFalse(AwsPartitions.allRegionIds().isEmpty());
|
||||
for (String region : AwsPartitions.allRegionIds()) {
|
||||
AwsPartition partition = AwsPartitions.forRegion(region).orElseThrow();
|
||||
String prefix = "arn:" + partition.id() + ":payment-cryptography:" + region + ":000000000000:";
|
||||
String key = prefix + "key/" + KEY_ID;
|
||||
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(key)), key);
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(prefix + "alias/team/card-key")), region);
|
||||
assertDoesNotThrow(() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request("alias/team/card-key")), region);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentifierThatNamesNoKeyIsRefused() {
|
||||
// The identifier of a key on its own is not the ARN of a key nor an alias, and the
|
||||
// model says so.
|
||||
AwsException refused = assertThrows(AwsException.class,
|
||||
() -> PaymentCryptographyDataRequestShapes.check(
|
||||
"EncryptData", request(KEY_ID)));
|
||||
|
||||
assertEquals("ValidationException", refused.getErrorCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package io.floci.aws.services.paymentcryptography.crypto;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HexFormat;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* The DUKPT derivation, against the vectors ANSI X9.24-1 publishes.
|
||||
*
|
||||
* <p>The vectors are the initial sequence of the standard's annex A.4.2: the device whose
|
||||
* base derivation key is the one the standard uses, over the five counters it walks
|
||||
* through. The initial key is the same for all of them, because the counter is cleared
|
||||
* before the key is derived.
|
||||
*
|
||||
* <p>The MAC of each counter is the retail MAC over the data the standard names, under
|
||||
* the MAC request key, so the vectors hold the derivation and the ISO 9797-1 algorithm 3
|
||||
* MAC the data plane computes together.
|
||||
*/
|
||||
class DukptCryptoTest {
|
||||
|
||||
/** The base derivation key of the published vectors. */
|
||||
private static final String BDK = "0123456789ABCDEFFEDCBA9876543210";
|
||||
|
||||
/** The initial key of the device, the same for every counter. */
|
||||
private static final String INITIAL_KEY = "6AC292FAA1315B4D858AB3A3D7D5933A";
|
||||
|
||||
/** The data the published MACs are taken over. */
|
||||
private static final byte[] DATA = "4012345678909D987".getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
@Test
|
||||
void theInitialKeyIsTheOneOfTheStandard() {
|
||||
assertEquals(INITIAL_KEY, hex(DukptCrypto.deriveIpek(BDK, "FFFF9876543210E00000")));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({"FFFF9876543210E00001", "FFFF9876543210E00005"})
|
||||
void theInitialKeyDoesNotDependOnTheCounter(String ksn) {
|
||||
assertEquals(INITIAL_KEY, hex(DukptCrypto.deriveIpek(BDK, ksn)));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"FFFF9876543210E00001, 042666B49184CFA368DE9628D0397BC9, 9CCC78173FC4FB64",
|
||||
"FFFF9876543210E00002, C46551CEF9FD24B0AA9AD834130D3BC7, F608A9BCA6FFC311",
|
||||
"FFFF9876543210E00003, 0DF3D9422ACA56E547676D07AD6BADFA, 20B59A4FEAC937E3",
|
||||
"FFFF9876543210E00004, 279C0F6AEED0BE652B2C733E1383AE91, C7BFA6CC44161828",
|
||||
"FFFF9876543210E00005, 5F8DC6D2C845C125508DDC048093B83F, 0202B96339022058"
|
||||
})
|
||||
void theDerivedKeyAndTheMacAreTheOnesOfTheStandard(String ksn, String key, String mac) {
|
||||
assertEquals(key, hex(DukptCrypto.deriveTransactionKey(BDK, ksn)));
|
||||
|
||||
byte[] macKey = DukptCrypto.macKey(BDK, ksn);
|
||||
|
||||
assertEquals(mac, hex(Ciphers.iso9797Alg3(macKey, DATA)));
|
||||
}
|
||||
|
||||
private static String hex(byte[] bytes) {
|
||||
return HexFormat.of().withUpperCase().formatHex(bytes);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user