Example usage for java.security.cert X509Certificate getNotBefore

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

Introduction

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

Prototype

public abstract Date getNotBefore();

Source Link

Document

Gets the notBefore date from the validity period of the certificate.

Usage

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

/**
 * Method onCreateView./*from  w  w w  .j  a va2 s  .  c  o 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.trust.linker.PublicKeyTrustLinker.java

@Override
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, AlgorithmPolicy algorithmPolicy)
        throws TrustLinkerResultException, Exception {
    if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        LOG.debug("child certificate issuer not the same as the issuer certificate subject");
        LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal());
        LOG.debug("certificate: " + certificate.getSubjectX500Principal());
        LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal());
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "child certificate issuer not the same as the issuer certificate subject");
    }/*from w  ww .j  av a2  s .c om*/
    try {
        childCertificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        LOG.debug("verification error: " + e.getMessage(), e);
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_SIGNATURE,
                "verification error: " + e.getMessage());
    }

    algorithmPolicy.checkSignatureAlgorithm(childCertificate.getSigAlgOID(), validationDate);

    if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) {
        LOG.warn("child certificate validity end is after certificate validity end");
        LOG.warn("child certificate validity end: " + childCertificate.getNotAfter());
        LOG.warn("certificate validity end: " + certificate.getNotAfter());
    }
    if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) {
        LOG.warn("child certificate validity begin before certificate validity begin");
        LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore());
        LOG.warn("certificate validity begin: " + certificate.getNotBefore());
    }
    if (true == validationDate.before(childCertificate.getNotBefore())) {
        LOG.debug("certificate is not yet valid");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate is not yet valid");
    }
    if (true == validationDate.after(childCertificate.getNotAfter())) {
        LOG.debug("certificate already expired");
        throw new TrustLinkerResultException(TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL,
                "certificate already expired");
    }
    if (-1 == certificate.getBasicConstraints()) {
        LOG.debug("certificate not a CA: " + certificate.getSubjectX500Principal());
        /*
         * http://www.valicert.com/ Root CA has no CA flag set. Actually
         * this is in violation with 4.2.1.10 Basic Constraints of RFC2459.
         */
        try {
            certificate.verify(certificate.getPublicKey());
            LOG.warn("allowing self-signed Root CA without CA flag set");
        } catch (Exception e) {
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "certificate not a CA");
        }
    }
    if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) {
        LOG.debug("child should not be a CA");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST, "child should not be a CA");
    }

    /*
     * SKID/AKID sanity check
     */
    boolean isCa = isCa(certificate);
    boolean isChildCa = isCa(childCertificate);

    byte[] subjectKeyIdentifierData = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    byte[] authorityKeyIdentifierData = childCertificate
            .getExtensionValue(Extension.authorityKeyIdentifier.getId());

    if (isCa && null == subjectKeyIdentifierData) {
        LOG.debug("certificate is CA and MUST contain a Subject Key Identifier");
        throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                "certificate is CA and  MUST contain a Subject Key Identifier");
    }

    if (isChildCa && null == authorityKeyIdentifierData && null != subjectKeyIdentifierData) {
        LOG.error("child certificate is CA and MUST contain an Authority Key Identifier");
        // return new TrustLinkerResult(false,
        // TrustLinkerResultReason.INVALID_TRUST,
        // "child certificate is CA and MUST contain an Authority Key Identifier");
    }

    if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) {
        AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdentifierData));
        SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier
                .getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdentifierData));
        if (!Arrays.equals(authorityKeyIdentifier.getKeyIdentifier(),
                subjectKeyIdentifier.getKeyIdentifier())) {
            LOG.debug(
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
            throw new TrustLinkerResultException(TrustLinkerResultReason.NO_TRUST,
                    "certificate's subject key identifier does not match child certificate's authority key identifier");
        }
    }

    /*
     * We don't check pathLenConstraint since this one is only there to
     * protect the PKI business.
     */
    /*
     * Keep in mind that this trust linker can never return TRUSTED.
     */
    return TrustLinkerResult.UNDECIDED;
}

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

