feat(paymentcryptography): a key pair signs a certificate signing request (#8832)

This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-18 13:35:25 -04:00
1 parent 8b7d06a9d1
commit 3f3625359a
12 files changed
+686 -45

No files matched your search

@@ -0,0 +1,162 @@
package io.floci.aws.services.paymentcryptography;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.paymentcryptography.crypto.Certificates;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x500.X500NameBuilder;
import org.bouncycastle.asn1.x500.style.BCStyle;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* The certificate signing request a key pair signs.
*
* <p>The request is a PKCS#10 one: the subject and the public half of the key, signed by the
* private half. The digest is the one the request names, and the signature algorithm is the
* one the key's own algorithm gives with that digest, so an RSA key signs with an RSA
* algorithm and an elliptic curve one with an ECDSA algorithm.
*/
final class PaymentCryptographyCertificateRequest {
/**
* The subject's members, and the attribute each is written as.
*
* <p>The order is the one the reference's own request carries, most general member
* first, so the subject of two requests with the same members is the same subject. The
* reference's example reads {@code C=US, ST=Virginia, L=Arlington, O=Amazon,
* OU=PaymentCryptography, CN=MyCertificateAWSUSEAST}, which is the order the members
* are written in here.
*/
private static final Map<String, ASN1ObjectIdentifier> SUBJECT_TYPES = subjectTypes();
/**
* The members whose attribute holds an IA5String, which is ASCII alone.
*
* <p>A value outside ASCII cannot be written as such an attribute, and the encoder would
* narrow it to a byte of its own, so the request would carry an address the caller did
* not name. A request that names one is refused instead.
*/
private static final Set<String> IA5_MEMBERS = Set.of("EmailAddress");
private PaymentCryptographyCertificateRequest() {
}
private static Map<String, ASN1ObjectIdentifier> subjectTypes() {
Map<String, ASN1ObjectIdentifier> types = new LinkedHashMap<>();
types.put("Country", BCStyle.C);
types.put("StateOrProvince", BCStyle.ST);
types.put("City", BCStyle.L);
types.put("Organization", BCStyle.O);
types.put("OrganizationUnit", BCStyle.OU);
types.put("CommonName", BCStyle.CN);
types.put("EmailAddress", BCStyle.E);
return types;
}
/**
* The subject of the request, as the members the model names.
*
* <p>A member the request does not name is not in the subject, and the one it does
* require, the common name, is. A member whose attribute cannot hold the value the
* request names is refused, because the request would otherwise carry a value the
* caller never wrote.
*
* @param fields the subject's members
* @return the subject
*/
static X500Name subject(Map<String, String> fields) {
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
for (Map.Entry<String, ASN1ObjectIdentifier> entry : SUBJECT_TYPES.entrySet()) {
String value = fields.get(entry.getKey());
if (value != null && !value.isEmpty()) {
requireAscii(entry.getKey(), value);
builder.addRDN(entry.getValue(), value);
}
}
return builder.build();
}
/**
* The refusal of a value the attribute of a member cannot hold.
*
* @param member the member of the subject
* @param value the value the request names
*/
private static void requireAscii(String member, String value) {
if (!IA5_MEMBERS.contains(member)) {
return;
}
for (int index = 0; index < value.length(); index++) {
if (value.charAt(index) > 127) {
throw new AwsException("ValidationException",
"the " + member + " of the subject holds a character that is not ASCII, "
+ "and the attribute it is written as holds ASCII alone", 400);
}
}
}
/**
* The request, in PEM.
*
* @param subject the subject of the request
* @param publicKey the public half of the key pair
* @param privateKey the private half of the key pair
* @param digest the digest the request names
* @param rsa whether the key pair is an RSA one
* @return the request, in PEM
*/
static String pem(X500Name subject, PublicKey publicKey, PrivateKey privateKey,
String digest, boolean rsa) {
String algorithm = algorithm(digest, rsa);
try {
ContentSigner signer = new JcaContentSignerBuilder(algorithm).build(privateKey);
// The request carries the public half in the form a certificate names it, which
// is the encoded form of the key.
SubjectPublicKeyInfo publicKeyInfo =
SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
byte[] encoded = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo)
.build(signer).getEncoded();
return Certificates.toPem("CERTIFICATE REQUEST", encoded);
} catch (OperatorCreationException | IOException e) {
throw new AwsException("ValidationException",
"the certificate signing request could not be signed: " + e.getMessage(), 400);
}
}
/**
* The members of the subject, as the model names them.
*
* @return the members, in the order the subject is written in
*/
static List<String> subjectMembers() {
return List.copyOf(SUBJECT_TYPES.keySet());
}
/**
* The signature algorithm a digest names.
*
* <p>The digest names the digest of the signature algorithm, and the key's own
* algorithm gives the rest, so a SHA256 digest signs with a SHA256withRSA algorithm
* for an RSA key and with a SHA256withECDSA one for an elliptic curve key. The model
* settles the digest, so the four the model names are the four that arrive.
*
* @param digest the digest the request names
* @param rsa whether the key pair is an RSA one
* @return the signature algorithm
*/
private static String algorithm(String digest, boolean rsa) {
return digest + "with" + (rsa ? "RSA" : "ECDSA");
}
}
@@ -84,6 +84,7 @@ public class PaymentCryptographyJsonHandler {
case "GetDefaultKeyReplicationRegions" -> () -> getDefaultKeyReplicationRegions(request, region);
case "EnableDefaultKeyReplicationRegions" -> () -> enableDefaultKeyReplicationRegions(request, region);
case "DisableDefaultKeyReplicationRegions" -> () -> disableDefaultKeyReplicationRegions(request, region);
case "GetCertificateSigningRequest" -> () -> getCertificateSigningRequest(request, region);
case "TagResource" -> () -> tagResource(request, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
@@ -544,6 +545,35 @@ public class PaymentCryptographyJsonHandler {
return tags;
}
// ---- certificate signing requests ----------------------------------------
/**
* The certificate signing request a key pair signs.
*
* <p>The subject is the metadata the request names, and the digest is the one the request
* names, so the request is the one the caller asked for. The answer carries the PEM of
* the request, base64 encoded, as the reference's own answer carries it.
*/
private Map<String, Object> getCertificateSigningRequest(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, KEY_IDENTIFIER);
String signingRequest = service.certificateSigningRequest(key,
request.path("SigningAlgorithm").asText(),
subjectOf(request.path("CertificateSubject")));
return Map.of("CertificateSigningRequest", signingRequest);
}
/** The subject of a request, as the members the model names. */
private static Map<String, String> subjectOf(JsonNode subject) {
Map<String, String> fields = new LinkedHashMap<>();
for (String member : PaymentCryptographyCertificateRequest.subjectMembers()) {
JsonNode value = subject.get(member);
if (value != null && !value.isNull()) {
fields.put(member, value.asText());
}
}
return fields;
}
// ---- helpers ------------------------------------------------------------
/**
@@ -173,7 +173,7 @@ final class PaymentCryptographyKeyExchange {
X509Certificate certificate = certificates.signCertificate(subject, subjectPublicKey,
issuer, issuerPrivateKey, List.of(), false, null, notBefore, notAfter);
byte[] der = certificate.getEncoded();
return new Certificates.Minted(der, Certificates.toPem(der));
return new Certificates.Minted(der, Certificates.toPem("CERTIFICATE", der));
} catch (IOException e) {
throw new IllegalStateException("cannot mint a certificate", e);
} catch (Exception e) {
@@ -668,12 +668,7 @@ final class PaymentCryptographyKeyExchange {
/** The name the key factory knows the key's algorithm by. */
private static String keyFactoryAlgorithm(PaymentCryptographyKey key) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
if (algorithm != null && algorithm.rsa) {
return "RSA";
}
return "EC";
return PaymentCryptographyService.isRsa(key) ? "RSA" : "EC";
}
/**
@@ -749,7 +744,7 @@ final class PaymentCryptographyKeyExchange {
private static String certificatePem(String certText) {
try {
X509Certificate certificate = Certificates.parseCertificate(certText);
return Certificates.toPem(certificate.getEncoded());
return Certificates.toPem("CERTIFICATE", certificate.getEncoded());
} catch (GeneralSecurityException | RuntimeException e) {
throw validation("the public key certificate is not a certificate: " + e.getMessage());
}
@@ -1131,7 +1126,8 @@ final class PaymentCryptographyKeyExchange {
/** The import parameters of an issued token, as the answer carries them. */
private static Map<String, Object> importParameters(Issued issued) {
String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer));
String certificate64 = Certificates.pemBase64(
Certificates.toPem("CERTIFICATE", issued.certificateDer));
Map<String, Object> out = new LinkedHashMap<>();
out.put("ImportToken", issued.token);
out.put("WrappingKeyCertificate", certificate64);
@@ -1190,7 +1186,8 @@ final class PaymentCryptographyKeyExchange {
/** The export parameters of an issued token, as the answer carries them. */
private static Map<String, Object> exportParameters(Issued issued) {
String certificate64 = Certificates.pemBase64(Certificates.toPem(issued.certificateDer));
String certificate64 = Certificates.pemBase64(
Certificates.toPem("CERTIFICATE", issued.certificateDer));
Map<String, Object> out = new LinkedHashMap<>();
out.put("ExportToken", issued.token);
out.put("SigningKeyCertificate", certificate64);
@@ -13,6 +13,7 @@ import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
import io.floci.aws.core.storage.StorageFactory;
import io.floci.aws.services.acm.CertificateGenerator;
import io.floci.aws.services.paymentcryptography.crypto.Certificates;
import io.floci.aws.services.paymentcryptography.crypto.DukptCrypto;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
@@ -21,6 +22,8 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.time.Clock;
import java.util.ArrayList;
@@ -486,6 +489,52 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
return current;
}
// ---- certificate signing requests ----------------------------------------
/**
* The certificate signing request a key pair signs.
*
* <p>The request carries the subject and the public half of the key, and it is signed by
* the private half, so the key has to be a key pair the service holds the private half
* of: a key that is not a key pair has no public half to certify, and a key pair the
* service holds no private half of has nothing to sign with. A key that is disabled does
* no work.
*
* <p>The usage and the mode of use of the key are not narrowed. The reference publishes
* no table of the keys this operation takes, and its own flows are two: one signs with a
* key pair of the digital signature usage whose mode of use is {@code Sign}, the other
* with a key pair of the TR-34 usage whose modes of use are {@code Unwrap} and
* {@code Decrypt}. Both are served here.
*
* <p>The answer is the PEM of the request, base64 encoded, which is what the reference's
* own answer carries, so a caller that decodes it holds the file the markers are in.
*
* @param key the key pair that signs
* @param digest the digest the request names
* @param subject the subject's members
* @return the request, base64 encoded
*/
public synchronized String certificateSigningRequest(PaymentCryptographyKey key, String digest,
Map<String, String> subject) {
PaymentCryptographyKey current = liveKey(key);
PaymentCryptographyKeyRules.requireEnabled(current);
if (!ASYMMETRIC_CLASS.equals(current.getKeyClass())) {
throw new AwsException("ValidationException",
"the key " + current.getArn() + " is not a key pair, and a key pair is what "
+ "signs a certificate signing request", 400);
}
PublicKey publicKey = PaymentCryptographyKeyExchange.publicKeyOf(current);
PrivateKey privateKey = PaymentCryptographyKeyExchange.privateKeyOf(current);
if (publicKey == null || privateKey == null) {
throw new AwsException("ValidationException",
"the key " + current.getArn() + " has no key pair to sign a certificate "
+ "signing request with", 400);
}
return Certificates.pemBase64(PaymentCryptographyCertificateRequest.pem(
PaymentCryptographyCertificateRequest.subject(subject), publicKey, privateKey,
digest, isRsa(current)));
}
// ---- aliases ------------------------------------------------------------
/**
@@ -1183,6 +1232,19 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
+ USAGE_NAMES.keySet(), 400);
}
/**
* Whether a key is an RSA key rather than an elliptic curve 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 the two key pairs are of different lengths and
* the algorithm is what a certificate names.
*/
static boolean isRsa(PaymentCryptographyKey key) {
PaymentCryptographyKeyAlgorithm algorithm =
PaymentCryptographyKeyAlgorithm.from(key.getKeyAlgorithm());
return algorithm != null && algorithm.rsa;
}
/**
* Whether a key is an AES key rather than a TDES one.
*
@@ -22,7 +22,8 @@ import java.util.Base64;
*
* <p>The service gives a counterparty a certificate over a key pair it made for the occasion,
* and reads the certificate a counterparty brings. A certificate travels in three shapes: PEM,
* base64 of PEM (which is how the service returns one), and base64 of DER.
* base64 of PEM (which is how the service returns one), and base64 of DER. The PEM of a
* certificate signing request is written here too, under its own label.
*
* <p>Reading a certificate is the emulator's own business, through {@link Pem}; minting one
* belongs to ACM's generator, which the service asks for a certificate with.
@@ -121,17 +122,18 @@ public final class Certificates {
}
/**
* Wrap DER as a PEM document.
* Wrap DER as a PEM document of the given label.
*
* @param der the certificate in DER
* @return the certificate in PEM
* @param label the label the document carries, such as {@code CERTIFICATE}
* @param der the document in DER
* @return the document in PEM
*/
public static String toPem(byte[] der) {
public static String toPem(String label, byte[] der) {
StringWriter writer = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(writer)) {
pemWriter.writeObject(new PemObject("CERTIFICATE", der));
pemWriter.writeObject(new PemObject(label, der));
} catch (IOException e) {
throw new IllegalStateException("cannot write the certificate as PEM", e);
throw new IllegalStateException("cannot write the document as PEM", e);
}
return writer.toString();
}