Example usage for java.security.cert X509Certificate getSubjectX500Principal

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

Introduction

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

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

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

Usage

From source file:be.fedict.trust.client.XKMS2Client.java

/**
 * If set, unilateral TLS authentication will occurs, verifying the server
 * {@link X509Certificate} specified {@link PublicKey}.
 * <p/>/*from  ww  w. j a  v  a2 s.  co  m*/
 * WARNING: only works when using the JAX-WS RI.
 * 
 * @param publicKey
 *            public key to validate server TLS certificate against.
 */
public void setServicePublicKey(final PublicKey publicKey) {
    // Create TrustManager
    TrustManager[] trustManager = { new X509TrustManager() {

        public X509Certificate[] getAcceptedIssuers() {

            return null;
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            X509Certificate serverCertificate = chain[0];
            LOG.debug("server X509 subject: " + serverCertificate.getSubjectX500Principal().toString());
            LOG.debug("authentication type: " + authType);
            if (null == publicKey) {
                LOG.warn("not performing any server certificate validation at all");
                return;
            }

            try {
                serverCertificate.verify(publicKey);
                LOG.debug("valid server certificate");
            } catch (InvalidKeyException e) {
                throw new CertificateException("Invalid Key");
            } catch (NoSuchAlgorithmException e) {
                throw new CertificateException("No such algorithm");
            } catch (NoSuchProviderException e) {
                throw new CertificateException("No such provider");
            } catch (SignatureException e) {
                throw new CertificateException("Wrong signature");
            }
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            throw new CertificateException("this trust manager cannot be used as server-side trust manager");
        }
    } };

    // Create SSL Context
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        SecureRandom secureRandom = new SecureRandom();
        sslContext.init(null, trustManager, secureRandom);
        LOG.debug("SSL context provider: " + sslContext.getProvider().getName());

        // Setup TrustManager for validation
        Map<String, Object> requestContext = ((BindingProvider) this.port).getRequestContext();
        requestContext.put("com.sun.xml.ws.transport.https.client.SSLSocketFactory",
                sslContext.getSocketFactory());

    } catch (KeyManagementException e) {
        String msg = "key management error: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    } catch (NoSuchAlgorithmException e) {
        String msg = "TLS algo not present: " + e.getMessage();
        LOG.error(msg, e);
        throw new RuntimeException(msg, e);
    }
}

From source file:org.apache.ws.security.validate.SignatureTrustValidator.java

/**
 * @return      true if the certificate's SubjectDN matches the constraints defined in the
 *              subject DNConstraints; false, otherwise. The certificate subject DN only
 *              has to match ONE of the subject cert constraints (not all).
 *//*  w  w  w  .  jav a2 s.c  o m*/
protected boolean matches(final java.security.cert.X509Certificate cert,
        final Collection<Pattern> subjectDNPatterns) {
    if (subjectDNPatterns.isEmpty()) {
        LOG.warn("No Subject DN Certificate Constraints were defined. This could be a security issue");
    }
    if (!subjectDNPatterns.isEmpty()) {
        if (cert == null) {
            LOG.debug("The certificate is null so no constraints matching was possible");
            return false;
        }
        String subjectName = cert.getSubjectX500Principal().getName();
        boolean subjectMatch = false;
        for (Pattern subjectDNPattern : subjectDNPatterns) {
            final Matcher matcher = subjectDNPattern.matcher(subjectName);
            if (matcher.matches()) {
                LOG.debug("Subject DN " + subjectName + " matches with pattern " + subjectDNPattern);
                subjectMatch = true;
                break;
            }
        }
        if (!subjectMatch) {
            return false;
        }
    }

    return true;
}

From source file:eu.peppol.outbound.transmission.As2MessageSender.java

/**
 * Handles the HTTP 200 POST response (the MDN with status indications)
 *
 * @param transmissionId the transmissionId (used in HTTP headers as Message-ID)
 * @param outboundMic    the calculated mic of the payload (should be verified against the one returned in MDN)
 * @param postResponse   the http response to be decoded as MDN
 * @return//from ww  w .j  a  va2  s  . co m
 */