private void populateCertificateTree() {
    certificateTree.removeAll();/*ww w .j  a v a2s  .  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:jproxy.ProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {//from   w w  w  . j  a va  2  s  .  c o  m
            X509Certificate caCert = (X509Certificate) keyStore.getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            log.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:mitm.common.security.certificate.impl.StandardX509CertificateBuilderTest.java

@Test
public void testGenerateSelfSignedV3Certificate() throws Exception {
    X509CertificateBuilder certificateBuilder = new StandardX509CertificateBuilder("BC", "BC");

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(2048, randomSource);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder issuerBuilder = new X500PrincipalBuilder();

    issuerBuilder.setCommonName("Martijn Brinkers");
    issuerBuilder.setCountryCode("NL");
    issuerBuilder.setEmail("test@example.com", "test2@example.com");
    issuerBuilder.setGivenName("Martijn");
    issuerBuilder.setSurname("Brinkers");
    issuerBuilder.setLocality("Amsterdam");
    issuerBuilder.setOrganisation("None");
    issuerBuilder.setState("NH");

    AltNamesBuilder altNamesBuider = new AltNamesBuilder();

    altNamesBuider.setRFC822Names("m.brinkers@pobox.com");
    altNamesBuider.setDNSNames("example.com");

    X500Principal issuer = issuerBuilder.buildPrincipal();
    GeneralNames altNames = altNamesBuider.buildAltNames();

    Set<KeyUsageType> keyUsage = new HashSet<KeyUsageType>();

    keyUsage.add(KeyUsageType.DIGITALSIGNATURE);
    keyUsage.add(KeyUsageType.KEYENCIPHERMENT);
    keyUsage.add(KeyUsageType.NONREPUDIATION);

    Set<ExtendedKeyUsageType> extendedKeyUsage = new HashSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);

    Date notBefore = DateUtils.addHours(new Date(), -1);
    Date notAfter = DateUtils.addYears(new Date(), 10);

    certificateBuilder.setSubject(issuer);
    certificateBuilder.setIssuer(issuer);
    certificateBuilder.setAltNames(altNames, true);
    certificateBuilder.setKeyUsage(keyUsage, true);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, true);
    certificateBuilder.setNotBefore(notBefore);
    certificateBuilder.setNotAfter(notAfter);
    certificateBuilder.setPublicKey(keyPair.getPublic());
    certificateBuilder.setSerialNumber(new BigInteger("1"));
    certificateBuilder.setSignatureAlgorithm("SHA256WithRSA");
    certificateBuilder.setIsCA(true, true /* critical */);
    certificateBuilder.setPathLengthConstraint(5);

    Set<String> crlDistPoints = new HashSet<String>();
    crlDistPoints.add("http://example.com");
    crlDistPoints.add("123");

    certificateBuilder.setCRLDistributionPoints(crlDistPoints);

    X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

    assertNotNull(certificate);/*from   w w w .j a v  a2 s  . com*/

    File file = new File(tempDir, "testGenerateSelfSignedV3Certificate.cer");

    CertificateUtils.writeCertificate(certificate, file);

    X509CertificateInspector certInspector = new X509CertificateInspector(certificate);

    assertEquals(
            "EMAILADDRESS=test2@example.com, EMAILADDRESS=test@example.com, GIVENNAME=Martijn, "
                    + "SURNAME=Brinkers, CN=Martijn Brinkers, O=None, L=Amsterdam, ST=NH, C=NL",
            certInspector.getSubjectFriendly());

    assertEquals(certInspector.getIssuerFriendly(), certInspector.getSubjectFriendly());

    AltNamesInspector altNamesInspector = new AltNamesInspector(certificate.getSubjectAlternativeNames());

    List<String> rFC822Names = altNamesInspector.getRFC822Names();

    assertEquals(1, rFC822Names.size());
    assertEquals("m.brinkers@pobox.com", rFC822Names.get(0));

    List<String> dNSNames = altNamesInspector.getDNSNames();

    assertEquals(1, dNSNames.size());
    assertEquals("example.com", dNSNames.get(0));

    assertEquals(3, certInspector.getKeyUsage().size());
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.DIGITALSIGNATURE));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.KEYENCIPHERMENT));
    assertTrue(certInspector.getKeyUsage().contains(KeyUsageType.NONREPUDIATION));

    assertEquals(2, certInspector.getExtendedKeyUsage().size());
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.CLIENTAUTH));
    assertTrue(certInspector.getExtendedKeyUsage().contains(ExtendedKeyUsageType.EMAILPROTECTION));

    // we cannot compare the dates because of encoding we loose some detail so check if within 1 sec
    assertTrue(Math.abs(notAfter.getTime() - certificate.getNotAfter().getTime()) < 1000);
    assertTrue(Math.abs(notBefore.getTime() - certificate.getNotBefore().getTime()) < 1000);

    assertEquals("1", certInspector.getSerialNumberHex());

    assertEquals("SHA256WITHRSA", certificate.getSigAlgName());

    assertTrue(certInspector.isCA());
    assertEquals(5, certInspector.getBasicConstraints().getPathLenConstraint().intValue());

    Set<String> crlDistPointsCert = CRLDistributionPointsInspector
            .getURIDistributionPointNames(certInspector.getCRLDistibutionPoints());

    assertTrue(crlDistPointsCert.contains("http://example.com"));
    assertTrue(crlDistPointsCert.contains("123"));
}

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

