Example usage for java.security.cert X509Certificate getNotAfter

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

Introduction

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

Prototype

public abstract Date getNotAfter();

Source Link

Document

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

Usage

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

protected void genTokenCertificates(boolean onlyOnce) throws Exception {

    GlobalConfiguration gc = (GlobalConfiguration) globalConfigurationSession
            .getCachedConfiguration(GlobalConfiguration.GLOBAL_CONFIGURATION_ID);
    boolean originalProfileSetting = gc.getEnableEndEntityProfileLimitations();
    gc.setEnableEndEntityProfileLimitations(false);
    globalConfigurationSession.saveConfiguration(intAdmin, gc);
    if (certificateProfileSession.getCertificateProfileId(WSTESTPROFILE) != 0) {
        certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE);
    }/*from www . j  av a2s . com*/
    {
        final CertificateProfile profile = new CertificateProfile(
                CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER);
        profile.setAllowValidityOverride(true);
        certificateProfileSession.addCertificateProfile(intAdmin, WSTESTPROFILE, profile);
    }
    // first a simple test
    UserDataVOWS tokenUser1 = new UserDataVOWS();
    tokenUser1.setUsername("WSTESTTOKENUSER1");
    tokenUser1.setPassword(PASSWORD);
    tokenUser1.setClearPwd(true);
    tokenUser1.setSubjectDN("CN=WSTESTTOKENUSER1");
    tokenUser1.setCaName(getAdminCAName());
    tokenUser1.setEmail(null);
    tokenUser1.setSubjectAltName(null);
    tokenUser1.setStatus(UserDataVOWS.STATUS_NEW);
    tokenUser1.setTokenType(UserDataVOWS.TOKEN_TYPE_USERGENERATED);
    tokenUser1.setEndEntityProfileName("EMPTY");
    tokenUser1.setCertificateProfileName("ENDUSER");

    KeyPair basickeys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA);
    PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
            CertTools.stringToBcX500Name("CN=NOUSED"), basickeys.getPublic(), new DERSet(),
            basickeys.getPrivate(), null);

    ArrayList<TokenCertificateRequestWS> requests = new ArrayList<TokenCertificateRequestWS>();
    TokenCertificateRequestWS tokenCertReqWS = new TokenCertificateRequestWS();
    tokenCertReqWS.setCAName(getAdminCAName());
    tokenCertReqWS.setCertificateProfileName(WSTESTPROFILE);
    tokenCertReqWS.setValidityIdDays("1");
    tokenCertReqWS.setPkcs10Data(basicpkcs10.getEncoded());
    tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_PKCS10_REQUEST);
    requests.add(tokenCertReqWS);
    tokenCertReqWS = new TokenCertificateRequestWS();
    tokenCertReqWS.setCAName(getAdminCAName());
    tokenCertReqWS.setCertificateProfileName("ENDUSER");
    tokenCertReqWS.setKeyalg("RSA");
    tokenCertReqWS.setKeyspec("1024");
    tokenCertReqWS.setType(HardTokenConstants.REQUESTTYPE_KEYSTORE_REQUEST);
    requests.add(tokenCertReqWS);

    HardTokenDataWS hardTokenDataWS = setupHardTokenDataWS("12345678");

    List<TokenCertificateResponseWS> responses = ejbcaraws.genTokenCertificates(tokenUser1, requests,
            hardTokenDataWS, true, false);
    assertTrue(responses.size() == 2);

    Iterator<TokenCertificateResponseWS> iter = responses.iterator();
    TokenCertificateResponseWS next = iter.next();
    assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_CERTIFICATE_RESPONSE);
    Certificate cert = next.getCertificate();
    X509Certificate realcert = (X509Certificate) CertificateHelper.getCertificate(cert.getCertificateData());
    assertNotNull(realcert);
    assertTrue(realcert.getNotAfter().toString(),
            realcert.getNotAfter().before(new Date(System.currentTimeMillis() + 2 * 24 * 3600 * 1000)));
    next = iter.next();
    assertTrue(next.getType() == HardTokenConstants.RESPONSETYPE_KEYSTORE_RESPONSE);
    KeyStore keyStore = next.getKeyStore();
    java.security.KeyStore realKeyStore = KeyStoreHelper.getKeyStore(keyStore.getKeystoreData(),
            HardTokenConstants.TOKENTYPE_PKCS12, PASSWORD);
    assertTrue(realKeyStore.containsAlias("WSTESTTOKENUSER1"));
    assertTrue(((X509Certificate) realKeyStore.getCertificate("WSTESTTOKENUSER1")).getNotAfter()
            .after(new Date(System.currentTimeMillis() + 48 * 24 * 3600 * 1000)));

    if (!onlyOnce) {
        try {
            responses = ejbcaraws.genTokenCertificates(tokenUser1, requests, hardTokenDataWS, false, false);
            assertTrue(false);
        } catch (HardTokenExistsException_Exception e) {

        }
    }

    certificateProfileSession.removeCertificateProfile(intAdmin, WSTESTPROFILE);
    gc.setEnableEndEntityProfileLimitations(originalProfileSetting);
    globalConfigurationSession.saveConfiguration(intAdmin, gc);

}

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  . c o m
    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:org.cesecore.util.CertTools.java

