Search in sources :

Example 16 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project XobotOS by xamarin.

the class X509CertificateObject method getCriticalExtensionOIDs.

public Set getCriticalExtensionOIDs() {
    if (this.getVersion() == 3) {
        Set set = new HashSet();
        X509Extensions extensions = c.getTBSCertificate().getExtensions();
        if (extensions != null) {
            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);
                if (ext.isCritical()) {
                    set.add(oid.getId());
                }
            }
            return set;
        }
    }
    return null;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) Enumeration(java.util.Enumeration) X509Extension(org.bouncycastle.asn1.x509.X509Extension) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) HashSet(java.util.HashSet)

Example 17 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project robovm by robovm.

the class PKIXCertPathValidatorSpi method engineValidate.

// END android-added
public CertPathValidatorResult engineValidate(CertPath certPath, CertPathParameters params) throws CertPathValidatorException, InvalidAlgorithmParameterException {
    if (!(params instanceof PKIXParameters)) {
        throw new InvalidAlgorithmParameterException("Parameters must be a " + PKIXParameters.class.getName() + " instance.");
    }
    ExtendedPKIXParameters paramsPKIX;
    if (params instanceof ExtendedPKIXParameters) {
        paramsPKIX = (ExtendedPKIXParameters) params;
    } else {
        paramsPKIX = ExtendedPKIXParameters.getInstance((PKIXParameters) params);
    }
    if (paramsPKIX.getTrustAnchors() == null) {
        throw new InvalidAlgorithmParameterException("trustAnchors is null, this is not allowed for certification path validation.");
    }
    //
    // 6.1.1 - inputs
    //
    //
    // (a)
    //
    List certs = certPath.getCertificates();
    int n = certs.size();
    if (certs.isEmpty()) {
        throw new CertPathValidatorException("Certification path is empty.", null, certPath, 0);
    }
    // BEGIN android-added
    {
        X509Certificate cert = (X509Certificate) certs.get(0);
        if (cert != null) {
            BigInteger serial = cert.getSerialNumber();
            if (blacklist.isSerialNumberBlackListed(serial)) {
                // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
                String message = "Certificate revocation of serial 0x" + serial.toString(16);
                System.out.println(message);
                AnnotatedException e = new AnnotatedException(message);
                throw new CertPathValidatorException(e.getMessage(), e, certPath, 0);
            }
        }
    }
    // END android-added
    //
    // (b)
    //
    // Date validDate = CertPathValidatorUtilities.getValidDate(paramsPKIX);
    //
    // (c)
    //
    Set userInitialPolicySet = paramsPKIX.getInitialPolicies();
    //
    // (d)
    // 
    TrustAnchor trust;
    try {
        trust = CertPathValidatorUtilities.findTrustAnchor((X509Certificate) certs.get(certs.size() - 1), paramsPKIX.getTrustAnchors(), paramsPKIX.getSigProvider());
    } catch (AnnotatedException e) {
        throw new CertPathValidatorException(e.getMessage(), e, certPath, certs.size() - 1);
    }
    if (trust == null) {
        throw new CertPathValidatorException("Trust anchor for certification path not found.", null, certPath, -1);
    }
    //
    // (e), (f), (g) are part of the paramsPKIX object.
    //
    Iterator certIter;
    int index = 0;
    int i;
    // Certificate for each interation of the validation loop
    // Signature information for each iteration of the validation loop
    //
    // 6.1.2 - setup
    //
    //
    // (a)
    //
    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }
    Set policySet = new HashSet();
    policySet.add(RFC3280CertPathUtilities.ANY_POLICY);
    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(), RFC3280CertPathUtilities.ANY_POLICY, false);
    policyNodes[0].add(validPolicyTree);
    //
    // (b) and (c)
    //
    PKIXNameConstraintValidator nameConstraintValidator = new PKIXNameConstraintValidator();
    // (d)
    //
    int explicitPolicy;
    Set acceptablePolicies = new HashSet();
    if (paramsPKIX.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }
    //
    // (e)
    //
    int inhibitAnyPolicy;
    if (paramsPKIX.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }
    //
    // (f)
    //
    int policyMapping;
    if (paramsPKIX.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }
    //
    // (g), (h), (i), (j)
    //
    PublicKey workingPublicKey;
    X500Principal workingIssuerName;
    X509Certificate sign = trust.getTrustedCert();
    try {
        if (sign != null) {
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            workingPublicKey = sign.getPublicKey();
        } else {
            workingIssuerName = new X500Principal(trust.getCAName());
            workingPublicKey = trust.getCAPublicKey();
        }
    } catch (IllegalArgumentException ex) {
        throw new ExtCertPathValidatorException("Subject of trust anchor could not be (re)encoded.", ex, certPath, -1);
    }
    AlgorithmIdentifier workingAlgId = null;
    try {
        workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
    } catch (CertPathValidatorException e) {
        throw new ExtCertPathValidatorException("Algorithm identifier of public key of trust anchor could not be read.", e, certPath, -1);
    }
    DERObjectIdentifier workingPublicKeyAlgorithm = workingAlgId.getObjectId();
    ASN1Encodable workingPublicKeyParameters = workingAlgId.getParameters();
    //
    // (k)
    //
    int maxPathLength = n;
    if (paramsPKIX.getTargetConstraints() != null && !paramsPKIX.getTargetConstraints().match((X509Certificate) certs.get(0))) {
        throw new ExtCertPathValidatorException("Target certificate in certification path does not match targetConstraints.", null, certPath, 0);
    }
    // 
    // initialize CertPathChecker's
    //
    List pathCheckers = paramsPKIX.getCertPathCheckers();
    certIter = pathCheckers.iterator();
    while (certIter.hasNext()) {
        ((PKIXCertPathChecker) certIter.next()).init(false);
    }
    X509Certificate cert = null;
    for (index = certs.size() - 1; index >= 0; index--) {
        // BEGIN android-added
        if (blacklist.isPublicKeyBlackListed(workingPublicKey)) {
            // emulate CRL exception message in RFC3280CertPathUtilities.checkCRLs
            String message = "Certificate revocation of public key " + workingPublicKey;
            System.out.println(message);
            AnnotatedException e = new AnnotatedException(message);
            throw new CertPathValidatorException(e.getMessage(), e, certPath, index);
        }
        // END android-added
        // try
        // {
        //
        // i as defined in the algorithm description
        //
        i = n - index;
        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialized the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);
        boolean verificationAlreadyPerformed = (index == certs.size() - 1);
        //
        // 6.1.3
        //
        RFC3280CertPathUtilities.processCertA(certPath, paramsPKIX, index, workingPublicKey, verificationAlreadyPerformed, workingIssuerName, sign);
        RFC3280CertPathUtilities.processCertBC(certPath, index, nameConstraintValidator);
        validPolicyTree = RFC3280CertPathUtilities.processCertD(certPath, index, acceptablePolicies, validPolicyTree, policyNodes, inhibitAnyPolicy);
        validPolicyTree = RFC3280CertPathUtilities.processCertE(certPath, index, validPolicyTree);
        RFC3280CertPathUtilities.processCertF(certPath, index, validPolicyTree, explicitPolicy);
        if (i != n) {
            if (cert != null && cert.getVersion() == 1) {
                throw new CertPathValidatorException("Version 1 certificates can't be used as CA ones.", null, certPath, index);
            }
            RFC3280CertPathUtilities.prepareNextCertA(certPath, index);
            validPolicyTree = RFC3280CertPathUtilities.prepareCertB(certPath, index, policyNodes, validPolicyTree, policyMapping);
            RFC3280CertPathUtilities.prepareNextCertG(certPath, index, nameConstraintValidator);
            // (h)
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertH1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertH2(certPath, index, policyMapping);
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertH3(certPath, index, inhibitAnyPolicy);
            //
            // (i)
            //
            explicitPolicy = RFC3280CertPathUtilities.prepareNextCertI1(certPath, index, explicitPolicy);
            policyMapping = RFC3280CertPathUtilities.prepareNextCertI2(certPath, index, policyMapping);
            // (j)
            inhibitAnyPolicy = RFC3280CertPathUtilities.prepareNextCertJ(certPath, index, inhibitAnyPolicy);
            // (k)
            RFC3280CertPathUtilities.prepareNextCertK(certPath, index);
            // (l)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertL(certPath, index, maxPathLength);
            // (m)
            maxPathLength = RFC3280CertPathUtilities.prepareNextCertM(certPath, index, maxPathLength);
            // (n)
            RFC3280CertPathUtilities.prepareNextCertN(certPath, index);
            Set criticalExtensions = cert.getCriticalExtensionOIDs();
            if (criticalExtensions != null) {
                criticalExtensions = new HashSet(criticalExtensions);
                // these extensions are handled by the algorithm
                criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
                criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
                criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
                criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
                criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
                criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
                criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
                criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
            } else {
                criticalExtensions = new HashSet();
            }
            // (o)
            RFC3280CertPathUtilities.prepareNextCertO(certPath, index, criticalExtensions, pathCheckers);
            // set signing certificate for next round
            sign = cert;
            // (c)
            workingIssuerName = CertPathValidatorUtilities.getSubjectPrincipal(sign);
            // (d)
            try {
                workingPublicKey = CertPathValidatorUtilities.getNextWorkingKey(certPath.getCertificates(), index);
            } catch (CertPathValidatorException e) {
                throw new CertPathValidatorException("Next working key could not be retrieved.", e, certPath, index);
            }
            workingAlgId = CertPathValidatorUtilities.getAlgorithmIdentifier(workingPublicKey);
            // (f)
            workingPublicKeyAlgorithm = workingAlgId.getObjectId();
            // (e)
            workingPublicKeyParameters = workingAlgId.getParameters();
        }
    }
    //
    // 6.1.5 Wrap-up procedure
    //
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertA(explicitPolicy, cert);
    explicitPolicy = RFC3280CertPathUtilities.wrapupCertB(certPath, index + 1, explicitPolicy);
    //
    // (c) (d) and (e) are already done
    //
    //
    // (f)
    //
    Set criticalExtensions = cert.getCriticalExtensionOIDs();
    if (criticalExtensions != null) {
        criticalExtensions = new HashSet(criticalExtensions);
        // these extensions are handled by the algorithm
        criticalExtensions.remove(RFC3280CertPathUtilities.KEY_USAGE);
        criticalExtensions.remove(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_MAPPINGS);
        criticalExtensions.remove(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY);
        criticalExtensions.remove(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT);
        criticalExtensions.remove(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR);
        criticalExtensions.remove(RFC3280CertPathUtilities.POLICY_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.BASIC_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME);
        criticalExtensions.remove(RFC3280CertPathUtilities.NAME_CONSTRAINTS);
        criticalExtensions.remove(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS);
    } else {
        criticalExtensions = new HashSet();
    }
    RFC3280CertPathUtilities.wrapupCertF(certPath, index + 1, pathCheckers, criticalExtensions);
    PKIXPolicyNode intersection = RFC3280CertPathUtilities.wrapupCertG(certPath, paramsPKIX, userInitialPolicySet, index + 1, policyNodes, validPolicyTree, acceptablePolicies);
    if ((explicitPolicy > 0) || (intersection != null)) {
        return new PKIXCertPathValidatorResult(trust, intersection, cert.getPublicKey());
    }
    throw new CertPathValidatorException("Path processing failed on policy.", null, certPath, index);
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXParameters(java.security.cert.PKIXParameters) PKIXCertPathChecker(java.security.cert.PKIXCertPathChecker) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) HashSet(java.util.HashSet) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) TrustAnchor(java.security.cert.TrustAnchor) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) ExtendedPKIXParameters(org.bouncycastle.x509.ExtendedPKIXParameters) PKIXCertPathValidatorResult(java.security.cert.PKIXCertPathValidatorResult) BigInteger(java.math.BigInteger) X500Principal(javax.security.auth.x500.X500Principal)

