Example usage for java.security.cert X509Certificate checkValidity

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

Introduction

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

Prototype

public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the certificate is currently valid.

Usage

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

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

From source file:org.codice.ddf.security.filter.login.LoginFilter.java

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs)
        throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;//  w  w w .  j  a  va 2 s .c o m
        }
    }

    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject()
                    .getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();

                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf
                                    .generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();

                            //HoK spec section 2.5:
                            //relying party MUST ensure that the certificate bound to the assertion matches the X.509 certificate in its possession.
                            //Matching is done by comparing the base64-decoded certificates, or the hash values of the base64-decoded certificates, byte-for-byte.
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException
                                | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with certificate.");
                        }

                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //HoK spec section 2.5:
                        //relying party MUST ensure that the subject distinguished name (DN) bound to the assertion matches the DN bound to the X.509 certificate.
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject DN.");
                        }

                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException(
                                "Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier
                                    .getInstance(assertionOs.getOctets());
                            //HoK spec section 2.5:
                            //relying party MUST ensure that the value bound to the assertion matches the Subject Key Identifier (SKI) extension bound to the X.509 certificate.
                            //Matching is done by comparing the base64-decoded SKI values byte-for-byte. If the X.509 certificate does not contain an SKI extension,
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(),
                                    assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException(
                                        "Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException(
                                    "Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}

From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler.java

protected final boolean doAuthentication(final Credentials credentials) throws AuthenticationException {

    final X509CertificateCredentials x509Credentials = (X509CertificateCredentials) credentials;
    final X509Certificate[] certificates = x509Credentials.getCertificates();

    /*/*from   ww  w. j av  a  2s. com*/
     * the certificate that was fully authenticated succesfully will be set
     * as the user credentials for CAS last certificate that can be set is
     * the end-user certificate
     */
    X509Certificate certificateCredentialsCandidate = null;
    // flag to check whether a trusted issuer is in the certificate chain
    boolean hasTrustedIssuerInChain = false;

    /*
     * reverse transversal of certificates (should be from root to end-user
     * cert)
     */
    for (int i = (certificates.length - 1); i >= 0; i--) {
        final X509Certificate certificate = certificates[i];
        try {
            final Principal issuerPrincipal = certificate.getIssuerDN();
            // flag that is set when this cert is an end user cert (no CA
            // cert)
            boolean isEndUserCertificate = false;

            if (log.isDebugEnabled()) {
                log.debug("--examining cert[" + certificate.getSerialNumber().toString() + "] "
                        + certificate.getSubjectDN() + "\"" + " from issuer \"" + issuerPrincipal.getName()
                        + "\"");
            }

            // check basic validity of the current certificate
            certificate.checkValidity();
            log.debug("certificate is valid");

            // initial check for trusted issuer in certificate chain
            // final check is done outside for loop
            if (isCertificateFromTrustedIssuer(issuerPrincipal)) {
                hasTrustedIssuerInChain = true;
                log.debug("certificate was issued by trusted issuer");
            }

            // getBasicConstraints returns pathLenContraint which is
            // >=0 when this is a CA cert and -1 when it's not
            int pathLength = certificate.getBasicConstraints();
            if (pathLength != -1) {
                log.debug("this is a CA certificate");

                // check pathLength when CA cert
                //if unlimited/unspecified and unlimited/unspecified not allowed: warn+stop
                if (pathLength == Integer.MAX_VALUE && this.maxPathLength_allowUnspecified != true) {
                    if (log.isWarnEnabled()) {
                        log.warn("authentication failed; cert pathLength not specified"
                                + " and unlimited/unspecified not allowed by config [see maxPathLength_allow_unlimited]");
                    }
                    return false;
                    //else if more than allowed length but not unlimited/unspecified: warn+stop
                } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) {
                    if (log.isWarnEnabled()) {
                        log.warn("authentication failed; cert pathLength [" + pathLength
                                + "] is more than allowed by config [" + this.maxPathLength + "]");
                    }
                    return false;
                }
            } else {
                isEndUserCertificate = true;
                log.debug("this is an end-user certificate");
            }

            /*
             * set this certificate as the user credentials if there is an
             * issuer in the cert (always so if valid cert) and this is an
             * end-user or CA certificate (so not a CA cert) and optional
             * KeyUsage check
             */
            if (issuerPrincipal != null && isEndUserCertificate
                    && this.doesCertificateSubjectDnMatchPattern(certificate.getSubjectDN())
                    && (!this.checkKeyUsage
                            || (this.checkKeyUsage && this.doesCertificateKeyUsageMatch(certificate)))) {

                if (log.isDebugEnabled()) {
                    log.debug("cert[" + certificate.getSerialNumber().toString()
                            + "] ok, setting as credentials candidate");
                }
                certificateCredentialsCandidate = certificate;
            }
        } catch (final CertificateExpiredException e) {
            log.warn("authentication failed; certficiate expired [" + certificate.toString() + "]");
            certificateCredentialsCandidate = null;
        } catch (final CertificateNotYetValidException e) {
            log.warn("authentication failed; certficate not yet valid [" + certificate.toString() + "]");
            certificateCredentialsCandidate = null;
        }
    }

    // check whether one of the certificates in the chain was
    // from the trusted issuer; else => fail auth
    if (certificateCredentialsCandidate != null && hasTrustedIssuerInChain) {
        if (log.isInfoEnabled()) {
            log.info("authentication OK; SSL client authentication data meets criteria for cert["
                    + certificateCredentialsCandidate.getSerialNumber().toString() + "]");
        }
        x509Credentials.setCertificate(certificateCredentialsCandidate);
        return true;
    }

    if (log.isInfoEnabled()) {
        if (!hasTrustedIssuerInChain) {
            log.info("client cert did not have trusted issuer pattern \""
                    + this.regExTrustedIssuerDnPattern.pattern() + "\" in chain; authentication failed");
        } else {
            log.info("authentication failed; SSL client authentication data doesn't meet criteria");
        }
    }
    return false;
}

From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

/**
 * Set the identity for the communications to the XMLRPC controller. Eventually
 * we may talk to several controller with different identities. For now only
 * one is configured./*from  www. ja v  a2 s .  c  o m*/
 */
private void setSSLIdentity() throws Exception {

    //if (sslIdentitySet)
    //   return;

    //System.out.println("In setSSLIdentity()");

    try {
        // create multikeymanager
        mkm = new MultiKeyManager();
        //TODO
        //URL ctrlrUrl = new URL(GUI.getInstance().getSelectedController());
        URL ctrlrUrl = new URL(CONTROLLER_URL);
        // TODO

        // register a new protocol
        ContextualSSLProtocolSocketFactory regSslFact = new ContextualSSLProtocolSocketFactory();

        // add this multikey context factory for the controller host/port
        regSslFact.addHostContextFactory(new MultiKeySSLContextFactory(mkm, trustAllCerts), ctrlrUrl.getHost(),
                ctrlrUrl.getPort());

        if (rmProperties == null) {
            System.out.println("ERROR ... Property File with user credentials not supplied...");
            return;
        }

        KeyStore ks = null;

        //File keyStorePath = loadUserFile("/Users/anirban/Misc/tmp/renci-openvpn/flukes.jks");
        //File certFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        //File certKeyFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        File keyStorePath = null;
        File certFilePath = null;
        File certKeyFilePath = null;

        if (rmProperties.getProperty(USER_KEYSTORE_PATH_PROP) != null) {
            keyStorePath = loadUserFile(rmProperties.getProperty(USER_KEYSTORE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTFILE_PATH_PROP) != null) {
            certFilePath = loadUserFile(rmProperties.getProperty(USER_CERTFILE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP) != null) {
            certKeyFilePath = loadUserFile(rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP));
        }

        String keyAlias = null, keyPassword = null;
        if (keyStorePath != null && keyStorePath.exists()) {
            // load keystore and get the right cert from it
            System.out.println("Reading auth details from keystore");
            //TODO
            keyAlias = rmProperties.getProperty(USER_KEYSTORE_KEYALIAS_PROP);
            keyPassword = rmProperties.getProperty(USER_KEYSTORE_KEYPASS_PROP);
            //TODO
            FileInputStream jksIS = new FileInputStream(keyStorePath);
            ks = loadJKSData(jksIS, keyAlias, keyPassword);
            jksIS.close();
        } else if (certFilePath != null && certKeyFilePath != null && certFilePath.exists()
                && certKeyFilePath.exists()) {
            System.out.println("Reading auth details from cert file and certkeyfile");
            FileInputStream certIS = new FileInputStream(certFilePath);
            FileInputStream keyIS = new FileInputStream(certKeyFilePath);
            keyAlias = "x509convert";
            //TODO
            keyPassword = rmProperties.getProperty(USER_KEYPASS_PROP);
            //TODO
            ks = loadX509Data(certIS, keyIS, keyAlias, keyPassword);
            certIS.close();
            keyIS.close();
        }

        if (ks == null)
            throw new Exception("Was unable to find either: " + keyStorePath.getCanonicalPath()
                    + " or the pair of: " + certFilePath.getCanonicalPath() + " and "
                    + certKeyFilePath.getCanonicalPath() + " as specified.");

        // check that the spelling of key alias is proper
        Enumeration<String> as = ks.aliases();
        while (as.hasMoreElements()) {
            String a = as.nextElement();
            if (keyAlias.toLowerCase().equals(a.toLowerCase())) {
                keyAlias = a;
                break;
            }
        }

        // alias has to exist and have a key and cert present
        if (!ks.containsAlias(keyAlias)) {
            throw new Exception("Alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getKey(keyAlias, keyPassword.toCharArray()) == null)
            throw new Exception(
                    "Key with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");

        if (ks.getCertificate(keyAlias) == null) {
            throw new Exception(
                    "Certificate with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getCertificate(keyAlias).getType().equals("X.509")) {
            X509Certificate x509Cert = (X509Certificate) ks.getCertificate(keyAlias);
            try {
                x509Cert.checkValidity();
            } catch (Exception e) {
                throw new Exception("Certificate with alias " + keyAlias + " is not yet valid or has expired.");
            }
        }

        // add the identity into it
        mkm.addPrivateKey(keyAlias, (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray()),
                ks.getCertificate(keyAlias));

        // before we do SSL to this controller, set our identity
        mkm.setCurrentGuid(keyAlias);

        // register the protocol (Note: All xmlrpc clients must use XmlRpcCommonsTransportFactory
        // for this to work). See ContextualSSLProtocolSocketFactory.
        Protocol reghhttps = new Protocol("https", (ProtocolSocketFactory) regSslFact, 443);
        Protocol.registerProtocol("https", reghhttps);

        sslIdentitySet = true;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Unable to load user private key and certificate from the keystore: " + e);
    }

    //System.out.println("Exiting setSSLIdentity");

}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Test
public void testGenerateSelfSignedCert()
        throws GeneralSecurityException, IOException, OperatorCreationException {
    String dn = "CN=testDN,O=testOrg";

    X509Certificate x509Certificate = CertificateUtils.generateSelfSignedX509Certificate(
            TlsHelper.generateKeyPair(keyPairAlgorithm, keySize), dn, signingAlgorithm, days);

    Date notAfter = x509Certificate.getNotAfter();
    assertTrue(notAfter.after(inFuture(days - 1)));
    assertTrue(notAfter.before(inFuture(days + 1)));

    Date notBefore = x509Certificate.getNotBefore();
    assertTrue(notBefore.after(inFuture(-1)));
    assertTrue(notBefore.before(inFuture(1)));

    assertEquals(dn, x509Certificate.getIssuerX500Principal().getName());
    assertEquals(signingAlgorithm, x509Certificate.getSigAlgName());
    assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm());

    x509Certificate.checkValidity();
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/** 
 * Sign the payloadBody as-is. Note that this is going to be encrypted anyway
 * so we avoid any incompatibilities due to canonicalisation, and we don't
 * care if the payloadBody is text, compressed and so on. Re-writes payloadBody
 * with a serialised XML Digital Signature "Signature" element containing an
 * enveloping signature, or throws an exception to signal failure. 
 * //from  ww  w.  j  a v  a 2s  .  c o m
 * @param pk
 * @param cert
 * @throws Exception 
 */
private void signPayload(PrivateKey pk, X509Certificate cert) throws Exception {
    if ((pk == null) || (cert == null)) {
        throw new Exception("Null signing material");
    }
    cert.checkValidity();

    XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM");
    Reference ref = null;
    String objectRef = "uuid" + UUID.randomUUID().toString();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document doc = null;
    DOMStructure payloadContent = null;
    if (compressed || base64 || !mimeType.contains("xml")) {
        ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null));
        doc = dbf.newDocumentBuilder().newDocument();
        payloadContent = new DOMStructure(doc.createTextNode(payloadBody));
    } else {
        Transform t = xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",
                (TransformParameterSpec) null);
        ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(t), null, null);
        doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(payloadBody)));
        payloadContent = new DOMStructure(doc.getDocumentElement());
    }
    XMLObject payloadObject = xsf.newXMLObject(Collections.singletonList(payloadContent), objectRef, null,
            null);
    SignedInfo si = xsf.newSignedInfo(
            xsf.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));

    KeyInfoFactory kif = xsf.getKeyInfoFactory();
    ArrayList<Object> x509content = new ArrayList<Object>();
    x509content.add(cert);
    X509Data xd = kif.newX509Data(x509content);

    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
    XMLSignature signature = xsf.newXMLSignature(si, ki, Collections.singletonList(payloadObject), null, null);
    DOMSignContext dsc = new DOMSignContext(pk, doc);
    signature.sign(dsc);
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    Transformer tx = TransformerFactory.newInstance().newTransformer();
    tx.transform(new DOMSource(doc), sr);
    if (sw.toString().indexOf("<?xml ") == 0) {
        payloadBody = sw.toString().substring(sw.toString().indexOf("?>") + "?>".length());
    } else {
        payloadBody = sw.toString();
    }
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *    ?  ? ? ? ?/*  w  ww .j av  a 2 s.c  o m*/
 *
 * @param signers
 * @param clientCerts
 * @return
 */