/**
 * Checks if a certificate is valid./*from  ww  w . ja  va2s.  c o  m*/
 * Does also print a WARN if the certificate is about to expire.
 * 
 * @param signerCert the certificate to be tested
 * @return true if the certificate is valid
 */
public static boolean isCertificateValid(final X509Certificate signerCert) {
    try {
        signerCert.checkValidity();
    } catch (CertificateExpiredException e) {
        log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    } catch (CertificateNotYetValidException e) {
        log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(),
                signerCert.getIssuerDN()));
        return false;
    }
    final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime();
    if (warnBeforeExpirationTime < 1) {
        return true;
    }
    final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime);
    try {
        signerCert.checkValidity(warnDate);
    } catch (CertificateExpiredException e) {
        log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(),
                signerCert.getIssuerDN(), signerCert.getNotAfter()));
    } catch (CertificateNotYetValidException e) {
        throw new Error("This should never happen.", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: "
                + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime));
    }
    return true;
}

From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java

/**
 * Checks the signature on an OCSP request. Does not check for revocation of the signer certificate
 * //from  w w  w  . j  a  va  2s . c o  m
 * @param clientRemoteAddr The IP address or host name of the remote client that sent the request, can be null.
 * @param req The signed OCSPReq
 * @return X509Certificate which is the certificate that signed the OCSP request
 * @throws SignRequestSignatureException if signature verification fail, or if the signing certificate is not authorized
 * @throws SignRequestException if there is no signature on the OCSPReq
 * @throws OCSPException if the request can not be parsed to retrieve certificates
 * @throws NoSuchProviderException if the BC provider is not installed
 * @throws CertificateException if the certificate can not be parsed
 * @throws NoSuchAlgorithmException if the certificate contains an unsupported algorithm
 * @throws InvalidKeyException if the certificate, or CA key is invalid
 */
