Example usage for java.security.cert X509Certificate getIssuerX500Principal

List of usage examples for java.security.cert X509Certificate getIssuerX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getIssuerX500Principal.

Prototype

public X500Principal getIssuerX500Principal() 

Source Link

Document

Returns the issuer (issuer distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Gets the trusted responder certificate. The response contains the responder certificate, however we cannot blindly trust it. Instead, we use a configured trusted CA. If the responder
 * certificate is a trusted CA, then we can use it. If the responder certificate is not directly trusted, we still may be able to trust it if it was issued by the same CA that issued the subject
 * certificate. Other various checks may be required (this portion is currently not implemented).
 *
 * @param responderCertificateHolder cert
 * @param issuerCertificate          cert
 * @return cert/*w  w  w  .j a  v a  2  s .c o  m*/
 */
private X509Certificate getTrustedResponderCertificate(final X509CertificateHolder responderCertificateHolder,
        final X509Certificate issuerCertificate) throws CertificateException {
    // look for the responder's certificate specifically
    final X509Certificate responderCertificate = new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate(responderCertificateHolder);
    final String trustedCAName = responderCertificate.getSubjectX500Principal().getName();
    if (trustedCAs.containsKey(trustedCAName)) {
        return trustedCAs.get(trustedCAName);
    }

    // if the responder certificate was issued by the same CA that issued the subject certificate we may be able to use that...
    final X500Principal issuerCA = issuerCertificate.getSubjectX500Principal();
    if (responderCertificate.getIssuerX500Principal().equals(issuerCA)) {
        // perform a number of verification steps... TODO... from sun.security.provider.certpath.OCSPResponse.java... currently incomplete...
        //            try {
        //                // ensure appropriate key usage
        //                final List<String> keyUsage = responderCertificate.getExtendedKeyUsage();
        //                if (keyUsage == null || !keyUsage.contains(KP_OCSP_SIGNING_OID)) {
        //                    return null;
        //                }
        //
        //                // ensure the certificate is valid
        //                responderCertificate.checkValidity();
        //
        //                // verify the signature
        //                responderCertificate.verify(issuerCertificate.getPublicKey());
        //
        //                return responderCertificate;
        //            } catch (final CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        //                return null;
        //            }
        return null;
    } else {
        return null;
    }
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

@Override
public boolean isNodeCertificateValid(String issuerDN) throws CertificateException {
    KeyStore keyStore = loadKeyStore();
    X509Certificate x509 = null;//from w w  w .j  av a 2s .  c om
    try {
        if (keyStore == null || !keyStore.containsAlias(nodeAlias)) {
            return false;
        }
        Certificate cert = keyStore.getCertificate(nodeAlias);
        if (!(cert instanceof X509Certificate)) {
            return false;
        }
        x509 = (X509Certificate) cert;
        x509.checkValidity();
        X500Principal issuer = new X500Principal(issuerDN);
        if (!x509.getIssuerX500Principal().equals(issuer)) {
            log.debug("Certificate issuer {} not same as expected {}", x509.getIssuerX500Principal().getName(),
                    issuer.getName());
            return false;
        }
        return true;
    } catch (KeyStoreException e) {
        throw new CertificateException("Error checking for node certificate", e);
    } catch (CertificateExpiredException e) {
        log.debug("Certificate {} has expired", x509.getSubjectDN().getName());
    } catch (CertificateNotYetValidException e) {
        log.debug("Certificate {} not valid yet", x509.getSubjectDN().getName());
    }
    return false;
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from  w  w  w  .j  av  a  2  s  . c o m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Secure session established");
            LOGGER.debug(" negotiated protocol: {}", session.getProtocol());
            LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                LOGGER.debug(" peer principal: {}", peer);
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" peer alternative names: {}", altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                LOGGER.debug(" issuer principal: {}", issuer);
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" issuer alternative names: {}", altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (RuntimeException | IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            iox.addSuppressed(x);
        }
        throw iox;
    }
}

From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java

/**
 * Sets the input for this composite. /*from w w w. j a  v  a2  s. c o m*/
 *
 * @param certificateChain certificate chain input
 */
public void setInput(X509Certificate[] certificateChain) {
    X509Certificate certificate = certificateChain[0];

    X500Principal issuedToPrincipal = certificate.getSubjectX500Principal();
    Map<String, String> issuedToAttributes = getAttributeMap(issuedToPrincipal);
    issuedToCN.setText(issuedToAttributes.get("CN")); //$NON-NLS-1$
    issuedToO.setText(issuedToAttributes.get("O")); //$NON-NLS-1$
    issuedToOU.setText(issuedToAttributes.get("OU")); //$NON-NLS-1$
    serialNumber.setText(certificate.getSerialNumber().toString(16));

    X500Principal issuedFromPrincipal = certificate.getIssuerX500Principal();
    Map<String, String> issuedFromAttributes = getAttributeMap(issuedFromPrincipal);
    issuedByCN.setText(issuedFromAttributes.get("CN")); //$NON-NLS-1$
    issuedByO.setText(issuedFromAttributes.get("O")); //$NON-NLS-1$
    issuedByOU.setText(issuedFromAttributes.get("OU")); //$NON-NLS-1$

    issuesOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotBefore()));
    expiresOn.setText(DateFormatUtils.ISO_DATE_FORMAT.format(certificate.getNotAfter()));

    byte[] encoded2 = null;

    try {
        encoded2 = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
    }

    byte[] md5 = DigestUtils.md5(encoded2);
    String md5HexString = getHexString(md5);
    fingerprintMD5.setText(md5HexString);
    byte[] sha = DigestUtils.sha(encoded2);
    String shaHexString = getHexString(sha);
    fingerprintSHA1.setText(shaHexString);

    // Details: certificate chain
    CertificateChainItem parentItem = null;
    CertificateChainItem certificateItem = null;

    for (X509Certificate cert : certificateChain) {
        CertificateChainItem item = new CertificateChainItem(cert);

        if (parentItem != null) {
            item.child = parentItem;
            parentItem.parent = item;
        }

        if (certificateItem == null) {
            certificateItem = item;
        }

        parentItem = item;
    }

    hierarchyTreeViewer.setInput(new CertificateChainItem[] { parentItem });
    hierarchyTreeViewer.expandAll();
    hierarchyTreeViewer.setSelection(new StructuredSelection(certificateItem), true);

    // Details: 
    certificateTree.removeAll();
    populateCertificateTree();
    valueText.setText(StringUtils.EMPTY);
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   ww w.  j a va 2 s.co  m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

