use of org.bouncycastle.asn1.x509.ExtensionsGenerator in project android by nextcloud.
the class CsrHelper method generateCSR.
/**
* Create the certificate signing request (CSR) from private and public keys
*
* @param keyPair the KeyPair with private and public keys
* @param userId userId of CSR owner
* @return PKCS10CertificationRequest with the certificate signing request (CSR) data
* @throws IOException thrown if key cannot be created
* @throws OperatorCreationException thrown if contentSigner cannot be build
*/
private static PKCS10CertificationRequest generateCSR(KeyPair keyPair, String userId) throws IOException, OperatorCreationException {
String principal = "CN=" + userId;
AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WITHRSA");
AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder().find("SHA-1");
ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm).build(privateKey);
PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(principal), keyPair.getPublic());
ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
extensionsGenerator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
return csrBuilder.build(signer);
}
use of org.bouncycastle.asn1.x509.ExtensionsGenerator in project curiostack by curioswitch.
the class RequestNamespaceCertTask method exec.
@TaskAction
public void exec() {
ImmutableClusterExtension cluster = getProject().getExtensions().getByType(ClusterExtension.class);
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=" + cluster.namespace() + ".ns.cluster.stellarstation.com"), keyPair.getPublic());
Stream<GeneralName> generalNames = Streams.concat(Stream.of(new GeneralName(GeneralName.dNSName, "*." + cluster.namespace()), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc"), new GeneralName(GeneralName.dNSName, "*." + cluster.namespace() + ".svc.cluster.local")), cluster.extraNamespaceTlsHosts().stream().map(name -> new GeneralName(GeneralName.dNSName, name)));
GeneralNames subjectAltNames = new GeneralNames(generalNames.toArray(GeneralName[]::new));
ExtensionsGenerator extensions = new ExtensionsGenerator();
try {
extensions.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
p10Builder.setAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions.generate());
} catch (IOException e) {
throw new IllegalStateException("Could not encode cert name, can't happen.", e);
}
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));
Map<Object, Object> csrApiRequest = ImmutableMap.of("apiVersion", "certificates.k8s.io/v1beta1", "kind", "CertificateSigningRequest", "metadata", ImmutableMap.of("name", cluster.namespace() + ".server.crt"), "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() ? CommandUtil.getGcloudSdkBinDir(getProject()).resolve("kubectl").toAbsolutePath().toString() : "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", cluster.namespace() + ".server.crt");
});
// Need to wait a bit for certificate to propagate before fetching.
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Gradle Exec seems to be flaky when reading from stdout, so use normal ProcessBuilder.
final byte[] certificateBytes;
try {
Process getCertProcess = new ProcessBuilder(command, "get", "csr", cluster.namespace() + ".server.crt", "-o", "jsonpath={.status.certificate}").start();
certificateBytes = ByteStreams.toByteArray(getCertProcess.getInputStream());
} catch (IOException e) {
throw new UncheckedIOException("Could not fetch certificate.", e);
}
String certificate = new String(Base64.getDecoder().decode(certificateBytes), 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("server-tls").withNamespace(cluster.namespace()).build()).withType("Opaque").withData(ImmutableMap.of("server.crt", Base64.getEncoder().encodeToString(certificate.getBytes(StandardCharsets.UTF_8)), "server-key.pem", Base64.getEncoder().encodeToString(key.getBytes(StandardCharsets.UTF_8)))).build();
client.resource(certificateSecret).createOrReplace();
}
use of org.bouncycastle.asn1.x509.ExtensionsGenerator in project nifi by apache.
the class TlsHelper method createDomainAlternativeNamesExtensions.
public static Extensions createDomainAlternativeNamesExtensions(String domainAlternativeNames, String requestedDn) throws IOException {
List<GeneralName> namesList = new ArrayList<>();
try {
final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
namesList.add(new GeneralName(GeneralName.dNSName, cn));
} catch (Exception e) {
throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
}
if (StringUtils.isNotBlank(domainAlternativeNames)) {
for (String alternativeName : domainAlternativeNames.split(",")) {
namesList.add(new GeneralName(GeneralName.dNSName, alternativeName));
}
}
GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[] {}));
ExtensionsGenerator extGen = new ExtensionsGenerator();
extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
return extGen.generate();
}
use of org.bouncycastle.asn1.x509.ExtensionsGenerator in project candlepin by candlepin.
the class X509CRLStreamWriter method add.
/**
* Create an entry to be added to the CRL.
*
* @param serial
* @param date
* @param reason
* @throws IOException if an entry fails to generate
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public void add(BigInteger serial, Date date, int reason) throws IOException {
if (locked) {
throw new IllegalStateException("Cannot add to a locked stream.");
}
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(serial));
v.add(new Time(date));
CRLReason crlReason = CRLReason.getInstance(new ASN1Enumerated(reason));
ExtensionsGenerator generator = new ExtensionsGenerator();
generator.addExtension(Extension.reasonCode, false, crlReason);
v.add(generator.generate());
newEntries.add(new DERSequence(v));
}
use of org.bouncycastle.asn1.x509.ExtensionsGenerator in project dcos-commons by mesosphere.
the class CertificateAuthorityClientTest method createCSR.
private byte[] createCSR() throws IOException, OperatorCreationException {
KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();
X500Name name = new X500NameBuilder().addRDN(BCStyle.CN, "issuer").build();
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 }));
GeneralNames subAtlNames = new GeneralNames(new GeneralName[] { new GeneralName(GeneralName.dNSName, "test.com"), new GeneralName(GeneralName.iPAddress, TEST_IP_ADDR) });
extensionsGenerator.addExtension(Extension.subjectAlternativeName, true, subAtlNames);
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());
PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(name, keyPair.getPublic()).addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());
return PEMUtils.toPEM(csrBuilder.build(signer));
}
Aggregations