Example usage for org.bouncycastle.asn1.x509 Extensions getInstance

List of usage examples for org.bouncycastle.asn1.x509 Extensions getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extensions getInstance.

Prototype

public static Extensions getInstance(Object obj) 

Source Link

Usage

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static String extractX509CSREmail(PKCS10CertificationRequest certReq) {

    String rfc822 = null;/* w  w  w .  ja v a2 s.  c  om*/
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.rfc822Name) {
                    rfc822 = (((DERIA5String) name.getName()).getString());
                    break;
                }
            }
        }
    }
    return rfc822;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CSRDnsNames(PKCS10CertificationRequest certReq) {

    List<String> dnsNames = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.dNSName) {
                    dnsNames.add(((DERIA5String) name.getName()).getString());
                }/* w  w  w. j a  v a2 s  .  co  m*/
            }
        }
    }
    return dnsNames;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static List<String> extractX509CSRIPAddresses(PKCS10CertificationRequest certReq) {

    List<String> ipAddresses = new ArrayList<>();
    Attribute[] attributes = certReq.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributes) {
        for (ASN1Encodable value : attribute.getAttributeValues()) {
            Extensions extensions = Extensions.getInstance(value);
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            for (GeneralName name : gns.getNames()) {
                if (name.getTagNo() == GeneralName.iPAddress) {
                    try {
                        InetAddress addr = InetAddress
                                .getByAddress(((DEROctetString) name.getName()).getOctets());
                        ipAddresses.add(addr.getHostAddress());
                    } catch (UnknownHostException e) {
                    }/*from w  w  w  .  j  av a2s  . c  o m*/
                }
            }
        }
    }
    return ipAddresses;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);/*from  ww w. j av  a2  s  . c  o m*/
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:net.felsing.client_cert.utilities.CertificateFabric.java

License:Open Source License

private void getSubjectAlternativeNames(PKCS10CertificationRequest csr) {
    subjectAlternativeNames = new ArrayList<>(new ArrayList<>());
    // GeneralName.otherName is lowest and
    // GeneralName.registeredID is highest id
    for (int i = GeneralName.otherName; i <= GeneralName.registeredID; i++) {
        subjectAlternativeNames.add(new ArrayList<>());
    }/*  w w  w  . jav  a 2 s . c  o m*/

    try {
        Attribute[] certAttributes = csr.getAttributes();
        for (Attribute attribute : certAttributes) {
            if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
                // @ToDo: Is there really one object only?
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns != null) {
                    GeneralName[] names = gns.getNames();
                    for (GeneralName name : names) {
                        subjectAlternativeNames.get(name.getTagNo()).add(name.getName().toString());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.ripe.rpki.commons.provisioning.x509.pkcs10.RpkiCaCertificateRequestParser.java

License:BSD License

private Extensions getPkcs9Extensions() throws RpkiCaCertificateRequestParserException {
    ASN1Set pkcs9ExtensionRequest = getPkcs9ExtensionRequest();

    Object extensionRequestElement = pkcs9ExtensionRequest.getObjects().nextElement();
    if (extensionRequestElement instanceof Extensions) {
        return (Extensions) extensionRequestElement;
    } else if (extensionRequestElement instanceof ASN1Sequence) {
        return Extensions.getInstance((ASN1Sequence) extensionRequestElement);
    } else {//ww w .j  a va 2 s.  c om
        throw new RpkiCaCertificateRequestParserException("Encountered an element I do not understand, type: "
                + extensionRequestElement.getClass().getSimpleName());
    }

}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

License:Apache License

/**
 * Extract extensions from CSR object//from   ww  w  . jav a  2s  . c om
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

License:Apache License

private List<String> extractSanFromCsr(JcaPKCS10CertificationRequest csr) {
    List<String> sans = new ArrayList<>();
    Attribute[] certAttributes = csr.getAttributes();
    for (Attribute attribute : certAttributes) {
        if (attribute.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
            GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
            GeneralName[] names = gns.getNames();
            for (GeneralName name : names) {
                logger.info("Type: " + name.getTagNo() + " | Name: " + name.getName());
                String title = "";
                if (name.getTagNo() == GeneralName.dNSName) {
                    title = "DNS";
                } else if (name.getTagNo() == GeneralName.iPAddress) {
                    title = "IP Address";
                    // name.toASN1Primitive();
                } else if (name.getTagNo() == GeneralName.otherName) {
                    title = "Other Name";
                }/*from  w w  w .j  a  v a2  s .  c  o  m*/
                sans.add(title + ": " + name.getName());
            }
        }
    }

    return sans;
}

From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public String getPassword() {
    if (password != null) {
        return password;
    }// w ww. j  a  va2s . c  o m
    try {
        if (pkcs10 == null) {
            init();
        }
    } catch (NullPointerException e) {
        log.error("PKCS10 not initated! " + e.getMessage());
        return null;
    }

    String ret = null;
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
    ASN1Encodable obj = null;
    if (attributes.length == 0) {
        // See if we have it embedded in an extension request instead
        attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (attributes.length == 0) {
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug("got extension request");
        }
        ASN1Set values = attributes[0].getAttrValues();
        if (values.size() == 0) {
            return null;
        }
        Extensions exts = Extensions.getInstance(values.getObjectAt(0));
        Extension ext = exts.getExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
        if (ext == null) {
            if (log.isDebugEnabled()) {
                log.debug("no challenge password extension");
            }
            return null;
        }
        obj = ext.getExtnValue();
    } else {
        // If it is a challengePassword directly, it's just to grab the value
        ASN1Set values = attributes[0].getAttrValues();
        obj = values.getObjectAt(0);
    }

    if (obj != null) {
        ASN1String str = null;

        try {
            str = DERPrintableString.getInstance((obj));
        } catch (IllegalArgumentException ie) {
            // This was not printable string, should be utf8string then according to pkcs#9 v2.0
            str = DERUTF8String.getInstance((obj));
        }

        if (str != null) {
            ret = str.getString();
        }
    }

    return ret;
}

From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public Extensions getRequestExtensions() {
    try {/* www.ja v  a  2 s . c o m*/
        if (pkcs10 == null) {
            init();
        }
    } catch (NullPointerException e) {
        log.error("PKCS10 not inited! " + e.getMessage());
        return null;
    }
    Extensions ret = null;

    // Get attributes
    // The X509 extension is in a a pkcs_9_at_extensionRequest

    // See if we have it embedded in an extension request instead
    Attribute[] attr = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    if (attr.length != 0) {
        if (log.isDebugEnabled()) {
            log.debug("got request extension");
        }
        ASN1Set values = attr[0].getAttrValues();
        if (values.size() > 0) {
            try {
                ret = Extensions.getInstance(values.getObjectAt(0));
            } catch (IllegalArgumentException e) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "pkcs_9_extensionRequest does not contain Extensions that it should, ignoring invalid encoded extension request.");
                }
            }
        }
    }

    return ret;
}