Example usage for org.bouncycastle.asn1.x509 GeneralName getName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName getName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName getName.

Prototype

public ASN1Encodable getName() 

Source Link

Usage

From source file:org.cesecore.util.CertTools.java

License:Open Source License

/**
 * Gets an altName string from an X509Extension
 * //from  ww  w. j a va2s  .c o  m
 * @param ext X509Extension with AlternativeNames
 * @return String as defined in method getSubjectAlternativeName
 */
public static String getAltNameStringFromExtension(Extension ext) {
    String altName = null;
    // GeneralNames
    ASN1Encodable gnames = ext.getParsedValue();
    if (gnames != null) {
        try {
            GeneralNames names = GeneralNames.getInstance(gnames);
            GeneralName[] gns = names.getNames();
            for (GeneralName gn : gns) {
                int tag = gn.getTagNo();
                ASN1Encodable name = gn.getName();
                String str = CertTools.getGeneralNameString(tag, name);
                if (str == null) {
                    continue;
                }
                if (altName == null) {
                    altName = str;
                } else {
                    altName += ", " + str;
                }
            }
        } catch (IOException e) {
            log.error("IOException parsing altNames: ", e);
            return null;
        }
    }
    return altName;
}

From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java

License:Open Source License

/**
 * Attempts to grab additional OCSP server urls off of the given {@param cert}.
 *
 * @param - the {@link X509Certificate} to check.
 * @return {@link List} of additional OCSP server urls found on the given {@param cert}.
 *///from ww  w  .  j  a  v a 2  s. c  om
