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.ws.security.components.crypto.Merlin.java

/**
 * Get an X509 Certificate (chain) of the X500Principal argument in the supplied KeyStore 
 * @param subjectRDN either an X500Principal or a BouncyCastle X509Name instance.
 * @param store The KeyStore//  w w w.  j a v  a  2  s  .  com
 * @return an X509 Certificate (chain)
 * @throws WSSecurityException
 */
private Certificate[] getCertificates(Object issuerRDN, BigInteger serialNumber, KeyStore store)
        throws WSSecurityException {
    try {
        for (Enumeration<String> e = store.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate cert = null;
            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) cert;
                if (x509cert.getSerialNumber().compareTo(serialNumber) == 0) {
                    Object certName = createBCX509Name(x509cert.getIssuerX500Principal().getName());
                    if (certName.equals(issuerRDN)) {
                        return certs;
                    }
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return new Certificate[] {};
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected X509Certificate checkCmpCertRepMessage(X500Name userDN, Certificate cacert, byte[] retMsg,
        int requestId) throws Exception {
    ///*  www .  j av a2s  .c o  m*/
    // Parse response message
    //
    assertTrue(cacert instanceof X509Certificate);
    PKIMessage respObject = null;
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // Verify body type
    PKIBody body = respObject.getBody();
    int tag = body.getType();
    assertEquals(1, tag);

    // Verify the response
    CertRepMessage c = (CertRepMessage) body.getContent();
    assertNotNull(c);
    CertResponse resp = c.getResponse()[0];
    assertNotNull(resp);
    assertEquals(resp.getCertReqId().getValue().intValue(), requestId);

    // Verify response status
    PKIStatusInfo info = resp.getStatus();
    assertNotNull(info);
    assertEquals(0, info.getStatus().intValue());

    // Verify response certificate
    CertifiedKeyPair kp = resp.getCertifiedKeyPair();
    assertNotNull(kp);
    CertOrEncCert cc = kp.getCertOrEncCert();
    assertNotNull(cc);
    final CMPCertificate cmpcert = cc.getCertificate();
    assertNotNull(cmpcert);
    final X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded());
    checkDN(userDN, new JcaX509CertificateHolder(cert).getSubject());
    assertArrayEquals(cert.getIssuerX500Principal().getEncoded(),
            ((X509Certificate) cacert).getSubjectX500Principal().getEncoded());

    // Verify the issuer of cert
    CMPCertificate respCmpCaCert = c.getCaPubs()[0];
    final X509Certificate respCaCert = (X509Certificate) CertTools
            .getCertfromByteArray(respCmpCaCert.getEncoded());
    assertEquals(CertTools.getFingerprintAsString(cacert), CertTools.getFingerprintAsString(respCaCert));

    Collection<Certificate> cacerts = new ArrayList<Certificate>();
    cacerts.add(cacert);
    assertTrue(CertTools.verify(cert, cacerts));
    cacerts = new ArrayList<Certificate>();
    cacerts.add(respCaCert);
    assertTrue(CertTools.verify(cert, cacerts));

    return cert;
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

/**
 * Produce a human readable export of the given tsl to the given file.
 * //  w w  w . j a  va 2  s .c  o  m
 * @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);
        }
        */
        final List<String> schemeTypes = new ArrayList<String>();
        List<NonEmptyMultiLangURIType> uris = tsl.getSchemeTypes();
        for (NonEmptyMultiLangURIType uri : uris) {
            schemeTypes.add(uri.getValue());
        }
        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.getTradeNames(), 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);

                //add Scheme service definition 
                if (null != trustService.getSchemeServiceDefinitionURI()) {
                    addTitle("Scheme Service Definition URI", title3Font, Paragraph.ALIGN_LEFT, 2, 0, document);
                    final PdfPTable schemeServiceDefinitionURITabel = createInfoTable();
                    for (NonEmptyMultiLangURIType uri : trustService.getSchemeServiceDefinitionURI().getURI()) {
                        addItemRow(uri.getLang(), uri.getValue(), schemeServiceDefinitionURITabel);
                    }
                    document.add(schemeServiceDefinitionURITabel);
                }

                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);

                ServiceHistoryType serviceHistoryType = trustService.getServiceHistoryInstanceType();

                if (null != serviceHistoryType) {

                    for (ServiceHistoryInstanceType serviceHistoryInstanceType : serviceHistoryType
                            .getServiceHistoryInstance()) {
                        PdfPTable serviceHistoryTable = createInfoTable();

                        //Service approval history information
                        addTitle("Service approval history information", title3Font, Paragraph.ALIGN_LEFT, 10,
                                2, document);

                        // service type identifier
                        //5.6.2 Service name
                        InternationalNamesType i18nServiceName = serviceHistoryInstanceType.getServiceName();
                        String servName = TrustServiceListUtils.getValue(i18nServiceName, Locale.ENGLISH);
                        addItemRow("Name", servName, serviceHistoryTable);
                        //5.6.1 Service type identifier
                        addItemRow("Type", substringAfter(serviceHistoryInstanceType.getServiceTypeIdentifier(),
                                "Svctype/"), serviceHistoryTable);
                        addItemRow("Status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.4 Service previous status
                        addItemRow("Previous status", serviceHistoryInstanceType.getServiceStatus(),
                                serviceHistoryTable);
                        //5.6.5 Previous status starting date and time
                        addItemRow(
                                "Previous starting time", new DateTime(serviceHistoryInstanceType
                                        .getStatusStartingTime().toGregorianCalendar()).toString(),
                                serviceHistoryTable);
                        //5.6.3 Service digital identity
                        final X509Certificate previousCertificate = trustService.getServiceDigitalIdentity(
                                serviceHistoryInstanceType.getServiceDigitalIdentity());

                        document.add(serviceHistoryTable);

                        addTitle("Service digital identity (X509)", title4Font, Paragraph.ALIGN_LEFT, 2, 0,
                                document);

                        final PdfPTable serviceIdentityTableHistory = createInfoTable();
                        addItemRow("Version", Integer.toString(previousCertificate.getVersion()),
                                serviceIdentityTableHistory);
                        addItemRow("Serial number", previousCertificate.getSerialNumber().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Signature algorithm", previousCertificate.getSigAlgName(),
                                serviceIdentityTableHistory);
                        addItemRow("Issuer", previousCertificate.getIssuerX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid from", previousCertificate.getNotBefore().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Valid to", previousCertificate.getNotAfter().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Subject", previousCertificate.getSubjectX500Principal().toString(),
                                serviceIdentityTableHistory);
                        addItemRow("Public key", previousCertificate.getPublicKey().toString(),
                                serviceIdentityTableHistory);
                        // TODO certificate policies
                        addItemRow("Subject key identifier", toHex(getSKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("CRL distribution points", getCrlDistributionPoints(previousCertificate),
                                serviceIdentityTableHistory);
                        addItemRow("Authority key identifier", toHex(getAKId(previousCertificate)),
                                serviceIdentityTableHistory);
                        addItemRow("Key usage", getKeyUsage(previousCertificate), serviceIdentityTableHistory);
                        addItemRow("Basic constraints", getBasicConstraints(previousCertificate),
                                serviceIdentityTableHistory);

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

                        ExtensionsListType previousExtensions = serviceHistoryInstanceType
                                .getServiceInformationExtensions();
                        if (null != previousExtensions) {
                            for (ExtensionType extension : previousExtensions.getExtension()) {
                                printExtension(extension, document);
                            }
                        }

                        addLongMonoItem("The decoded certificate:", previousCertificate.toString(), document);
                        addLongMonoItem("The certificate in PEM format:", toPem(previousCertificate), 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:test.be.fedict.eid.applet.PcscTest.java

@Test
public void testReadNonRepudiationCertificate() throws Exception {
    PcscEidSpi pcscEidSpi = new PcscEid(new TestView(), this.messages);
    if (false == pcscEidSpi.isEidPresent()) {
        LOG.debug("insert eID card");
        pcscEidSpi.waitForEidPresent();//w  ww.j ava 2  s  .co m
    }

    File tmpFile = File.createTempFile("eid-sign-cert-", ".der");
    byte[] signCert = pcscEidSpi.readFile(PcscEid.SIGN_CERT_FILE_ID);
    FileUtils.writeByteArrayToFile(tmpFile, signCert);

    LOG.debug("ASN1 dump: " + ASN1Dump.dumpAsString(new ASN1InputStream(signCert).readObject()));

    LOG.debug("tmp file: " + tmpFile.getAbsolutePath());

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(signCert));
    X509Principal issuerPrincipal = PrincipalUtil.getIssuerX509Principal(certificate);
    LOG.debug("BC issuer principal: " + issuerPrincipal.getName());
    LOG.debug("Sun issuer (getName): " + certificate.getIssuerX500Principal().getName());
    LOG.debug("Sun issuer (toString): " + certificate.getIssuerX500Principal());
    String issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", ");
    LOG.debug("issuer name: " + issuerName);
    LOG.debug("certificate: " + certificate);

    pcscEidSpi.close();
}

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

private X509Certificate findCertIssuerInStore(X509Certificate x509cert, KeyStore kStore)
        throws CertificateException {
    X509Certificate x509issuer = null;

    debug("searching store for issuer: " + x509cert.getIssuerDN());

    // check in our local root CA Store
    Enumeration<String> enumAliases;
    try {/* w ww.  ja v  a  2s .  co m*/
        enumAliases = kStore.aliases();
        X509Certificate x509search = null;
        while (enumAliases.hasMoreElements()) {
            x509search = (X509Certificate) kStore.getCertificate(enumAliases.nextElement());

            if (checkSubjectMatchesIssuer(x509search.getSubjectX500Principal(),
                    x509cert.getIssuerX500Principal())) {
                x509issuer = x509search;
                debug("found issuer for current cert in chain in ROOT CA store: " + x509issuer.getSubjectDN());

                break;
            }
        }
    } catch (KeyStoreException e) {

        String errMsg = mContext.getString(R.string.error_problem_access_local_root_ca_store);
        debug(errMsg);

        throw new CertificateException(errMsg);
    }

    return x509issuer;
}

From source file:controller.CCInstance.java

public Certificate hasTrustedIssuerCertificate(final X509Certificate x509c) {
    ArrayList<Certificate> alTrustedCertificates;
    try {/*from w w  w.j a v a 2 s  .co  m*/
        alTrustedCertificates = getTrustedCertificatesFromKeystore(getKeystore());
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | InvalidAlgorithmParameterException ex) {
        return null;
    }

    if (alTrustedCertificates.isEmpty()) {
        return null;
    }

    for (final Certificate c : alTrustedCertificates) {
        try {
            final X509Certificate x509cc = (X509Certificate) c;
            if (x509c.getIssuerX500Principal().equals(x509cc.getSubjectX500Principal())) {
                return c;
            }
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

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

private void populateCertificateTree() {
    certificateTree.removeAll();//from w w w  .j  ava2s.  c  om
    valueText.setText(StringUtils.EMPTY);

    IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection();

    if (selection.size() != 1) {
        return;
    }

    CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement();
    X509Certificate certificate = certificateItem.certificate;

    TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE);
    Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal());
    rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$

    TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$
            String.valueOf(certificate.getVersion()));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$
            certificate.getSerialNumber().toString(16));
    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$
            certificate.getIssuerX500Principal().getName());

    TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$
            StringUtils.EMPTY);
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$
            certificate.getNotBefore().toString());
    createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$
            certificate.getNotAfter().toString());

    createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$
            certificate.getSubjectX500Principal().getName());

    TreeItem pkiItem = createTreeItem(certItem,
            Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$
    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$
            certificate.getPublicKey().getAlgorithm());

    createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getPublicKey().getEncoded())));

    TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$
            StringUtils.EMPTY);
    populateExtensions(extItem, certificate, true);
    populateExtensions(extItem, certificate, false);

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$
            certificate.getSigAlgName());

    createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$
            new String(Hex.encodeHex(certificate.getSignature())));

    rootItem.setExpanded(true);
    certItem.setExpanded(true);
    validityItem.setExpanded(true);
    pkiItem.setExpanded(true);
    extItem.setExpanded(true);
}