MimeMessage handleTheHttpResponse(TransmissionId transmissionId, Mic outboundMic,
        CloseableHttpResponse postResponse, SmpLookupManager.PeppolEndpointData peppolEndpointData) {

    try {

        HttpEntity entity = postResponse.getEntity(); // Any textual results?
        if (entity == null) {
            throw new IllegalStateException(
                    "No contents in HTTP response with rc=" + postResponse.getStatusLine().getStatusCode());
        }

        String contents = EntityUtils.toString(entity);

        if (traceEnabled) {
            log.debug("HTTP-headers:");
            Header[] allHeaders = postResponse.getAllHeaders();
            for (Header header : allHeaders) {
                log.debug("" + header.getName() + ": " + header.getValue());
            }
            log.debug("Contents:\n" + contents);
            log.debug("---------------------------");
        }

        Header contentTypeHeader = postResponse.getFirstHeader("Content-Type");
        if (contentTypeHeader == null) {
            throw new IllegalStateException("No Content-Type header in response, probably a server error");
        }
        String contentType = contentTypeHeader.getValue();

        MimeMessage mimeMessage = null;
        try {
            mimeMessage = MimeMessageHelper.parseMultipart(contents, new MimeType(contentType));

            try {
                mimeMessage.writeTo(System.out);
            } catch (MessagingException e) {
                throw new IllegalStateException("Unable to print mime message");
            }

        } catch (MimeTypeParseException e) {
            throw new IllegalStateException("Invalid Content-Type header");
        }

        // verify the signature of the MDN, we warn about dodgy signatures
        try {
            SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
            X509Certificate cert = signedMimeMessage.getSignersX509Certificate();
            cert.checkValidity();

            // Verify if the certificate used by the receiving Access Point in
            // the response message does not match its certificate published by the SMP
            if (peppolEndpointData.getCommonName() == null || !CommonName
                    .valueOf(cert.getSubjectX500Principal()).equals(peppolEndpointData.getCommonName())) {
                throw new CertificateException(
                        "Common name in certificate from SMP does not match common name in AP certificate");
            }

            log.debug("MDN signature was verfied for : " + cert.getSubjectDN().toString());
        } catch (Exception ex) {
            log.warn("Exception when verifying MDN signature : " + ex.getMessage());
        }

        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();

        if (mdnMimeMessageInspector.isOkOrWarning(outboundMic)) {

            return mimeMessage;
        } else {
            log.error("AS2 transmission failed with some error message, msg :" + msg);
            log.error(contents);
            throw new IllegalStateException("AS2 transmission failed : " + msg);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to obtain the contents of the response: " + e.getMessage(), e);
    } finally {
        try {
            postResponse.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to close http connection: " + e.getMessage(), e);
        }
    }

}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private OCSPUnidResponse sendOCSPRequest(byte[] ocspPackage, X509Certificate knownTrustAnchor, boolean useGet)
        throws IOException, OCSPException, OperatorCreationException, CertificateException,
        UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    final HttpURLConnection con;
    if (useGet) {
        String b64 = new String(Base64.encode(ocspPackage, false));
        URL url = new URL(httpReqPath + '/' + b64);
        con = (HttpURLConnection) url.openConnection();
    } else {//  w  ww  . jav a 2  s  .c o  m
        // POST the OCSP request
        URL url = new URL(httpReqPath);
        con = (HttpURLConnection) getUrlConnection(url);
        // we are going to do a POST
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        // POST it
        con.setRequestProperty("Content-Type", "application/ocsp-request");
        OutputStream os = null;
        try {
            os = con.getOutputStream();
            os.write(ocspPackage);
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }
    final OCSPUnidResponse ret = new OCSPUnidResponse();
    ret.setHttpReturnCode(con.getResponseCode());
    if (ret.getHttpReturnCode() != 200) {
        if (ret.getHttpReturnCode() == 401) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNAUTHORIZED);
        } else {
            ret.setErrorCode(OCSPUnidResponse.ERROR_UNKNOWN);
        }
        return ret;
    }
    final OCSPResp response;
    {
        final InputStream in = con.getInputStream();
        if (in != null) {
            try {
                response = new OCSPResp(IOUtils.toByteArray(in));
            } finally {
                in.close();
            }
        } else {
            response = null;
        }
    }
    if (response == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    ret.setResp(response);
    final BasicOCSPResp brep = (BasicOCSPResp) response.getResponseObject();
    if (brep == null) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_NO_RESPONSE);
        return ret;
    }
    // Compare nonces to see if the server sent the same nonce as we sent
    final byte[] noncerep = brep.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce).getExtnValue()
            .getEncoded();
    if (noncerep != null) {
        ASN1InputStream ain = new ASN1InputStream(noncerep);
        ASN1OctetString oct = ASN1OctetString.getInstance(ain.readObject());
        ain.close();
        boolean eq = ArrayUtils.isEquals(this.nonce, oct.getOctets());
        if (!eq) {
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_NONCE);
            return ret;
        }
    }

    final RespID id = brep.getResponderId();
    final DERTaggedObject to = (DERTaggedObject) id.toASN1Object().toASN1Primitive();
    final RespID respId;
    final X509CertificateHolder[] chain = brep.getCerts();
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    X509Certificate signerCertificate = converter.getCertificate(chain[0]);
    final PublicKey signerPub = signerCertificate.getPublicKey();
    if (to.getTagNo() == 1) {
        // This is Name
        respId = new JcaRespID(signerCertificate.getSubjectX500Principal());
    } else {
        // This is KeyHash
        respId = new JcaRespID(signerPub, SHA1DigestCalculator.buildSha1Instance());
    }
    if (!id.equals(respId)) {
        // Response responderId does not match signer certificate responderId!
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERID);
    }
    if (!brep.isSignatureValid(new JcaContentVerifierProviderBuilder().build(signerPub))) {
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNATURE);
        return ret;
    }

    /* 
     * Okay, at this point we have three different variables and six different possible valid use cases. These
     * variables are:
     *          1. If the OCSP reply is from a CA (integrated) or an OCSP responder (standalone) 
     *          2. If it was from a CA, then if that CA is self signed or a subCA
     *          3. If the server (in the integrated case) or keybinding (standalone case) was set to include the certificate chain
     */

    //If we have a chain, verify it
    if (chain.length > 1) {
        // end at one shortof chain.length, because the root certificate is (usually) not included in the OCSP response
        // TODO: improve this when we can pass in the root cert from parameter to properly validate the whole chain
        for (int i = 0; i + 1 < chain.length; i++) {
            final X509Certificate cert1 = converter.getCertificate(chain[i]);
            final X509Certificate cert2 = converter.getCertificate(chain[Math.min(i + 1, chain.length - 1)]);
            try {
                cert1.verify(cert2.getPublicKey());
            } catch (GeneralSecurityException e) {
                m_log.info("Verifying problem with", e);
                m_log.info("Certificate to be verified: " + cert1);
                m_log.info("Verifying certificate: " + cert2);
                ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
                return ret;
            }
        }
    }

    if (CertTools.isCA(signerCertificate)) {
        //Verify that the signer certificate was the same as the trust anchor
        if (!signerCertificate.getSerialNumber().equals(knownTrustAnchor.getSerialNumber())) {
            m_log.info("Signing certificate for integrated OCSP was not the provided trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else if (CertTools.isOCSPCert(signerCertificate)) {
        //If an OCSP certificate was used to sign
        try {
            signerCertificate.verify(knownTrustAnchor.getPublicKey());
        } catch (GeneralSecurityException e) {
            m_log.info("Signing certificate was not signed by known trust anchor.");
            ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
            return ret;
        }
    } else {
        m_log.info("Signing certificate was not an OCSP certificate.");
        ret.setErrorCode(OCSPUnidResponse.ERROR_INVALID_SIGNERCERT);
        return ret;
    }

    String fnr = getFnr(brep);
    if (fnr != null) {
        ret.setFnr(fnr);
    }
    return ret;
}

From source file:org.globus.gsi.stores.PEMKeyStore.java

private void loadDirectories(String directoryList) throws CertificateException {

    try {//from  ww  w  .j  a v  a 2 s .  co  m
        caDelegate.loadWrappers(directoryList);
        Map<String, ResourceTrustAnchor> wrapperMap = caDelegate.getWrapperMap();
        Set<String> knownCerts = new HashSet<String>();
        // The alias hashing merits explanation.  Loading all the files in a directory triggers a
        // deadlock bug for old jglobus clients if the directory contains repeated CAs (like the
        // modern IGTF bundle does).  So, we ignore the cert if the alias is incorrect or already seen.
        // However, we track all the certs we ignore and load any that were completely ignored due to
        // aliases.  So, non-hashed directories will still work.
        Map<String, String> ignoredAlias = new HashMap<String, String>();
        Map<String, ResourceTrustAnchor> ignoredAnchor = new HashMap<String, ResourceTrustAnchor>();
        Map<String, X509Certificate> ignoredCert = new HashMap<String, X509Certificate>();
        for (ResourceTrustAnchor trustAnchor : wrapperMap.values()) {
            String alias = trustAnchor.getResourceURL().toExternalForm();
            TrustAnchor tmpTrustAnchor = trustAnchor.getTrustAnchor();
            X509Certificate trustCert = tmpTrustAnchor.getTrustedCert();
            String hash = CertificateIOUtil.nameHash(trustCert.getSubjectX500Principal());
            if (this.aliasObjectMap == null) {
                System.out.println("Alias Map Null");
            }
            boolean hash_in_alias = !alias.contains(hash);
            if (knownCerts.contains(hash) || !hash_in_alias) {
                if (!hash_in_alias) {
                    ignoredAlias.put(hash, alias);
                    ignoredAnchor.put(hash, trustAnchor);
                    ignoredCert.put(hash, trustCert);
                }
                continue;
            }
            knownCerts.add(hash);
            this.aliasObjectMap.put(alias, trustAnchor);
            certFilenameMap.put(trustCert, alias);
        }
        // Add any CA we skipped above.
        for (String hash : ignoredAlias.keySet()) {
            if (knownCerts.contains(hash)) {
                continue;
            }
            String alias = ignoredAlias.get(hash);
            this.aliasObjectMap.put(alias, ignoredAnchor.get(hash));
            certFilenameMap.put(ignoredCert.get(hash), alias);
        }
    } catch (ResourceStoreException e) {
        throw new CertificateException("", e);
    }
}

From source file:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java

private X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, DateTime notBefore,
        DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey) throws Exception {

    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();/*  ww  w .  ja  v  a  2 s  . c o  m*/
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());

    X509Principal issuerDN;
    if (null != issuerCertificate) {
        issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            createSubjectKeyId(subjectPublicKey));

    PublicKey issuerPublicKey;
    if (null != issuerCertificate) {
        issuerPublicKey = issuerCertificate.getPublicKey();
    } else {
        issuerPublicKey = subjectPublicKey;
    }
    certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            createAuthorityKeyId(issuerPublicKey));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
}