private boolean reCheckClientSignature(SignerInformationStore signers, CertStore clientCerts)
        throws CertStoreException, NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    Iterator it = signers.getSigners().iterator();

    boolean overAllResult = true;
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        int indexOfSigner = 0;
        while (certIt.hasNext()) {
            indexOfSigner++;
            X509Certificate cert = (X509Certificate) certIt.next();
            //System.out.println( "------   ?: " + indexOfSigner+ " ----- ");
            //System.out.println( cert );
            try {
                cert.checkValidity();
                overAllResult = (overAllResult) && (signer.verify(cert, providerName));
            } catch (CertificateExpiredException ex) {
                verifyErrorMsg = " ??   ?  !";
                Logger.getLogger(SecureManager.class.getName()).log(Level.SEVERE, "ORE SIGN2:", ex);
                return false;
            } catch (CertificateNotYetValidException ex) {
                verifyErrorMsg = "  ?    ?!";
                Logger.getLogger(SecureManager.class.getName()).log(Level.SEVERE, "ORE SIGN3:", ex);
                return false;
            }
        }
        if (indexOfSigner == 0) {
            verifyErrorMsg = "? ? ,    ?   ? ?!";
        }

        if (!overAllResult) {
            verifyErrorMsg = " ?   ?  !";
        }
    }
    return overAllResult;
}