/**
 * Gives back the JAXB CertID data structure.
 * //w  w  w.j av a  2s  .c o  m
 * @param certificate
 * @param xadesObjectFactory
 * @param xmldsigObjectFactory
 * @param digestAlgorithm
 * @return
 */
private CertIDType getCertID(X509Certificate certificate) {

    CertIDType certId = xades13ObjectFactory.createCertIDType();

    X509IssuerSerialType issuerSerial = getDsObjectFactory().createX509IssuerSerialType();
    certId.setIssuerSerial(issuerSerial);
    String issuerName = certificate.getIssuerX500Principal().toString();
    issuerSerial.setX509IssuerName(issuerName);
    issuerSerial.setX509SerialNumber(certificate.getSerialNumber());

    byte[] encodedCertificate;
    try {
        encodedCertificate = certificate.getEncoded();
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
    }
    DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, DigestAlgorithm.SHA1);
    certId.setCertDigest(certDigest);

    return certId;
}

From source file:org.opensc.pkcs11.spi.PKCS11KeyStoreSpi.java

@Override
public Certificate[] engineGetCertificateChain(String name) {
    Certificate endEntity = engineGetCertificate(name);

    if (endEntity == null)
        return null;

    if (!(endEntity instanceof X509Certificate)) {
        log.error("engineGetCertificateChain: Only X.509 certificates are supported.");
        return null;
    }/*from ww  w  .ja  va  2  s  .c o m*/

    List<Certificate> ret = new ArrayList<Certificate>();

    ret.add(endEntity);

    X509Certificate x509Certificate = (X509Certificate) endEntity;

    try {
        // OK ,this is acrude form of certificate chain evaluation.
        // Assuming, that the upper layer does a more detailed anlysis of the
        // validity period and key extensions, we only search the chain by
        // finding the issuing certificate on the token using the issuer DN
        // and trying to check the Signature on the certificate using the
        // public key on the next certificate.
        while (!isRootCA(x509Certificate)) {
            Map<String, PKCS11KSEntry> centries = getAllCertificatesForSubject(
                    x509Certificate.getIssuerX500Principal());

            X509Certificate x509NextCert = null;

            for (PKCS11KSEntry entry : centries.values()) {
                Certificate next = entry.getDecodedCertificate();

                X509Certificate x509Next = (X509Certificate) next;

                if (!x509Next.getSubjectX500Principal().equals(x509Certificate.getIssuerX500Principal()))
                    continue;

                try {
                    x509Certificate.verify(x509Next.getPublicKey());
                    x509NextCert = x509Next;
                    break;
                } catch (Exception e) {
                    log.warn("Exception during evaluation of certificate chain:", e);
                }
            }

            if (x509NextCert == null) {
                //throw new CertificateException("Cannot find the issuing CA for certificate ["+x509Certificate+"].");
                break; // to allow chains with one/leaf certificate only
            }

            x509Certificate = x509NextCert;
            ret.add(x509Certificate);
        }

        return ret.toArray(new Certificate[0]);

    } catch (Exception e) {
        log.error("Exception caught during analysis of the certificate chain:", e);
    }
    return null;
}