private X509Certificate checkRequestSignature(String clientRemoteAddr, OCSPReq req) throws SignRequestException,
        SignRequestSignatureException, CertificateException, NoSuchAlgorithmException {
    X509Certificate signercert = null;
    // Get all certificates embedded in the request (probably a certificate chain)
    try {
        final X509CertificateHolder[] certs = req.getCerts();
        String signerSubjectDn = null;
        // We must find a certificate to verify the signature with...
        boolean verifyOK = false;
        for (int i = 0; i < certs.length; i++) {
            final X509Certificate certificate = certificateConverter.getCertificate(certs[i]);
            try {
                if (req.isSignatureValid(
                        new JcaContentVerifierProviderBuilder().build(certificate.getPublicKey()))) {
                    signercert = certificate; // if the request signature verifies by this certificate, this is the signer cert 
                    signerSubjectDn = CertTools.getSubjectDN(signercert);
                    log.info(intres.getLocalizedMessage("ocsp.infosigner", signerSubjectDn));
                    verifyOK = true;
                    // Check that the signer certificate can be verified by one of the CA-certificates that we answer for
                    final X509Certificate signerca = CaCertificateCache.INSTANCE
                            .findLatestBySubjectDN(HashID.getFromIssuerDN(signercert));
                    if (signerca != null) {
                        try {
                            signercert.verify(signerca.getPublicKey());
                            final Date now = new Date();
                            if (log.isDebugEnabled()) {
                                log.debug("Checking validity. Now: " + now + ", signerNotAfter: "
                                        + signercert.getNotAfter());
                            }
                            try {
                                // Check validity of the request signing certificate
                                CertTools.checkValidity(signercert, now);
                            } catch (CertificateNotYetValidException e) {
                                log.info(intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid",
                                        signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage()));
                                verifyOK = false;
                            } catch (CertificateExpiredException e) {
                                log.info(intres.getLocalizedMessage("ocsp.infosigner.certexpired",
                                        signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage()));
                                verifyOK = false;
                            }
                            try {
                                // Check validity of the CA certificate
                                CertTools.checkValidity(signerca, now);
                            } catch (CertificateNotYetValidException e) {
                                log.info(intres.getLocalizedMessage("ocsp.infosigner.certnotyetvalid",
                                        CertTools.getSubjectDN(signerca), CertTools.getIssuerDN(signerca),
                                        e.getMessage()));
                                verifyOK = false;
                            } catch (CertificateExpiredException e) {
                                log.info(intres.getLocalizedMessage("ocsp.infosigner.certexpired",
                                        CertTools.getSubjectDN(signerca), CertTools.getIssuerDN(signerca),
                                        e.getMessage()));
                                verifyOK = false;
                            }
                        } catch (SignatureException e) {
                            log.info(intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature",
                                    signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage()));
                            verifyOK = false;
                        } catch (InvalidKeyException e) {
                            log.info(intres.getLocalizedMessage("ocsp.infosigner.invalidcertsignature",
                                    signerSubjectDn, CertTools.getIssuerDN(signercert), e.getMessage()));
                            verifyOK = false;
                        }
                    } else {
                        log.info(intres.getLocalizedMessage("ocsp.infosigner.nocacert", signerSubjectDn,
                                CertTools.getIssuerDN(signercert)));
                        verifyOK = false;
                    }
                    break;
                }
            } catch (OperatorCreationException e) {
                // Very fatal error
                throw new EJBException("Can not create Jca content signer: ", e);
            }
        }
        if (!verifyOK) {
            if (signerSubjectDn == null && certs.length > 0) {
                signerSubjectDn = CertTools.getSubjectDN(certificateConverter.getCertificate(certs[0]));
            }
            String errMsg = intres.getLocalizedMessage("ocsp.errorinvalidsignature", signerSubjectDn);
            log.info(errMsg);
            throw new SignRequestSignatureException(errMsg);
        }
    } catch (OCSPException e) {
        throw new CryptoProviderException("BouncyCastle was not initialized properly.", e);
    } catch (NoSuchProviderException e) {
        throw new CryptoProviderException("BouncyCastle was not found as a provider.", e);
    }
    return signercert;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private RevocationDetail getRevocationDetail(List<X509CRL> crls, X509Certificate targetCertificate,
        X509Certificate issuerCertificate, PublicKey issuerPublicKey, Date now) throws NoSuchProviderException {
    RevocationDetailImpl detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);

    boolean validCRLFound = false;

    int reasonMask = 0;

    for (X509CRL crl : crls) {
        BigInteger serialNumber = targetCertificate.getSerialNumber();

        X509CRLEntry crlEntry = crl.getRevokedCertificate(serialNumber);

        Date revocationDate = null;

        if (crlEntry != null) {
            revocationDate = crlEntry.getRevocationDate();

            if (revocationDate == null || !now.before(revocationDate)) {
                /*/*w  w w.j  a  v a 2 s. com*/
                 * X.509 7.3 NOTE 4  When an implementation processing a certificate revocation list does not 
                 * recognize a critical extension in the crlEntryExtensions field, it shall assume that, 
                 * at a minimum, the identified certificate has been revoked and is no longer valid and 
                 * perform additional actions concerning that revoked certificate as dictated by local policy.
                 *
                 * We do not need to check for unsupported critical extension because if we do not support them
                 * we should assume that the certificate is revoked.
                 */

                // TODO: add support for onHold/removeFromCRL

                Integer reasonCode = null;
                try {
                    reasonCode = X509CRLEntryInspector.getReasonCode(crlEntry);
                } catch (IOException e) {
                    logger.error("Error retrieving reasonCode.", e);
                }

                detail = (reasonCode != null ? new RevocationDetailImpl(RevocationStatus.REVOKED, reasonCode)
                        : new RevocationDetailImpl(RevocationStatus.REVOKED));

                /* there is no need to continue because certificate is revoked */
                break;
            } else {
                if (now.before(revocationDate)) {
                    logger.info("Certificate is revoked in the future.");
                }
            }
        }

        if (hasUnsupportedCriticalExtensions(crl)) {
            logger.debug("The CRL has unsupported critical extensions.");

            detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

            continue;
        }

        /*
         * check that the start time the CRL is valid is before the time the certificate is 
         * no longer valid. In other words, that the expiration date of the certificate is 
         * later than the date the CRL was issued. It is possible that the certificate was
         * at some point revoked but the CA removed it because the certificate is no longer 
         * valid
         */
        if (crl.getThisUpdate() != null && targetCertificate.getNotAfter().before(crl.getThisUpdate())) {
            logger.info("Certificate has expired before the CRL was valid.");

            continue;
        }

        try {
            if (X509CRLInspector.isDeltaCRL(crl)) {
                DeltaCRLStatus deltaStatus = getDeltaCRLStatus(targetCertificate, crl, issuerPublicKey, now);

                if (deltaStatus == DeltaCRLStatus.UNSUPPORTED_CRITICAL_EXTENSION) {
                    detail = new RevocationDetailImpl(RevocationStatus.UNSUPPORTED_CRITICAL_EXTENSION);

                    continue;
                } else if (deltaStatus == DeltaCRLStatus.UNKNOWN) {
                    continue;
                }
            } else {
                if (!acceptCRL_6_3_3_b(targetCertificate, crl)) {
                    logger.debug("CRL not valid according to acceptCRL_6_3_3_b.");
                    continue;
                }
            }
        } catch (IOException e) {
            logger.error("Error inspecting CRL.", e);

            continue;
        }

        if (crl.getNextUpdate() != null && now.after(crl.getNextUpdate())) {
            /*
             * an CRL cannot really expire but, when we want at least to log that the 
             * nextUpdate is overdue
             */
            logger.debug("The CRL next update is overdue.");

            /* we need to set the nextUpdate if this is a newer CRL */

            if (detail.getStatus() != RevocationStatus.EXPIRED || detail.getNextUpdate() == null) {
                detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
            } else {
                if (crl.getNextUpdate().after(detail.getNextUpdate())) {
                    /* the nextUpdate of the current CRL is later so it's longer valid */
                    detail = new RevocationDetailImpl(RevocationStatus.EXPIRED, crl.getNextUpdate());
                }
            }

            continue;
        }

        try {
            reasonMask = reasonMask | getInterimReasonsMask(targetCertificate, crl);

            /* a valid crl was found. Continue search. */
            validCRLFound = true;
        } catch (IOException e) {
            logger.error("Error getting interim mask.", e);
        }
    }

    /*
     * if one the CRLs was good and the certificate was not revoked we will set the 
     * status to NOT_REVOKED
     */
    if (validCRLFound && detail.getStatus() != RevocationStatus.REVOKED) {
        /* check if all reasons are covered */
        if (reasonMask == allReasons) {
            detail = new RevocationDetailImpl(RevocationStatus.NOT_REVOKED);
        } else {
            logger.debug("Not all reasons were covered.");

            detail = new RevocationDetailImpl(RevocationStatus.UNKNOWN);
        }
    }

    return detail;
}

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.
 * // w ww  . j  a  v a 2s.c o  m
 * 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));
    }
}