Example 18 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project robovm by robovm.

the class X509CertificateObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
    byte[] sig = this.getSignature();
    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
        if (i < sig.length - 20) {
            buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
        } else {
            buf.append("                       ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
        }
    }
    Extensions extensions = c.getTBSCertificate().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("       Extensions: \n");
        }
        while (e.hasMoreElements()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
            Extension ext = extensions.getExtension(oid);
            if (ext.getExtnValue() != null) {
                byte[] octs = ext.getExtnValue().getOctets();
                ASN1InputStream dIn = new ASN1InputStream(octs);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(Extension.basicConstraints)) {
                        buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(Extension.keyUsage)) {
                        buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
                        buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
                        buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
                        buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    //buf.append(" value = ").append("*****").append(nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    //     buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl);
                    buf.append(" value = ").append("*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    return buf.toString();
}
Also used : VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) NetscapeRevocationURL(org.bouncycastle.asn1.misc.NetscapeRevocationURL) DERBitString(org.bouncycastle.asn1.DERBitString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1String(org.bouncycastle.asn1.ASN1String) Extensions(org.bouncycastle.asn1.x509.Extensions) CertificateExpiredException(java.security.cert.CertificateExpiredException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) NoSuchProviderException(java.security.NoSuchProviderException) Extension(org.bouncycastle.asn1.x509.Extension) VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) DERIA5String(org.bouncycastle.asn1.DERIA5String) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 19 with Extensions

use of org.bouncycastle.asn1.x509.Extensions 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();
}
Also used : KeyPair(java.security.KeyPair) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) Extension(org.bouncycastle.asn1.x509.Extension) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) Security(java.security.Security) SecureRandom(java.security.SecureRandom) TaskAction(org.gradle.api.tasks.TaskAction) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) DefaultTask(org.gradle.api.DefaultTask) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KeyPairGenerator(java.security.KeyPairGenerator) PemObject(org.bouncycastle.util.io.pem.PemObject) ImmutableMap(com.google.common.collect.ImmutableMap) Streams(com.google.common.collect.Streams) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Base64(java.util.Base64) GeneralName(org.bouncycastle.asn1.x509.GeneralName) Stream(java.util.stream.Stream) GcloudExtension(org.curioswitch.gradle.plugins.gcloud.GcloudExtension) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteStreams(com.google.common.io.ByteStreams) Secret(io.fabric8.kubernetes.api.model.Secret) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) X500Principal(javax.security.auth.x500.X500Principal) PKCSObjectIdentifiers(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers) ContentSigner(org.bouncycastle.operator.ContentSigner) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) ImmutableList(com.google.common.collect.ImmutableList) ClusterExtension(org.curioswitch.gradle.plugins.gcloud.ClusterExtension) YAMLFactory(com.fasterxml.jackson.dataformat.yaml.YAMLFactory) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) TimeUnit(java.util.concurrent.TimeUnit) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) CommandUtil(org.curioswitch.gradle.plugins.shared.CommandUtil) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) NoSuchProviderException(java.security.NoSuchProviderException) ImmutableGcloudExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableGcloudExtension) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) UncheckedIOException(java.io.UncheckedIOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ImmutableClusterExtension(org.curioswitch.gradle.plugins.gcloud.ImmutableClusterExtension) SecretBuilder(io.fabric8.kubernetes.api.model.SecretBuilder) StringWriter(java.io.StringWriter) JcaPKCS8Generator(org.bouncycastle.openssl.jcajce.JcaPKCS8Generator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) PKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) KeyPairGenerator(java.security.KeyPairGenerator) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ObjectMetaBuilder(io.fabric8.kubernetes.api.model.ObjectMetaBuilder) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator) Secret(io.fabric8.kubernetes.api.model.Secret) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) X500Principal(javax.security.auth.x500.X500Principal) PemObject(org.bouncycastle.util.io.pem.PemObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) DefaultKubernetesClient(io.fabric8.kubernetes.client.DefaultKubernetesClient) NoSuchProviderException(java.security.NoSuchProviderException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) TaskAction(org.gradle.api.tasks.TaskAction)