From source file:homenetapp.HomeNetAppGui.java

private void checkClientCert() {
    try {//from   w w w  .ja  v a2  s  .com
        URL url = new URL("https://" + homenetapp.clientServer + "/");
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.connect();
        Certificate[] certs = conn.getServerCertificates();

        //System.out.println("Cert Chain Length: "+certs.length);

        Certificate c = certs[0];
        X509Certificate xc = (X509Certificate) c;

        String[] from = homenetapp.splitTokens(xc.getIssuerX500Principal().getName(), "=, ");
        String[] to = homenetapp.splitTokens(xc.getSubjectX500Principal().getName(), "=, ");

        certPropertiesLabel.setText("<html>Issued by: " + from[1] + "<br>For: " + to[1] + "<br>Expires: "
                + xc.getNotAfter() + "</html>");

        System.out.println("Cert: " + c.getType());

        System.out.println("Not After: " + xc.getNotAfter());
        System.out.println("Subject DN: " + xc.getSubjectX500Principal());
        System.out.println("Issuer DN: " + xc.getIssuerX500Principal());
        System.out.println("getSigAlgName: " + xc.getSigAlgName());

    } catch (Exception e) {
        certPropertiesLabel.setText("Failed to load certficate");
    }

}

From source file:com.idevity.card.read.ShowCert.java