From source file:org.viafirma.nucleo.X509.CertificadoGenericoFactory.java

/**
 * Retorna un certificado generico parseando los datos de un certificado X509
 * @param certificadoX509 /*from   w ww . j  a  v a 2  s . c  o m*/
 * @return
 */
public CertificadoGenerico generar(X509Certificate certificadoX509) {
    CertificadoGenerico certificado = new CertificadoGenerico();

    // recuperamos el conjunto de oids
    Map<String, String> propiedadesOid = X509Handler.getCurrentInstance().readPropertiesOid(certificadoX509);

    String subject = certificadoX509.getSubjectDN().toString();

    // parseo el subject
    //StringTokenizer tokenizer=new StringTokenizer(subject,",\"");
    //String [] tokens=subject.split(",");
    //for (int i = 0; i < tokens.length; i++) {
    //   String parIdValor = tokens[i].trim();
    //   String id= parIdValor.split("=")[0];
    //   String valor= parIdValor.split("=")[1];
    //   propiedadesOid.put(id,valor);
    //}
    loadPropiedadesOid(subject, propiedadesOid);

    // guardo todas las propiedades(pintables)
    Set<String> keys = propiedadesOid.keySet();
    for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
        String key = iter.next();
        String valor = propiedadesOid.get(key);
        // FIX: Problema con el encondig utf-8 en openid.
        String newValue = StringUtils.replaceChars(valor, "??", "aeiounuAEIOU");
        if (!StringUtils.isAsciiPrintable(newValue)) {
            // omitimos el campo 
            iter.remove();
        } else {
            // remplazamos el valor
            propiedadesOid.put(key, newValue);
        }
    }
    certificado.setPropiedades(propiedadesOid);

    // identifico el nombre de la CA propietaria del certificado
    certificado.setCa(certificadoX509.getIssuerDN().getName());

    certificado.setNombre(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.1"));
    certificado.setApellido1(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.2"));
    certificado.setApellido2(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.3"));
    certificado.setNumberUserId(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.4"));
    certificado.setCn(propiedadesOid.get("CN"));

    // si no hemos recuperado el nombre en la extensin lo intento recuperar del GIVENNAME.
    if (StringUtils.isEmpty(certificado.getNombre())) {
        certificado.setNombre(propiedadesOid.get("GIVENNAME"));
    }

    // si no hemos recuperado el nombre APELLIDO.
    if (StringUtils.isEmpty(certificado.getApellido1())) {
        certificado.setApellido1(propiedadesOid.get("SURNAME"));
    }

    // si no tenemos apelligos, los intentamos recuperar del CN ( cado del edni)
    // CN="Apelido1 apellido2, nombre (AUTENTICACIN)",
    if (StringUtils.isEmpty(certificado.getApellido1())) {
        // TODO, no se recupera correctamente el CN, pero el resultado es el correcto.
        // Debera de ser StringUtils.substringAfterLast(propiedadesOid.get("CN").replaceAll("\"", ""),",")
        // pero nos vale con propiedadesOid.get("CN")
        certificado.setApellido1(propiedadesOid.get("CN"));
    }

    // si no hemos recuperado el nombre NIF.
    if (StringUtils.isEmpty(certificado.getNumberUserId())) {
        certificado.setNumberUserId(propiedadesOid.get("SERIALNUMBER"));
    }

    // si no hemos recuperado el nombre email.
    if (StringUtils.isEmpty(certificado.getEmail())) {
        certificado.setEmail(certificado.getPropiedades().get(OID_EMAIL));
    }

    // si sige siendo null lo recupero del oid
    if (StringUtils.isEmpty(certificado.getEmail())) {
        certificado.setEmail(propiedadesOid.get("EMAILADDRESS"));
    }

    // si no hemos recuperado el pais
    if (StringUtils.isEmpty(certificado.getPais())) {
        certificado.setPais(certificado.getPropiedades().get("C"));
    }

    // filtrado para que ningun campo sea null
    if (certificado.getApellido1() == null) {
        certificado.setApellido1("");
    }

    if (certificado.getApellido2() == null) {
        certificado.setApellido2("");
    }

    if (certificado.getCa() == null) {
        certificado.setCa("");
    }
    if (certificado.getEmail() == null) {
        certificado.setEmail("");
    }
    if (certificado.getNombre() == null) {
        certificado.setNombre("");
    }
    if (certificado.getPais() == null) {
        certificado.setPais("");
    }

    if (certificado.getNumberUserId() == null) {
        certificado.setNumberUserId("");
    }

    // recupero el cargo. 
    String cargo = propiedadesOid.get("T");
    if (cargo != null) {
        certificado.setCargo(cargo);
    }
    // recupero el nombre de la organizacin.
    String organizacion = propiedadesOid.get("O");
    if (organizacion != null) {
        certificado.setOrganizacion(organizacion);
    }

    // Detectamos si el certificado est caducado
    Date hoy = new Date();
    if (certificadoX509.getNotAfter().before(hoy)) {
        // el certificado est caducado.
        certificado.setCaducado(true);
    }

    // recuperar el tpo de certificado
    loadTipoCertificado(certificado, propiedadesOid, certificado.getCa());

    return certificado;
}