From source file:eu.europa.ec.markt.dss.report.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * //ww w  . j a  v  a2s .  c om
 * @param tsl
 *            the TrustServiceList to export
 * @param pdfFile
 *            the file to generate
 * @return
 * @throws IOException
 */
public void humanReadableExport(final TrustServiceList tsl, final File pdfFile) {
    Document document = new Document();
    OutputStream outputStream;
    try {
        outputStream = new FileOutputStream(pdfFile);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("file not found: " + pdfFile.getAbsolutePath(), e);
    }
    try {
        final PdfWriter pdfWriter = PdfWriter.getInstance(document, outputStream);
        pdfWriter.setPDFXConformance(PdfWriter.PDFA1B);

        // title
        final EUCountry country = EUCountry.valueOf(tsl.getSchemeTerritory());
        final String title = country.getShortSrcLangName() + " (" + country.getShortEnglishName()
                + "): Trusted List";

        Phrase footerPhrase = new Phrase("PDF document generated on " + new Date().toString() + ", page ",
                headerFooterFont);
        HeaderFooter footer = new HeaderFooter(footerPhrase, true);
        document.setFooter(footer);

        Phrase headerPhrase = new Phrase(title, headerFooterFont);
        HeaderFooter header = new HeaderFooter(headerPhrase, false);
        document.setHeader(header);

        document.open();
        addTitle(title, title0Font, Paragraph.ALIGN_CENTER, 0, 20, document);

        addLongItem("Scheme name", tsl.getSchemeName(), document);
        addLongItem("Legal Notice", tsl.getLegalNotice(), document);

        // information table
        PdfPTable informationTable = createInfoTable();
        addItemRow("Scheme territory", tsl.getSchemeTerritory(), informationTable);
        addItemRow("Scheme status determination approach",
                substringAfter(tsl.getStatusDeterminationApproach(), "StatusDetn/"), informationTable);

        final List<String> schemeTypes = new ArrayList<String>();
        for (final String schemeType : tsl.getSchemeTypes()) {
            schemeTypes.add(schemeType);
        }
        addItemRow("Scheme type community rules", schemeTypes, informationTable);

        addItemRow("Issue date", tsl.getListIssueDateTime().toString(), informationTable);
        addItemRow("Next update", tsl.getNextUpdate().toString(), informationTable);
        addItemRow("Historical information period", tsl.getHistoricalInformationPeriod().toString() + " days",
                informationTable);
        addItemRow("Sequence number", tsl.getSequenceNumber().toString(), informationTable);
        addItemRow("Scheme information URIs", tsl.getSchemeInformationUris(), informationTable);

        document.add(informationTable);

        addTitle("Scheme Operator", title1Font, Paragraph.ALIGN_CENTER, 0, 10, document);

        informationTable = createInfoTable();
        addItemRow("Scheme operator name", tsl.getSchemeOperatorName(), informationTable);
        PostalAddressType schemeOperatorPostalAddress = tsl.getSchemeOperatorPostalAddress(Locale.ENGLISH);
        addItemRow("Scheme operator street address", schemeOperatorPostalAddress.getStreetAddress(),
                informationTable);
        addItemRow("Scheme operator postal code", schemeOperatorPostalAddress.getPostalCode(),
                informationTable);
        addItemRow("Scheme operator locality", schemeOperatorPostalAddress.getLocality(), informationTable);
        addItemRow("Scheme operator state", schemeOperatorPostalAddress.getStateOrProvince(), informationTable);
        addItemRow("Scheme operator country", schemeOperatorPostalAddress.getCountryName(), informationTable);

        List<String> schemeOperatorElectronicAddressess = tsl.getSchemeOperatorElectronicAddresses();
        addItemRow("Scheme operator contact", schemeOperatorElectronicAddressess, informationTable);
        document.add(informationTable);

        addTitle("Trust Service Providers", title1Font, Paragraph.ALIGN_CENTER, 10, 2, document);

        List<TrustServiceProvider> trustServiceProviders = tsl.getTrustServiceProviders();
        for (TrustServiceProvider trustServiceProvider : trustServiceProviders) {
            addTitle(trustServiceProvider.getName(), title1Font, Paragraph.ALIGN_LEFT, 10, 2, document);

            PdfPTable providerTable = createInfoTable();
            addItemRow("Service provider trade name", trustServiceProvider.getTradeName(), providerTable);
            addItemRow("Information URI", trustServiceProvider.getInformationUris(), providerTable);
            PostalAddressType postalAddress = trustServiceProvider.getPostalAddress();
            addItemRow("Service provider street address", postalAddress.getStreetAddress(), providerTable);
            addItemRow("Service provider postal code", postalAddress.getPostalCode(), providerTable);
            addItemRow("Service provider locality", postalAddress.getLocality(), providerTable);
            addItemRow("Service provider state", postalAddress.getStateOrProvince(), providerTable);
            addItemRow("Service provider country", postalAddress.getCountryName(), providerTable);
            document.add(providerTable);

            List<TrustService> trustServices = trustServiceProvider.getTrustServices();
            for (TrustService trustService : trustServices) {
                addTitle(trustService.getName(), title2Font, Paragraph.ALIGN_LEFT, 10, 2, document);
                PdfPTable serviceTable = createInfoTable();
                addItemRow("Type", substringAfter(trustService.getType(), "Svctype/"), serviceTable);
                addItemRow("Status", substringAfter(trustService.getStatus(), "Svcstatus/"), serviceTable);
                addItemRow("Status starting time", trustService.getStatusStartingTime().toString(),
                        serviceTable);
                document.add(serviceTable);

                addTitle("Service digital identity (X509)", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                final X509Certificate certificate = trustService.getServiceDigitalIdentity();
                final PdfPTable serviceIdentityTable = createInfoTable();
                addItemRow("Version", Integer.toString(certificate.getVersion()), serviceIdentityTable);
                addItemRow("Serial number", certificate.getSerialNumber().toString(), serviceIdentityTable);
                addItemRow("Signature algorithm", certificate.getSigAlgName(), serviceIdentityTable);
                addItemRow("Issuer", certificate.getIssuerX500Principal().toString(), serviceIdentityTable);
                addItemRow("Valid from", certificate.getNotBefore().toString(), serviceIdentityTable);
                addItemRow("Valid to", certificate.getNotAfter().toString(), serviceIdentityTable);
                addItemRow("Subject", certificate.getSubjectX500Principal().toString(), serviceIdentityTable);
                addItemRow("Public key", certificate.getPublicKey().toString(), serviceIdentityTable);
                // TODO certificate policies
                addItemRow("Subject key identifier", toHex(getSKId(certificate)), serviceIdentityTable);
                addItemRow("CRL distribution points", getCrlDistributionPoints(certificate),
                        serviceIdentityTable);
                addItemRow("Authority key identifier", toHex(getAKId(certificate)), serviceIdentityTable);
                addItemRow("Key usage", getKeyUsage(certificate), serviceIdentityTable);
                addItemRow("Basic constraints", getBasicConstraints(certificate), serviceIdentityTable);

                byte[] encodedCertificate;
                try {
                    encodedCertificate = certificate.getEncoded();
                } catch (CertificateEncodingException e) {
                    throw new RuntimeException("cert: " + e.getMessage(), e);
                }
                addItemRow("SHA1 Thumbprint", DigestUtils.shaHex(encodedCertificate), serviceIdentityTable);
                addItemRow("SHA256 Thumbprint", DigestUtils.sha256Hex(encodedCertificate),
                        serviceIdentityTable);
                document.add(serviceIdentityTable);

                List<ExtensionType> extensions = trustService.getExtensions();
                for (ExtensionType extension : extensions) {
                    printExtension(extension, document);
                }

                addLongMonoItem("The decoded certificate:", certificate.toString(), document);
                addLongMonoItem("The certificate in PEM format:", toPem(certificate), document);
            }
        }

        X509Certificate signerCertificate = tsl.verifySignature();
        if (null != signerCertificate) {
            Paragraph tslSignerTitle = new Paragraph("Trusted List Signer", title1Font);
            tslSignerTitle.setAlignment(Paragraph.ALIGN_CENTER);
            document.add(tslSignerTitle);

            final PdfPTable signerTable = createInfoTable();
            addItemRow("Subject", signerCertificate.getSubjectX500Principal().toString(), signerTable);
            addItemRow("Issuer", signerCertificate.getIssuerX500Principal().toString(), signerTable);
            addItemRow("Not before", signerCertificate.getNotBefore().toString(), signerTable);
            addItemRow("Not after", signerCertificate.getNotAfter().toString(), signerTable);
            addItemRow("Serial number", signerCertificate.getSerialNumber().toString(), signerTable);
            addItemRow("Version", Integer.toString(signerCertificate.getVersion()), signerTable);
            byte[] encodedPublicKey = signerCertificate.getPublicKey().getEncoded();
            addItemRow("Public key SHA1 Thumbprint", DigestUtils.shaHex(encodedPublicKey), signerTable);
            addItemRow("Public key SHA256 Thumbprint", DigestUtils.sha256Hex(encodedPublicKey), signerTable);
            document.add(signerTable);

            addLongMonoItem("The decoded certificate:", signerCertificate.toString(), document);
            addLongMonoItem("The certificate in PEM format:", toPem(signerCertificate), document);
            addLongMonoItem("The public key in PEM format:", toPem(signerCertificate.getPublicKey()), document);
        }

        document.close();
    } catch (DocumentException e) {
        throw new RuntimeException("PDF document error: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new RuntimeException("Exception: " + e.getMessage(), e);
    }
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test search criteria. There's no easy way to check the subject key id and
 * authority key id - we can get the extension's bytes but still need to
 * parse them./* ww w .j a  v  a2  s  .  c  om*/
 */
@Test
public void testTestSearchCriteria() throws GeneralSecurityException {

    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setBasicConstraints(true);
    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);
    X509Certificate cert = builder.build(keyPair.getPrivate());

    assertEquals(certUtil.getFingerprint(cert), toHex(DigestUtils.sha(cert.getEncoded())));
    assertEquals(certUtil.getCertificateHash(cert), rfc4387(cert.getEncoded()));
    assertEquals(certUtil.getIHash(cert), rfc4387(cert.getIssuerX500Principal().getEncoded()));
    assertEquals(certUtil.getSHash(cert), rfc4387(cert.getSubjectX500Principal().getEncoded()));
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validatePem(CertificateBundle certificateBundle, String subjectName)
        throws CertificateException, IOException, KeyVaultErrorException, IllegalArgumentException,
        InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, BadPaddingException {
    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());
    String secretValue = secret.value();

    // Extract private key from PEM
    PrivateKey secretPrivateKey = extractPrivateKeyFromPemContents(secretValue);
    Assert.assertNotNull(secretPrivateKey);

    // Extract certificates from PEM
    List<X509Certificate> certificates = extractCertificatesFromPemContents(secretValue);
    Assert.assertNotNull(certificates);/*w w w  .j  av  a2  s  .c o  m*/
    Assert.assertTrue(certificates.size() == 1);

    // has the public key corresponding to the private key.
    X509Certificate secretCertificate = certificates.get(0);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}