From source file:org.warlock.itk.distributionenvelope.Payload.java

/**
 * Add an X.509v3 certificate for a recipient.
 * /*  ww w  .  ja v  a 2 s.c  o  m*/
 * @param r 
 */
public void addReaderCertificate(X509Certificate r) throws Exception {
    if (r == null) {
        throw new Exception("Null certificate");
    }
    // Date range check against current date and time
    //
    r.checkValidity();

    // Allowed use check. Need to check that the certificate is issued
    // for usages that include "data encipherment". By default, require a
    // "key usage" extension unless the compile-time "allowNonUsageCertificates"
    // has been set.
    //
    // This is here where other certificate checking steps are handled elsewhere,
    // because the "data encipherment" usage is a specific usage type for the
    // content encryption.
    //
    boolean[] usage = r.getKeyUsage();
    if (usage != null) {
        if (!usage[DATAENCIPHERMENTUSAGE]) {
            throw new Exception(
                    "Certificate " + r.getSubjectDN().getName() + " not valid for data encipherment");
        }
    } else {
        if (!allowNonUsageCertificates) {
            throw new Exception("Certificate " + r.getSubjectDN().getName() + " has no key usage extension.");
        }
    }
    // This is included but commented out specifically to make the point that
    // section 4.2.1.3, "Key Usage" in RFC2459 says that the "key encipherment"
    // usage is for key management, so it isn't relevant here.
    //
    //        if (!usage[KEYENCIPHERMENTUSAGE]) {
    //            throw new Exception("Certificate " + r.getSubjectDN().getName() + " not valid for key encipherment");
    //        }
    encrypted = true;
    readerCerts.add(r);
}