private List<String> getOcspUrlsFromCert(X509Certificate cert) {
    List<String> ocspUrls = new ArrayList<>();

    try {
        byte[] authorityInfoAccess = cert.getExtensionValue(Extension.authorityInfoAccess.getId());

        if (authorityInfoAccess == null) {
            return ocspUrls;
        }

        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(X509ExtensionUtil.fromExtensionValue(authorityInfoAccess));

        if (authorityInformationAccess == null) {
            return ocspUrls;
        }

        for (AccessDescription description : authorityInformationAccess.getAccessDescriptions()) {
            GeneralName accessLocation = description.getAccessLocation();
            if (accessLocation.getTagNo() == GeneralName.uniformResourceIdentifier)
                ocspUrls.add(((DERIA5String) accessLocation.getName()).getString());
        }
    } catch (IOException e) {
        LOGGER.debug("Problem retrieving the OCSP server url(s) from the certificate." + CONTINUING_MSG, e);
    }

    return ocspUrls;
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

/**
 * Check the private key archive control in the certification request
 *
 * @throws OperatorCreationException//from  ww w  .  j  ava2s.  co m
 * @throws PKICMPMessageException
 * @throws CertificateEncodingException
 * @throws IOException
 * @throws CRMFException
 * @throws CMPException
 * @throws CMSException
 */
@Test
public void testCertificationWithPrivateKeyControl()
        throws OperatorCreationException, PKICMPMessageException, CertificateException, IOException,
        CRMFException, CMPException, CMSException, InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchFieldException, IllegalAccessException, CRLException {
    String distinguishedName = pki.getTestUser1Cert().getSubjectX500Principal().getName();

    KeyPair keyPair = new KeyPair(pki.getTestUser1Cert().getPublicKey(), pki.getTestUser1CertPrivateKey());

    PKICMPMessages pkiMessages = new PKICMPMessages();
    pkiMessages.setPkiKeyStore(pkiKeyStoreRA);
    byte[] result = pkiMessages.createCertificateMessageWithLocalKey(distinguishedName, keyPair);

    ASN1InputStream asn1InputStream = new ASN1InputStream(result);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    PKIMessage pkiMessage = PKIMessage.getInstance(asn1Primitive);

    CertReqMsg[] certReqMsgs = CertReqMessages.getInstance(pkiMessage.getBody().getContent())
            .toCertReqMsgArray();
    AttributeTypeAndValue[] attributeTypeAndValues = certReqMsgs[0].getCertReq().getControls()
            .toAttributeTypeAndValueArray();
    GeneratePKI genPKI = new GeneratePKI();
    genPKI.createPKI();

    boolean bFound = false;
    for (AttributeTypeAndValue attributeTypeAndValue : attributeTypeAndValues) {
        if (attributeTypeAndValue.getType().equals(CRMFObjectIdentifiers.id_regCtrl_pkiArchiveOptions)) {
            PKIArchiveControl pkiArchiveControl = new PKIArchiveControl(
                    PKIArchiveOptions.getInstance(attributeTypeAndValue.getValue()));

            // Decrypt data
            CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(
                    pkiArchiveControl.getEnvelopedData().getEncoded());
            RecipientInformationStore recipients = cmsEnvelopedDataParser.getRecipientInfos();
            Collection c = recipients.getRecipients();
            Iterator it = c.iterator();

            if (it.hasNext()) {
                RecipientInformation recipient = (RecipientInformation) it.next();
                byte[] recdata = recipient
                        .getContent(new JceKeyTransEnvelopedRecipient(genPKI.getSubCACertPrivateKey())
                                .setProvider(pkiKeyStoreRA.getProvider()));
                ASN1InputStream tstAsn1InputStream = new ASN1InputStream(recdata);
                ASN1Primitive tstAsn1Primitive = tstAsn1InputStream.readObject();
                EncKeyWithID encKeyWithID = EncKeyWithID.getInstance(tstAsn1Primitive);
                Assert.assertArrayEquals(keyPair.getPrivate().getEncoded(),
                        encKeyWithID.getPrivateKey().getEncoded());
                Assert.assertTrue(encKeyWithID.hasIdentifier());
                GeneralName identifier = GeneralName.getInstance(encKeyWithID.getIdentifier());
                Assert.assertEquals(genPKI.getTestUser1Cert().getSubjectDN().getName(),
                        identifier.getName().toString());
                bFound = true;
            }
        }
    }

    Assert.assertTrue(bFound);

}

From source file:org.cryptacular.util.CertUtil.java

License:Open Source License

/**
 * Gets a list of all subject names defined for the given certificate. The
 * list includes the first common name (CN) specified in the subject
 * distinguished name (if defined) and all subject alternative names.
 *
 * @param  cert  X.509 certificate to examine.
 *
 * @return  List of subject names.// www . j  ava  2 s  .c om
 */
public static List<String> subjectNames(final X509Certificate cert) {
    final List<String> names = new ArrayList<>();
    final String cn = subjectCN(cert);
    if (cn != null) {
        names.add(cn);
    }

    final GeneralNames altNames = subjectAltNames(cert);
    if (altNames == null) {
        return names;
    }
    for (GeneralName name : altNames.getNames()) {
        names.add(name.getName().toString());
    }
    return names;
}

From source file:org.cryptacular.util.CertUtil.java

License:Open Source License

/**
 * Gets a list of subject names defined for the given certificate. The list
 * includes the first common name (CN) specified in the subject distinguished
 * name (if defined) and all subject alternative names of the given type.
 *
 * @param  cert  X.509 certificate to examine.
 * @param  types  One or more subject alternative name types to fetch.
 *
 * @return  List of subject names.//from  w w  w . j  ava  2  s .  co  m
 */
public static List<String> subjectNames(final X509Certificate cert, final GeneralNameType... types) {
    final List<String> names = new ArrayList<>();
    final String cn = subjectCN(cert);
    if (cn != null) {
        names.add(cn);
    }

    final GeneralNames altNames = subjectAltNames(cert, types);
    if (altNames == null) {
        return names;
    }
    for (GeneralName name : altNames.getNames()) {
        names.add(name.getName().toString());
    }
    return names;
}

From source file:org.demoiselle.signer.core.extension.BasicCertificate.java

License:Open Source License

/**
 * /*  w w  w .j a v  a2 s.  c om*/
 * @return A list of ulrs that inform the location of the certificate revocation lists
 * @throws IOException exception
 */
public List<String> getCRLDistributionPoint() throws IOException {

    List<String> crlUrls = new ArrayList<>();
    ASN1Primitive primitive = getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (primitive == null) {
        return null;
    }
    CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(primitive);
    DistributionPoint[] distributionPoints = crlDistPoint.getDistributionPoints();

    for (DistributionPoint distributionPoint : distributionPoints) {
        DistributionPointName dpn = distributionPoint.getDistributionPoint();
        // Look for URIs in fullName
        if (dpn != null) {
            if (dpn.getType() == DistributionPointName.FULL_NAME) {
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                for (GeneralName genName : genNames) {
                    if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        String url = DERIA5String.getInstance(genName.getName()).getString();
                        crlUrls.add(url);
                        logger.info("Adicionando a url {}", url);
                    }
                }
            }
        }
    }
    return crlUrls;
}

From source file:org.dihedron.crypto.crl.CRL.java

License:Open Source License

/**
 * Extracts all CRL distribution point URLs from the "CRL Distribution Point" 
 * extension in a X.509 certificate. If CRL distribution point extension is 
 * unavailable, returns an empty list./*from   w w w  .  ja  v a2s.  c  om*/
 */
public static List<String> getCrlDistributionPoints(X509Certificate certificate)
        throws CertificateParsingException, IOException {

    List<String> urls = new ArrayList<>();

    byte[] extension = certificate.getExtensionValue(Extension.cRLDistributionPoints.getId());
    if (extension == null) {
        // return an empty list
        return urls;
    }

    try (ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(extension))) {
        byte[] crldpExtOctets = ((DEROctetString) oAsnInStream.readObject()).getOctets();
        try (ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(crldpExtOctets))) {
            for (DistributionPoint dp : CRLDistPoint.getInstance(oAsnInStream2.readObject())
                    .getDistributionPoints()) {
                DistributionPointName name = dp.getDistributionPoint();
                // look for URIs in fullName
                if (name != null && name.getType() == DistributionPointName.FULL_NAME) {
                    GeneralName[] generalNames = GeneralNames.getInstance(name.getName()).getNames();
                    // look for an URI
                    for (GeneralName generalName : generalNames) {
                        if (generalName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                            String url = DERIA5String.getInstance(generalName.getName()).getString();
                            urls.add(url);
                        }
                    }
                }
            }
            return urls;
        }
    }
}

