use of org.gudy.bouncycastle.asn1.x509.GeneralName in project XobotOS by xamarin.
the class X509ExtensionUtil method getAlternativeNames.
private static Collection getAlternativeNames(byte[] extVal) throws CertificateParsingException {
if (extVal == null) {
return Collections.EMPTY_LIST;
}
try {
Collection temp = new ArrayList();
Enumeration it = DERSequence.getInstance(fromExtensionValue(extVal)).getObjects();
while (it.hasMoreElements()) {
GeneralName genName = GeneralName.getInstance(it.nextElement());
List list = new ArrayList();
// BEGIN android-changed
list.add(Integer.valueOf(genName.getTagNo()));
// END android-changed
switch(genName.getTagNo()) {
case GeneralName.ediPartyName:
case GeneralName.x400Address:
case GeneralName.otherName:
list.add(genName.getName().getDERObject());
break;
case GeneralName.directoryName:
list.add(X509Name.getInstance(genName.getName()).toString());
break;
case GeneralName.dNSName:
case GeneralName.rfc822Name:
case GeneralName.uniformResourceIdentifier:
list.add(((ASN1String) genName.getName()).getString());
break;
case GeneralName.registeredID:
list.add(DERObjectIdentifier.getInstance(genName.getName()).getId());
break;
case GeneralName.iPAddress:
list.add(DEROctetString.getInstance(genName.getName()).getOctets());
break;
default:
throw new IOException("Bad tag number: " + genName.getTagNo());
}
temp.add(list);
}
return Collections.unmodifiableCollection(temp);
} catch (Exception e) {
throw new CertificateParsingException(e.getMessage());
}
}
use of org.gudy.bouncycastle.asn1.x509.GeneralName in project robovm by robovm.
the class CertPathValidatorUtilities method getCRLIssuersFromDistributionPoint.
/**
* Add the CRL issuers from the cRLIssuer field of the distribution point or
* from the certificate if not given to the issuer criterion of the
* <code>selector</code>.
* <p/>
* The <code>issuerPrincipals</code> are a collection with a single
* <code>X500Principal</code> for <code>X509Certificate</code>s. For
* {@link X509AttributeCertificate}s the issuer may contain more than one
* <code>X500Principal</code>.
*
* @param dp The distribution point.
* @param issuerPrincipals The issuers of the certificate or attribute
* certificate which contains the distribution point.
* @param selector The CRL selector.
* @param pkixParams The PKIX parameters containing the cert stores.
* @throws AnnotatedException if an exception occurs while processing.
* @throws ClassCastException if <code>issuerPrincipals</code> does not
* contain only <code>X500Principal</code>s.
*/
protected static void getCRLIssuersFromDistributionPoint(DistributionPoint dp, Collection issuerPrincipals, X509CRLSelector selector, ExtendedPKIXParameters pkixParams) throws AnnotatedException {
List issuers = new ArrayList();
// indirect CRL
if (dp.getCRLIssuer() != null) {
GeneralName[] genNames = dp.getCRLIssuer().getNames();
// look for a DN
for (int j = 0; j < genNames.length; j++) {
if (genNames[j].getTagNo() == GeneralName.directoryName) {
try {
issuers.add(new X500Principal(genNames[j].getName().toASN1Primitive().getEncoded()));
} catch (IOException e) {
throw new AnnotatedException("CRL issuer information from distribution point cannot be decoded.", e);
}
}
}
} else {
/*
* certificate issuer is CRL issuer, distributionPoint field MUST be
* present.
*/
if (dp.getDistributionPoint() == null) {
throw new AnnotatedException("CRL issuer is omitted from distribution point but no distributionPoint field present.");
}
// add and check issuer principals
for (Iterator it = issuerPrincipals.iterator(); it.hasNext(); ) {
issuers.add((X500Principal) it.next());
}
}
// TODO: is not found although this should correctly add the rel name. selector of Sun is buggy here or PKI test case is invalid
// distributionPoint
// if (dp.getDistributionPoint() != null)
// {
// // look for nameRelativeToCRLIssuer
// if (dp.getDistributionPoint().getType() == DistributionPointName.NAME_RELATIVE_TO_CRL_ISSUER)
// {
// // append fragment to issuer, only one
// // issuer can be there, if this is given
// if (issuers.size() != 1)
// {
// throw new AnnotatedException(
// "nameRelativeToCRLIssuer field is given but more than one CRL issuer is given.");
// }
// ASN1Encodable relName = dp.getDistributionPoint().getName();
// Iterator it = issuers.iterator();
// List issuersTemp = new ArrayList(issuers.size());
// while (it.hasNext())
// {
// Enumeration e = null;
// try
// {
// e = ASN1Sequence.getInstance(
// new ASN1InputStream(((X500Principal) it.next())
// .getEncoded()).readObject()).getObjects();
// }
// catch (IOException ex)
// {
// throw new AnnotatedException(
// "Cannot decode CRL issuer information.", ex);
// }
// ASN1EncodableVector v = new ASN1EncodableVector();
// while (e.hasMoreElements())
// {
// v.add((ASN1Encodable) e.nextElement());
// }
// v.add(relName);
// issuersTemp.add(new X500Principal(new DERSequence(v)
// .getDEREncoded()));
// }
// issuers.clear();
// issuers.addAll(issuersTemp);
// }
// }
Iterator it = issuers.iterator();
while (it.hasNext()) {
try {
selector.addIssuerName(((X500Principal) it.next()).getEncoded());
} catch (IOException ex) {
throw new AnnotatedException("Cannot decode CRL issuer information.", ex);
}
}
}
use of org.gudy.bouncycastle.asn1.x509.GeneralName in project robovm by robovm.
the class X509CertificateObject method getAlternativeNames.
private static Collection getAlternativeNames(byte[] extVal) throws CertificateParsingException {
if (extVal == null) {
return null;
}
try {
Collection temp = new ArrayList();
Enumeration it = ASN1Sequence.getInstance(extVal).getObjects();
while (it.hasMoreElements()) {
GeneralName genName = GeneralName.getInstance(it.nextElement());
List list = new ArrayList();
list.add(Integers.valueOf(genName.getTagNo()));
switch(genName.getTagNo()) {
case GeneralName.ediPartyName:
case GeneralName.x400Address:
case GeneralName.otherName:
list.add(genName.getEncoded());
break;
case GeneralName.directoryName:
// BEGIN android-changed
list.add(X509Name.getInstance(genName.getName()).toString(true, X509Name.DefaultSymbols));
// END android-changed
break;
case GeneralName.dNSName:
case GeneralName.rfc822Name:
case GeneralName.uniformResourceIdentifier:
list.add(((ASN1String) genName.getName()).getString());
break;
case GeneralName.registeredID:
list.add(ASN1ObjectIdentifier.getInstance(genName.getName()).getId());
break;
case GeneralName.iPAddress:
byte[] addrBytes = DEROctetString.getInstance(genName.getName()).getOctets();
final String addr;
try {
addr = InetAddress.getByAddress(addrBytes).getHostAddress();
} catch (UnknownHostException e) {
continue;
}
list.add(addr);
break;
default:
throw new IOException("Bad tag number: " + genName.getTagNo());
}
temp.add(Collections.unmodifiableList(list));
}
if (temp.size() == 0) {
return null;
}
return Collections.unmodifiableCollection(temp);
} catch (Exception e) {
throw new CertificateParsingException(e.getMessage());
}
}
use of org.gudy.bouncycastle.asn1.x509.GeneralName 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.gudy.bouncycastle.asn1.x509.GeneralName 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();
}
Aggregations