use of org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder in project curiostack by curioswitch.
the class CreateClientCertTask method exec.
@TaskAction
public void exec() {
ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
String commonName = (String) getProject().getRootProject().findProperty("commonName");
checkNotNull(commonName, "-PcommonName must be set");
final KeyPairGenerator keygen;
try {
keygen = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new IllegalStateException("Could not find RSA, can't happen.", e);
}
keygen.initialize(256, new SecureRandom());
KeyPair keyPair = keygen.generateKeyPair();
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + commonName), keyPair.getPublic());
final ContentSigner signer;
try {
signer = new JcaContentSignerBuilder("SHA256withECDSA").build(keyPair.getPrivate());
} catch (OperatorCreationException e) {
throw new IllegalStateException("Could not find signer, can't happen.", e);
}
PKCS10CertificationRequest csr = p10Builder.build(signer);
StringWriter csrWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(csrWriter)) {
pemWriter.writeObject(csr);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String encodedCsr = Base64.getEncoder().encodeToString(csrWriter.toString().getBytes(StandardCharsets.UTF_8));
String csrName = cluster.namespace() + "." + commonName + ".client.crt";
Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", csrName), "spec", ImmutableMap.of("request", encodedCsr, "usages", ImmutableList.of("digital signature", "key encipherment", "server auth", "client auth")));
final byte[] encodedApiRequest;
try {
encodedApiRequest = OBJECT_MAPPER.writeValueAsBytes(csrApiRequest);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode yaml", e);
}
ImmutableGcloudExtension config = getProject().getRootProject().getExtensions().getByType(GcloudExtension.class);
String command = config.download() ? new File(config.platformConfig().gcloudBinDir(), "kubectl").getAbsolutePath() : "kubectl";
getProject().exec(exec -> {
exec.executable(command);
exec.args("create", "-f", "-");
exec.setStandardInput(new ByteArrayInputStream(encodedApiRequest));
});
getProject().exec(exec -> {
exec.executable(command);
exec.args("certificate", "approve", csrName);
});
// Need to wait a bit for certificate to propagate before fetching.
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
ByteArrayOutputStream certStream = new ByteArrayOutputStream();
getProject().exec(exec -> {
exec.executable(command);
exec.args("get", "csr", csrName, "-o", "jsonpath={.status.certificate}");
exec.setStandardOutput(certStream);
});
String certificate = new String(Base64.getDecoder().decode(certStream.toByteArray()), StandardCharsets.UTF_8);
final JcaPKCS8Generator keyGenerator;
final PemObject keyObject;
try {
keyGenerator = new JcaPKCS8Generator(keyPair.getPrivate(), null);
keyObject = keyGenerator.generate();
} catch (PemGenerationException e) {
throw new IllegalStateException("Could not encode to pkcs8.", e);
}
StringWriter keyWriter = new StringWriter();
try (JcaPEMWriter pemWriter = new JcaPEMWriter(keyWriter)) {
pemWriter.writeObject(keyObject);
} catch (IOException e) {
throw new IllegalStateException("Could not encode csr, can't happen.", e);
}
String key = keyWriter.toString();
KubernetesClient client = new DefaultKubernetesClient();
Secret certificateSecret = new SecretBuilder().withMetadata(new ObjectMetaBuilder().withName(commonName + "-client-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("client.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "client-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
client.resource(certificateSecret).createOrReplace();
}
use of org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder in project fabric-sdk-java by hyperledger.
the class CryptoPrimitives method generateCertificationRequest.
/**
* generateCertificationRequest
*
* @param subject The subject to be added to the certificate
* @param pair Public private key pair
* @return PKCS10CertificationRequest Certificate Signing Request.
* @throws OperatorCreationException
*/
public String generateCertificationRequest(String subject, KeyPair pair) throws InvalidArgumentException {
try {
PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("CN=" + subject), pair.getPublic());
JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withECDSA");
if (null != SECURITY_PROVIDER) {
csBuilder.setProvider(SECURITY_PROVIDER);
}
ContentSigner signer = csBuilder.build(pair.getPrivate());
return certificationRequestToPEM(p10Builder.build(signer));
} catch (Exception e) {
logger.error(e);
throw new InvalidArgumentException(e);
}
}
use of org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder in project dcos-commons by mesosphere.
the class TLSArtifactsGenerator method generateCSR.
@SuppressWarnings("checkstyle:ThrowsCount")
private static byte[] generateCSR(KeyPair keyPair, CertificateNamesGenerator certificateNamesGenerator) throws IOException, OperatorCreationException {
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
extensionsGenerator.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
extensionsGenerator.addExtension(Extension.subjectAlternativeName, true, certificateNamesGenerator.getSANs());
PKCS10CertificationRequest csr = new JcaPKCS10CertificationRequestBuilder(certificateNamesGenerator.getSubject(), keyPair.getPublic()).addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate()).build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
return PEMUtils.toPEM(csr);
}
Aggregations