From source file:org.ejbca.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the 'NameRegistrationAuthorities' defined in the QCStatement extension (rfc3739).
 * /*from  ww  w . ja  v  a 2  s.c  om*/
 * @param cert Certificate containing the extension
 * @return String with for example 'rfc822Name=foo2bar.se, rfc822Name=bar2foo.se' etc. Supports email, dns and uri name, or null of no RAs are found.
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementAuthorities(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final DERObject obj = getExtensionValue(x509cert, X509Extensions.QCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        SemanticsInformation si = null;
        // Look through all the QCStatements and see if we have a standard RFC3739 pkixQCSyntax
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final DERObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && (oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1)
                    || oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2))) {
                // We MAY have a SemanticsInformation object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    si = SemanticsInformation.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (si != null) {
            final GeneralName[] gns = si.getNameRegistrationAuthorities();
            if (gns == null) {
                return null;
            }
            final StringBuilder strBuf = new StringBuilder();
            for (int i = 0; i < gns.length; i++) {
                final GeneralName gn = gns[i];
                if (strBuf.length() != 0) {
                    // Append comma so we get nice formatting if there are more than one authority
                    strBuf.append(", ");
                }
                final String str = getGeneralNameString(gn.getTagNo(), gn.getName());
                if (str != null) {
                    strBuf.append(str);
                }
            }
            if (strBuf.length() > 0) {
                ret = strBuf.toString();
            }
        }
    }
    return ret;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/** Gets an altName string from an X509Extension
 * /*  w  ww.  ja  v  a 2s . c om*/
 * @param ext X509Extension with AlternativeNames
 * @return String as defined in method getSubjectAlternativeName
 */
public static String getAltNameStringFromExtension(X509Extension ext) {
    String altName = null;
    //GeneralNames
    ASN1OctetString octs = ext.getValue();
    if (octs != null) {
        ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
        DERObject obj;
        try {
            obj = aIn.readObject();
            GeneralNames gan = GeneralNames.getInstance(obj);
            GeneralName[] gns = gan.getNames();
            for (int i = 0; i < gns.length; i++) {
                GeneralName gn = gns[i];
                int tag = gn.getTagNo();
                DEREncodable name = gn.getName();
                String str = CertTools.getGeneralNameString(tag, name);
                if (altName == null) {
                    altName = str;
                } else {
                    altName += ", " + str;
                }
            }
        } catch (IOException e) {
            log.error("IOException parsing altNames: ", e);
            return null;
        }
    }
    return altName;
}

From source file:org.elasticsearch.xpack.core.ssl.CertificateGenerateToolTests.java

License:Open Source License

private void assertSubjAltNames(GeneralNames subjAltNames, CertificateInformation certInfo) throws Exception {
    final int expectedCount = certInfo.ipAddresses.size() + certInfo.dnsNames.size()
            + certInfo.commonNames.size();
    assertEquals(expectedCount, subjAltNames.getNames().length);
    Collections.sort(certInfo.dnsNames);
    Collections.sort(certInfo.ipAddresses);
    for (GeneralName generalName : subjAltNames.getNames()) {
        if (generalName.getTagNo() == GeneralName.dNSName) {
            String dns = ((ASN1String) generalName.getName()).getString();
            assertTrue(certInfo.dnsNames.stream().anyMatch(dns::equals));
        } else if (generalName.getTagNo() == GeneralName.iPAddress) {
            byte[] ipBytes = DEROctetString.getInstance(generalName.getName()).getOctets();
            String ip = NetworkAddress.format(InetAddress.getByAddress(ipBytes));
            assertTrue(certInfo.ipAddresses.stream().anyMatch(ip::equals));
        } else if (generalName.getTagNo() == GeneralName.otherName) {
            ASN1Sequence seq = ASN1Sequence.getInstance(generalName.getName());
            assertThat(seq.size(), equalTo(2));
            assertThat(seq.getObjectAt(0), instanceOf(ASN1ObjectIdentifier.class));
            assertThat(seq.getObjectAt(0).toString(), equalTo(CN_OID));
            assertThat(seq.getObjectAt(1), instanceOf(DERTaggedObject.class));
            DERTaggedObject taggedName = (DERTaggedObject) seq.getObjectAt(1);
            assertThat(taggedName.getTagNo(), equalTo(0));
            assertThat(taggedName.getObject(), instanceOf(ASN1String.class));
            assertThat(taggedName.getObject().toString(), Matchers.isIn(certInfo.commonNames));
        } else {//from  www.  j a  v  a2s  .  c o  m
            fail("unknown general name with tag " + generalName.getTagNo());
        }
    }
}