Example 20 with Extensions

use of org.bouncycastle.asn1.x509.Extensions in project nifi by apache.

the class CertificateUtils method generateSelfSignedX509Certificate.

/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo);
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));
        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));
        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));
        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth }));
        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertIOException(org.bouncycastle.cert.CertIOException) Date(java.util.Date) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage)

Aggregations

ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)67 Extensions (org.bouncycastle.asn1.x509.Extensions)58 Extension (org.bouncycastle.asn1.x509.Extension)54 IOException (java.io.IOException)44 DEROctetString (org.bouncycastle.asn1.DEROctetString)38 HashSet (java.util.HashSet)35 Enumeration (java.util.Enumeration)34 X500Name (org.bouncycastle.asn1.x500.X500Name)31 Date (java.util.Date)29 BigInteger (java.math.BigInteger)27 DERIA5String (org.bouncycastle.asn1.DERIA5String)26 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)25 X509Certificate (java.security.cert.X509Certificate)24 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)23 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)23 DERUTF8String (org.bouncycastle.asn1.DERUTF8String)23 GeneralName (org.bouncycastle.asn1.x509.GeneralName)23 ContentSigner (org.bouncycastle.operator.ContentSigner)22 ArrayList (java.util.ArrayList)21 Set (java.util.Set)21