From source file:org.sinekartads.smartcard.SmartCardAccess.java

public X509Certificate selectCertificate(String alias) throws SmartCardAccessException {
    if (iaikSession == null) {
        tracer.error("Session not initialized, login before");
        throw new IllegalStateException("Session not initialized, login before");
    }//from  w  w w  . j  ava  2  s  . co  m
    iaikPrivateKey = null;

    // Look for the suitable signing certificate with the given alias
    X509Certificate cert = null;
    X509PublicKeyCertificate iaikCert;
    Iterator<X509PublicKeyCertificate> iaikCertificateIt = iaikCertificateList().iterator();
    while (iaikCertificateIt.hasNext() && iaikPrivateKey == null) {

        // Transform the iaik certificate to a X509 instance
        iaikCert = iaikCertificateIt.next();
        cert = toX509Certificate(iaikCert);

        String curAlias = DNParser.parse(cert.getSubjectX500Principal().getName(), "CN");
        if (curAlias.equals(alias)) {

            if (cert.getKeyUsage()[1]) {
                // Accept the certificate only if has the digitalSignature usage
                // available
                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    tracer.error("Invalid certificate, expired!", e);
                    throw new CertificateListException("Invalid certificate, expired!", e);
                } catch (CertificateNotYetValidException e) {
                    tracer.error("Invalid certificate, not yet valid!", e);
                    throw new CertificateListException("Invalid certificate, not yet valid!", e);
                }

                Object[] iaikCorrespondingKeys;
                try {
                    // Init the privateKey seek
                    RSAPrivateKey iaikPrivateSignatureKeyTemplate = new RSAPrivateKey();
                    iaikPrivateSignatureKeyTemplate.getId()
                            .setByteArrayValue(iaikCert.getId().getByteArrayValue());
                    iaikSession.findObjectsInit(iaikPrivateSignatureKeyTemplate);

                    // Look for the privateKey
                    iaikCorrespondingKeys = iaikSession.findObjects(1);

                    // Extract the private key result and store it into the
                    // iaikPrivateKey property
                    iaikPrivateKey = (RSAPrivateKey) iaikCorrespondingKeys[0];

                    // Look for the privateKey
                    iaikCorrespondingKeys = iaikSession.findObjects(1);

                } catch (TokenException e) {
                    tracer.error("Unable to read private key from smart card (findObjectsInit)", e);
                    throw new CertificateListException(
                            "Unable to read private key from smart card (findObjectsInit)", e);
                } finally {
                    try {
                        iaikSession.findObjectsFinal();
                    } catch (TokenException e) {
                        tracer.error("Unable to read private key from smart card (findObjectsFinal)", e);
                        throw new CertificateListException(
                                "Unable to read private key from smart card (findObjectsFinal)", e);
                    }
                }
                break;
            } else {
                tracer.error("Invalid certificate, Not for digital signature!");
                throw new CertificateListException("Invalid certificate, Not for digital signature!");
            }
        }
    }

    return cert;
}