From source file:net.sf.keystore_explorer.gui.actions.GenerateCsrAction.java

/**
 * Do action.//  w  w w.  j  a va2s.com
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:org.dataone.proto.trove.net.SocketFactoryManager.java

/**
 * Load PEM file contents into in-memory keystore NOTE: this implementation uses Bouncy Castle security provider
 *
 * @return the keystore that will provide the material
 * @throws KeyStoreException/*from   w w w  .j  av  a 2  s  . c o m*/
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
private KeyStore getKeyStore()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    // if the location has been set, use it
    KeyStore keyStore = null;
    Object pemObject = null;

    keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, keyStorePassword.toCharArray());

    // get the private key and certificate from the PEM
    // TODO: find a way to do this with default Java provider (not Bouncy Castle)?
    Security.addProvider(new BouncyCastleProvider());
    PEMParser pemReader = new PEMParser(new FileReader(clientCertificateLocation));

    X509Certificate certificate = null;
    PrivateKey privateKey = null;
    KeyPair keyPair = null;

    while ((pemObject = pemReader.readObject()) != null) {
        if (pemObject instanceof PrivateKey) {
            privateKey = (PrivateKey) pemObject;
        } else if (pemObject instanceof KeyPair) {
            keyPair = (KeyPair) pemObject;
            privateKey = keyPair.getPrivate();
        } else if (pemObject instanceof X509Certificate) {
            certificate = (X509Certificate) pemObject;
        }
    }
    if (certificate == null) {
        log.warn("Certificate is null");
    } else {
        if (certificate.getSubjectX500Principal().getName(X500Principal.RFC2253)
                .equals(certificate.getIssuerX500Principal().getName(X500Principal.RFC2253))) {
            log.warn("Certificate is Self Signed");
        }
    }
    Certificate[] chain = new Certificate[] { certificate };

    // set the entry
    keyStore.setKeyEntry("cilogon", privateKey, keyStorePassword.toCharArray(), chain);

    return keyStore;

}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testCAAliases() throws Exception {
    // setup/*from   w ww  . j  av  a2s.co  m*/
    Security.addProvider(new BeIDProvider());
    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    // operate
    X509Certificate citizenCACertificate = (X509Certificate) keyStore.getCertificate("CA");
    X509Certificate rootCACertificate = (X509Certificate) keyStore.getCertificate("Root");
    X509Certificate rrnCertificate = (X509Certificate) keyStore.getCertificate("RRN");

    // verify
    assertNotNull(citizenCACertificate);
    LOG.debug("citizen CA: " + citizenCACertificate.getSubjectX500Principal());
    assertNotNull(rootCACertificate);
    LOG.debug("root CA: " + rootCACertificate.getSubjectX500Principal());
    assertNotNull(rrnCertificate);
    assertTrue(rrnCertificate.getSubjectX500Principal().toString().contains("RRN"));
}

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");
    }//w w w .  ja  va2 s.  c  om
    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;
}