/**
 * Method onCreateView.//from ww  w  .j  av  a 2s.co  m
 * 
 * @param inflater
 *            LayoutInflater
 * @param container
 *            ViewGroup
 * @param savedInstanceState
 *            Bundle
 * @return View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Globals g = Globals.getInstance();

    byte[] _data = g.getCard();
    CardData80073 carddata = new CardData80073(_data);

    X509Certificate cardAuth = null;
    String issuer = new String();
    String subject = new String();
    String validfrom = new String();
    String validto = new String();
    try {
        PIVCertificate pca = null;
        PIVDataTempl dataTempl = carddata.getCardAuthCertificate();
        if (dataTempl != null) {
            byte[] data = dataTempl.getData();
            if (data == null) {
                data = dataTempl.getEncoded();
            }
            pca = new PIVCertificate(data);
        }
        cardAuth = pca.getCertificate();
    } catch (NullPointerException e) {
        if (debug) {
            Log.d(TAG, "Error: No Card Authentication Certificate Received");
        }
    } catch (Throwable e) {
        Log.e(TAG, "Error: " + e.getMessage());
    }
    if (cardAuth != null) {
        /*
         * The default implementation does not decode the
         * DN in a very human friendly form.  The following
         * Map and Format variables will help to better decode
         * the X500Principal object to a String value.
         */
        HashMap<String, String> oidMap = new HashMap<String, String>();
        oidMap.put("2.5.4.5", "SERIALNUMBER");
        String dnFormat = "RFC1779";
        /*
         * Get the values from the certificate
         */
        issuer = cardAuth.getIssuerX500Principal().getName(dnFormat, oidMap);
        subject = cardAuth.getSubjectX500Principal().getName(dnFormat, oidMap);
        validfrom = cardAuth.getNotBefore().toString();
        validto = cardAuth.getNotAfter().toString();
        /*
         * Populate the UI
         */
        View certLayout = inflater.inflate(R.layout.activity_show_cert, container, false);
        ImageView valPeriodIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_vp);
        ImageView popIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_pop);
        TextView valPeriodLabel = (TextView) certLayout.findViewById(R.id.cert_vp_label);
        TextView popLabel = (TextView) certLayout.findViewById(R.id.cert_pop_label);
        TextView vfText = (TextView) certLayout.findViewById(R.id.cert_nb_label);
        TextView vtText = (TextView) certLayout.findViewById(R.id.cert_na_label);
        /*
         * Assume the cert is good unless an exception
         * is thrown below.
         */
        valPeriodIndicator.setImageResource(R.drawable.cert_good);

        /*
         * Note to self.  I am not thrilled how Java almost forces you
         * to assume a certificate if valid unless an exception is thrown!
         */
        try {
            cardAuth.checkValidity();
        } catch (CertificateNotYetValidException e) {
            valPeriodIndicator.setImageResource(R.drawable.cert_bad);
            valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain));
            vfText.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Error: Authentication Certificate Not Valid Yet!");
            }
        } catch (CertificateExpiredException e) {
            valPeriodIndicator.setImageResource(R.drawable.cert_bad);
            valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain));
            vtText.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Error: Card Authentication Certificate Expired!");
            }
        }
        CAKChallenge popVerify = new CAKChallenge(cardAuth, carddata.getCAKPoPNonce(), carddata.getCAKPoPSig());
        try {
            if (popVerify.validatePOP()) {
                popIndicator.setImageResource(R.drawable.cert_good);
                if (debug) {
                    Log.d(TAG, "Proof of Possession Verified!");
                }
            } else {
                popIndicator.setImageResource(R.drawable.cert_bad);
                popLabel.setTextColor(getResources().getColor(R.color.idredmain));
                if (debug) {
                    Log.d(TAG, "Proof of Possession Failed!");
                }
            }
        } catch (SignatureException e) {
            popIndicator.setImageResource(R.drawable.cert_bad);
            popLabel.setTextColor(getResources().getColor(R.color.idredmain));
            if (debug) {
                Log.d(TAG, "Problem with Proof of Possession: " + e.getMessage());
            }
        }
        TextView editCertSubject = (TextView) certLayout.findViewById(R.id.cert_sub_dn);
        editCertSubject.setText(subject);

        TextView editValidFrom = (TextView) certLayout.findViewById(R.id.cert_nb_date);
        editValidFrom.setText(validfrom);

        TextView editValidTo = (TextView) certLayout.findViewById(R.id.cert_na_date);
        editValidTo.setText(validto);

        TextView editIssuer = (TextView) certLayout.findViewById(R.id.cert_iss_dn);
        editIssuer.setText(issuer);
        return certLayout;
    } else {
        View certLayout = inflater.inflate(R.layout.activity_no_cert, container, false);
        return certLayout;
    }
}