From source file:org.ejbca.ui.web.admin.keybind.InternalKeyBindingMBean.java

/** @return list of gui representations for all the InternalKeyBindings of the current type*/
public ListDataModel getInternalKeyBindingGuiList() {
    if (internalKeyBindingGuiList == null) {
        // Get the current type of tokens we operate on
        final String internalKeyBindingType = getSelectedInternalKeyBindingType();
        List<GuiInfo> internalKeyBindingList = new LinkedList<GuiInfo>();
        for (InternalKeyBindingInfo current : internalKeyBindingSession
                .getInternalKeyBindingInfos(authenticationToken, internalKeyBindingType)) {
            final int cryptoTokenId = current.getCryptoTokenId();
            final CryptoTokenInfo cryptoTokenInfo = cryptoTokenManagementSession
                    .getCryptoTokenInfo(cryptoTokenId);
            final String cryptoTokenName;
            boolean cryptoTokenAvailable = false;
            boolean cryptoTokenActive = false;
            if (cryptoTokenInfo == null) {
                cryptoTokenName = "unknown";
            } else {
                cryptoTokenAvailable = accessControlSession.isAuthorizedNoLogging(authenticationToken,
                        CryptoTokenRules.GENERATE_KEYS.resource() + "/" + cryptoTokenId);
                cryptoTokenActive = cryptoTokenInfo.isActive();
                cryptoTokenName = cryptoTokenInfo.getName();
            }//from   ww  w  . j  a  v  a 2s  . c  om
            final String certificateId = current.getCertificateId();
            final Certificate certificate = certificateId == null ? null
                    : certificateStoreSession.findCertificateByFingerprint(certificateId);
            String certificateIssuerDn = "";
            String certificateSubjectDn = "";
            String certificateSerialNumber = "";
            String caCertificateIssuerDn = "";
            String caCertificateSerialNumber = "";
            String certificateInternalCaName = null;
            int certificateInternalCaId = 0;
            String status = current.getStatus().name();
            if (certificate != null) {
                certificateSubjectDn = CertTools.getSubjectDN(certificate);
                certificateIssuerDn = CertTools.getIssuerDN(certificate);
                certificateSerialNumber = CertTools.getSerialNumberAsString(certificate);
                try {
                    // Note that we can do lookups using the .hashCode, but we will use the objects id
                    final CA ca = caSession.getCANoLog(authenticationToken, certificateIssuerDn.hashCode());
                    certificateInternalCaName = ca.getName();
                    certificateInternalCaId = ca.getCAId();
                    caCertificateIssuerDn = CertTools.getIssuerDN(ca.getCACertificate());
                    caCertificateSerialNumber = CertTools.getSerialNumberAsString(ca.getCACertificate());
                } catch (Exception e) {
                    // CADoesntExistsException or AuthorizationDeniedException
                    // The CA is for the purpose of "internal" renewal not available to this administrator.
                    // Try to find the issuer (CA) certificate by other means, trying to get it through CA certificate link from the bound certificate 
                    CertificateInfo info = certificateStoreSession.getCertificateInfo(certificateId);
                    final Certificate cacertificate = info.getCAFingerprint() == null ? null
                            : certificateStoreSession.findCertificateByFingerprint(info.getCAFingerprint());
                    if (cacertificate != null) {
                        caCertificateIssuerDn = CertTools.getIssuerDN(cacertificate);
                        caCertificateSerialNumber = CertTools.getSerialNumberAsString(cacertificate);
                    }
                }
                // Check for additional informative UI states
                if (InternalKeyBindingStatus.ACTIVE.equals(current.getStatus())) {
                    // Check if certificate is expired
                    if (certificate instanceof X509Certificate) {
                        final X509Certificate x509Certificate = (X509Certificate) certificate;
                        try {
                            x509Certificate.checkValidity();
                            // Check if certificate is revoked
                            if (certificateStoreSession.isRevoked(certificateIssuerDn,
                                    x509Certificate.getSerialNumber())) {
                                status = "REVOKED";
                            }
                        } catch (CertificateExpiredException e) {
                            status = "EXPIRED";
                        } catch (CertificateNotYetValidException e) {
                            status = "NOTYETVALID";
                        }
                    }
                }
            }
            internalKeyBindingList.add(new GuiInfo(current.getId(), current.getName(), cryptoTokenId,
                    cryptoTokenName, cryptoTokenAvailable, cryptoTokenActive, current.getKeyPairAlias(),
                    current.getNextKeyPairAlias(), status, current.getCertificateId(), certificateIssuerDn,
                    certificateSubjectDn, certificateInternalCaName, certificateInternalCaId,
                    certificateSerialNumber, caCertificateIssuerDn, caCertificateSerialNumber));
            Collections.sort(internalKeyBindingList, new Comparator<GuiInfo>() {
                @Override
                public int compare(final GuiInfo guiInfo1, final GuiInfo guiInfo2) {
                    return guiInfo1.getName().compareToIgnoreCase(guiInfo2.getName());
                }
            });
        }
        internalKeyBindingGuiList = new ListDataModel(internalKeyBindingList);
    }
    // View the list will purge the view cache
    flushSingleViewCache();
    return internalKeyBindingGuiList;
}