public static Date getNotBefore(Certificate cert) {
    Date ret = null;//from w w  w . j  ava  2s .  co  m
    if (cert == null) {
        throw new IllegalArgumentException("getNotBefore: cert is null");
    }
    if (cert instanceof X509Certificate) {
        X509Certificate xcert = (X509Certificate) cert;
        ret = xcert.getNotBefore();
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        try {
            ret = cvccert.getCVCertificate().getCertificateBody().getValidFrom();
        } catch (NoSuchFieldException e) {
            // it is not uncommon that this field is missing in CVC certificate requests (it's not in the EAC standard so)
            log.debug("NoSuchFieldException: " + e.getMessage());
            return null;
        }
    }
    return ret;
}

From source file:org.cesecore.certificates.ca.X509CA.java

@Override
public void createOrRemoveLinkCertificate(final CryptoToken cryptoToken, final boolean createLinkCertificate,
        final CertificateProfile certProfile) throws CryptoTokenOfflineException {
    byte[] ret = null;
    if (createLinkCertificate) {
        try {//from   w w  w .j  av  a  2 s  .  c o m
            final CAToken catoken = getCAToken();
            // Check if the input was a CA certificate, which is the same CA as this. If all is true we should create a NewWithOld link-certificate
            final X509Certificate currentCaCert = (X509Certificate) getCACertificate();
            if (log.isDebugEnabled()) {
                log.debug("We will create a link certificate.");
            }
            final X509CAInfo info = (X509CAInfo) getCAInfo();
            final EndEntityInformation cadata = new EndEntityInformation("nobody", info.getSubjectDN(),
                    info.getSubjectDN().hashCode(), info.getSubjectAltName(), null, 0,
                    new EndEntityType(EndEntityTypes.INVALID), 0, info.getCertificateProfileId(), null, null, 0,
                    0, null);
            final PublicKey previousCaPublicKey = cryptoToken
                    .getPublicKey(catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS));
            final PrivateKey previousCaPrivateKey = cryptoToken.getPrivateKey(
                    catoken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS));
            final String provider = cryptoToken.getSignProviderName();
            // The sequence is ignored later, but we fetch the same previous for now to do this the same way as for CVC..
            final String ignoredKeySequence = catoken.getProperties()
                    .getProperty(CATokenConstants.PREVIOUS_SEQUENCE_PROPERTY);
            final Certificate retcert = generateCertificate(cadata, null, currentCaCert.getPublicKey(), -1,
                    currentCaCert.getNotBefore(), currentCaCert.getNotAfter(), certProfile, null,
                    ignoredKeySequence, previousCaPublicKey, previousCaPrivateKey, provider, null);
            log.info(intres.getLocalizedMessage("cvc.info.createlinkcert", cadata.getDN(), cadata.getDN()));
            ret = retcert.getEncoded();
        } catch (CryptoTokenOfflineException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("Bad CV CA certificate.", e);
        }
    }
    updateLatestLinkCertificate(ret);
}

From source file:view.CertificatePropertiesDialog.java