From source file:be.fedict.eid.dss.spi.utils.XAdESUtils.java

public static void checkSigningCertificate(X509Certificate signingCertificate,
        SignedSignaturePropertiesType signedSignatureProperties)
        throws XAdESValidationException, CertificateEncodingException {
    CertIDListType signingCertificateCertIDList = signedSignatureProperties.getSigningCertificate();
    List<CertIDType> signingCertificateCertIDs = signingCertificateCertIDList.getCert();
    CertIDType signingCertificateCertID = signingCertificateCertIDs.get(0);
    DigestAlgAndValueType signingCertificateDigestAlgAndValue = signingCertificateCertID.getCertDigest();
    String certXmlDigestAlgo = signingCertificateDigestAlgAndValue.getDigestMethod().getAlgorithm();
    String certDigestAlgo = XAdESUtils.getDigestAlgo(certXmlDigestAlgo);
    byte[] certDigestValue = signingCertificateDigestAlgAndValue.getDigestValue();
    MessageDigest messageDigest;/* ww  w.j a va  2  s.co m*/
    try {
        messageDigest = MessageDigest.getInstance(certDigestAlgo);
    } catch (NoSuchAlgorithmException e) {
        throw new XAdESValidationException("message digest algo error: " + e.getMessage(), e);
    }
    byte[] actualCertDigestValue = messageDigest.digest(signingCertificate.getEncoded());
    if (!Arrays.equals(actualCertDigestValue, certDigestValue)) {
        throw new XAdESValidationException(
                "XAdES signing certificate not corresponding with actual signing certificate");
    }

    X509IssuerSerialType issuerSerial = signingCertificateCertID.getIssuerSerial();
    BigInteger serialNumber = issuerSerial.getX509SerialNumber();
    if (false == signingCertificate.getSerialNumber().equals(serialNumber)) {
        throw new XAdESValidationException("xades:SigningCertificate serial number mismatch");
    }
    X509Name issuerName;
    try {
        /*issuerName = new X509Name(
              (ASN1Sequence) new ASN1InputStream(signingCertificate
             .getIssuerX500Principal().getEncoded())
             .readObject());*/
        X509Principal sprin = new X509Principal(signingCertificate.getIssuerX500Principal().getEncoded());

        //issuerName = new X509Name( signingCertificate.getIssuerX500Principal().getName(X500Principal.RFC1779) );
        issuerName = new X509Name(sprin.getName());

    } catch (IOException e) {
        throw new XAdESValidationException("error parsing xades:SigningCertificate ds:X509IssuerName: " + e);
    }
    X509Name xadesIssuerName = new X509Name(issuerSerial.getX509IssuerName());
    if (false == issuerName.equals(xadesIssuerName)) {
        throw new XAdESValidationException("xades:SigningCertificate issuer name mismatch");
    }
    LOG.debug("XAdES SigningCertificate OK");
}