private void setCertificateProperties(X509Certificate x509Certificate) {
    selectedCertificate = x509Certificate;
    jTextField1.setText(null);/*from  w w w .j  a v a 2 s . com*/
    jTextField2.setText(null);
    jTextField3.setText(null);
    jTextField4.setText(null);
    jTextField5.setText(null);
    jTextField6.setText(null);
    jTextField7.setText(null);
    jTextField9.setText(null);
    jTextField10.setText(null);
    jTextField11.setText(null);
    jTextField12.setText(null);

    X500Name x500subject = null;
    X500Name x500issuer = null;
    try {
        x500subject = new JcaX509CertificateHolder(x509Certificate).getSubject();
        x500issuer = new JcaX509CertificateHolder(x509Certificate).getIssuer();
    } catch (CertificateEncodingException ex) {
        controller.Logger.getLogger().addEntry(ex);
    }

    RDN subjectCN = null;
    if (x500subject.getRDNs(BCStyle.CN).length > 0) {
        subjectCN = x500subject.getRDNs(BCStyle.CN)[0];
    }
    RDN subjectOU1 = null;
    if (x500subject.getRDNs(BCStyle.OU).length >= 1) {
        subjectOU1 = x500subject.getRDNs(BCStyle.OU)[0];
        jTextField2.setText(IETFUtils.valueToString(subjectOU1.getFirst().getValue()));
        jTextField2.setCaretPosition(0);
    }
    RDN subjectOU2 = null;
    if (x500subject.getRDNs(BCStyle.OU).length >= 2) {
        subjectOU2 = x500subject.getRDNs(BCStyle.OU)[1];
        jTextField3.setText(IETFUtils.valueToString(subjectOU2.getFirst().getValue()));
        jTextField3.setCaretPosition(0);
    }
    RDN subjectO = null;
    if (x500subject.getRDNs(BCStyle.O).length > 0) {
        subjectO = x500subject.getRDNs(BCStyle.O)[0];
    }
    RDN subjectC = null;
    if (x500subject.getRDNs(BCStyle.C).length > 0) {
        subjectC = x500subject.getRDNs(BCStyle.C)[0];
    }
    if (!x500issuer.equals(x500subject)) {
        RDN issuerCN = x500issuer.getRDNs(BCStyle.CN)[0];
        if (1 == x500issuer.getRDNs(BCStyle.OU).length) {
            RDN issuerOU1 = x500issuer.getRDNs(BCStyle.OU)[0];
            jTextField7.setText(IETFUtils.valueToString(issuerOU1.getFirst().getValue()));
            jTextField7.setCaretPosition(0);
        }
        RDN issuerO = x500issuer.getRDNs(BCStyle.O)[0];
        RDN issuerC = x500issuer.getRDNs(BCStyle.C)[0];

        jTextField6.setText(IETFUtils.valueToString(issuerCN.getFirst().getValue()));
        jTextField6.setCaretPosition(0);
        jTextField9.setText(IETFUtils.valueToString(issuerO.getFirst().getValue()));
        jTextField9.setCaretPosition(0);
        jTextField10.setText(IETFUtils.valueToString(issuerC.getFirst().getValue()));
        jTextField10.setCaretPosition(0);
    }

    Date since = x509Certificate.getNotBefore();
    Date until = x509Certificate.getNotAfter();

    jTextField1.setText(
            WordUtils.capitalize(IETFUtils.valueToString(subjectCN.getFirst().getValue()).toLowerCase()));
    jTextField1.setCaretPosition(0);
    if (subjectO != null) {
        jTextField4.setText(IETFUtils.valueToString(subjectO.getFirst().getValue()));
    }
    jTextField4.setCaretPosition(0);
    if (subjectC != null) {
        jTextField5.setText(IETFUtils.valueToString(subjectC.getFirst().getValue()));
    }
    jTextField5.setCaretPosition(0);

    jTextField11.setText(since.toLocaleString());
    jTextField11.setCaretPosition(0);
    jTextField12.setText(until.toLocaleString());
    jTextField12.setCaretPosition(0);

    boolean usage[] = x509Certificate.getKeyUsage();
    if (null != usage) {
        boolean digitalSignature = usage[0];
        boolean nonRepudiation = usage[1];
        boolean keyEncipherment = usage[2];
        boolean dataEncipherment = usage[3];
        boolean keyAgreement = usage[4];
        boolean keyCertSign = usage[5];
        boolean cRLSign = usage[6];
        boolean encipherOnly = usage[7];
        boolean decipherOnly = usage[8];

        String uso = (digitalSignature ? Bundle.getBundle().getString("digitalSignature") + ", " : "")
                + (nonRepudiation ? Bundle.getBundle().getString("nonRepudiation") + ", " : "")
                + (keyEncipherment ? Bundle.getBundle().getString("keyEncipherment") + ", " : "")
                + (dataEncipherment ? Bundle.getBundle().getString("dataEncipherment") + ", " : "")
                + (keyAgreement ? Bundle.getBundle().getString("keyAgreement") + ", " : "")
                + (keyCertSign ? Bundle.getBundle().getString("keyCertSign") + ", " : "")
                + (cRLSign ? Bundle.getBundle().getString("cRLSign") + ", " : "")
                + (encipherOnly ? Bundle.getBundle().getString("encipherOnly") + ", " : "")
                + (decipherOnly ? Bundle.getBundle().getString("decipherOnly") + ", " : "");

        if (uso.length() == 0) {
            lblUso.setText(Bundle.getBundle().getString("label.none"));
        } else if (uso.endsWith(", ")) {
            lblUso.setText(uso.substring(0, uso.length() - 2));
        }
    } else {
        lblUso.setText(Bundle.getBundle().getString("unknown"));
    }

}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * /*from   www  .j a  v  a 2s .com*/
 * The saved data must always win over any passed-in URI data
 * 
 * @param cert the given cert.
 */
private void validateX509Cert(final X509Certificate cert) {

    boolean certMismatch = false;

    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }

    // If there is no saved cert, then if a signature was provided,
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
        // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }

    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };

    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel),
                certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(),
                cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");

        // Actually display the message
        Utils.showYesNoPrompt(getContext(),
                getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?",
                certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}