Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

In this page you can find the example usage for java.security KeyStore getCertificate.

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:org.tolven.config.model.CredentialManager.java

public void processTrustStore(TrustStoreDetail trustStoreDetail) {
    try {/*from w  w  w . j  a  va  2  s  . c  o  m*/
        Set<X509Certificate> newTrustStoreCerts = new HashSet<X509Certificate>();
        Set<X509Certificate> previousTrustStoreCerts = new HashSet<X509Certificate>();
        Set<X509Certificate> resultingTrustStoreCerts = new HashSet<X509Certificate>();
        for (TrustStoreCertificateDetail trustStoreCertificateDetail : trustStoreDetail.getCertificate()) {
            CertificateGroupDetail certGroup = getTolvenConfigWrapper()
                    .getCredentialGroup(trustStoreCertificateDetail.getRefId());
            if (certGroup == null) {
                throw new RuntimeException("The trusted group " + trustStoreCertificateDetail.getRefId()
                        + " in truststore " + trustStoreDetail.getId() + " does not exist");
            }
            X509Certificate trustStoreX509Certificate = getTolvenConfigWrapper().getX509Certificate(certGroup);
            newTrustStoreCerts.add(trustStoreX509Certificate);
        }
        File trustStoreFile = new File(trustStoreDetail.getSource());
        if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PEM.equals(trustStoreDetail.getFormat())) {
            if (trustStoreFile.exists()) {
                previousTrustStoreCerts = getTolvenConfigWrapper().getX509Certificates(trustStoreFile);
                for (X509Certificate cert : previousTrustStoreCerts) {
                    resultingTrustStoreCerts.add(cert);
                }
            }
            // And now for what Java calls a Set intersection
            resultingTrustStoreCerts.retainAll(newTrustStoreCerts);
            if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size()
                    || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) {
                FileOutputStream out = null;
                try {
                    out = new FileOutputStream(trustStoreFile);
                    for (X509Certificate x509Certificate : newTrustStoreCerts) {
                        out.write(convertToPEMBytes(x509Certificate));
                    }
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
                logger.info("Created truststore: " + trustStoreDetail.getId());
            }
        } else if (TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_JKS.equals(trustStoreDetail.getFormat())
                || TolvenConfigWrapper.TOLVEN_CREDENTIAL_FORMAT_PKCS12.equals(trustStoreDetail.getFormat())) {
            char[] truststorepass = getPasswordHolder().getPassword(trustStoreDetail.getId());
            if (trustStoreFile.exists()) {
                KeyStore trustStore = getTolvenConfigWrapper().getKeyStore(truststorepass, trustStoreFile,
                        trustStoreDetail.getFormat());
                Enumeration<String> enumeration = trustStore.aliases();
                while (enumeration.hasMoreElements()) {
                    String alias = enumeration.nextElement();
                    X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                    previousTrustStoreCerts.add(cert);
                    resultingTrustStoreCerts.add(cert);
                }
            }
            // And now for what Java calls a Set intersection
            resultingTrustStoreCerts.retainAll(newTrustStoreCerts);
            if (resultingTrustStoreCerts.size() != newTrustStoreCerts.size()
                    || !resultingTrustStoreCerts.containsAll(newTrustStoreCerts)) {
                KeyStore trustStore = KeyStore.getInstance(trustStoreDetail.getFormat());
                trustStore.load(null, truststorepass);
                for (X509Certificate newCert : newTrustStoreCerts) {
                    String alias = newCert.getSubjectDN().getName();
                    trustStore.setCertificateEntry(alias, newCert);
                }
                trustStoreFile.getParentFile().mkdirs();
                write(trustStore, trustStoreFile, truststorepass);
                logger.info("Created truststore: " + trustStoreDetail.getId());
            }
        } else {
            throw new RuntimeException("Unrecognized keystore format: " + trustStoreDetail.getFormat());
        }
    } catch (Exception ex) {
        throw new RuntimeException("Failed to process truststore: " + trustStoreDetail.getId(), ex);
    }
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void service(String operation, String message, String remoteAddr, HttpServletResponse response)
        throws IOException {
    try {//w ww. j a  v a2s.  c o  m
        if ((operation == null) || (message == null)) {
            log.error("Got request missing operation and/or message parameters.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameters 'operation' and 'message' must be supplied!");
            return;
        }
        log.debug("Got request '" + operation + "'");
        log.debug("Message: " + message);
        log.debug("Operation is : " + operation);

        String alias = scepraks.getAlias();
        log.debug("SCEP RA Keystore alias : " + alias);
        KeyStore raks = scepraks.getKeyStore();
        Certificate[] chain = raks.getCertificateChain(alias);
        X509Certificate cacert = null;
        if (chain.length > 1) {
            // This should absolutely be more than one!
            cacert = (X509Certificate) chain[1];
        } else {
            log.error(
                    "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates.");
        }
        X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        String kspwd = ExtraConfiguration.instance()
                .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber);
        PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray());

        if (operation.equals("PKIOperation")) {
            byte[] scepmsg = Base64.decode(message.getBytes());

            // Read the message end get the cert, this also checks authorization
            boolean includeCACert = true;
            if (StringUtils.equals("0", getInitParameter("includeCACert"))) {
                includeCACert = false;
            }

            byte[] reply = null;
            ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert);
            String transId = reqmsg.getTransactionId();
            log.debug("Received a message of type: " + reqmsg.getMessageType());
            if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) {
                log.info("Received a GetCertInitial message from host: " + remoteAddr);
                Message msg = null;
                try {
                    msg = msgHome.findByMessageId(transId);
                } catch (Exception e) {
                    // TODO: internal resources
                    log.info("Error looking for message with transId " + transId + " :", e);
                }
                if (msg != null) {
                    if (msg.getStatus().equals(Message.STATUS_PROCESSED)) {
                        log.debug("Request is processed with status: " + msg.getStatus());
                        SubMessages submessagesresp = msg.getSubMessages(null, null, null);
                        Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator();
                        PKCS10Response resp = (PKCS10Response) iter.next();
                        // create proper ScepResponseMessage
                        IResponseMessage ret = reqmsg.createResponseMessage(
                                org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv,
                                cryptProvider);
                        ret.setCACert(cacert);
                        X509Certificate respCert = resp.getCertificate();
                        if (resp.isSuccessful() && (respCert != null)) {
                            ret.setCertificate(respCert);
                        } else {
                            ret.setStatus(ResponseStatus.FAILURE);
                            ret.setFailInfo(FailInfo.BAD_REQUEST);
                            String failText = resp.getFailInfo();
                            ret.setFailText(failText);
                        }
                        ret.create();
                        reply = ret.getResponseMessage();
                    } else {
                        log.debug("Request is not yet processed, status: " + msg.getStatus());
                        reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                                .getResponseMessage();
                        log.debug("Responding with pending response, still pending.");
                    }
                } else {
                    // User doesn't exist
                }
            } else {
                if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
                    log.debug("Received a PKCSReq message from host: " + remoteAddr);
                    // Decrypt the Scep message and extract the pkcs10 request
                    if (reqmsg.requireKeyInfo()) {
                        // scep encrypts message with the RAs certificate
                        reqmsg.setKeyInfo(racert, rapriv, cryptProvider);
                    }
                    // Verify the request
                    if (reqmsg.verify() == false) {
                        String msg = "POPO verification failed.";
                        log.error(msg);
                        throw new SignRequestSignatureException(msg);
                    }
                    String username = reqmsg.getUsername();
                    if (username == null) {
                        String msg = "No username in request, request DN: " + reqmsg.getRequestDN();
                        log.error(msg);
                        throw new SignRequestException(msg);
                    }
                    log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: "
                            + remoteAddr);
                    String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD);
                    if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) {
                        log.debug("Requiring authPwd in order to precess SCEP requests");
                        String pwd = reqmsg.getPassword();
                        if (!StringUtils.equals(authPwd, pwd)) {
                            log.error("Wrong auth password received in SCEP request: " + pwd);
                            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch");
                            return;
                        }
                        log.debug("Request passed authPwd test.");
                    } else {
                        log.debug("Not requiring authPwd in order to precess SCEP requests");
                    }
                    // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default
                    String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN());
                    String caName = ExtraConfiguration.instance().getString(issuerDN);
                    if (StringUtils.isEmpty(caName)) {
                        caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA);
                        log.info("Did not find a CA name from issuerDN: " + issuerDN
                                + ", using the default CA '" + caName + "'");
                    } else {
                        log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN);
                    }
                    // Get altNames if we can find them
                    String altNames = reqmsg.getRequestAltNames();

                    byte[] encoded = reqmsg.getCertificationRequest().getEncoded();
                    String pkcs10 = new String(Base64.encode(encoded, false));

                    // Create a pkcs10 request
                    String certificateProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPCERTPROFILEKEY);
                    String entityProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY);
                    boolean createOrEditUser = ExtraConfiguration.instance()
                            .getBoolean(ExtraConfiguration.SCEPEDITUSER);
                    PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null,
                            null, entityProfile, certificateProfile, caName, pkcs10);
                    req.setCreateOrEditUser(createOrEditUser);
                    SubMessages submessages = new SubMessages();
                    submessages.addSubMessage(req);
                    msgHome.create(transId, submessages);
                    reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                            .getResponseMessage();
                }
            }

            if (reply == null) {
                // This is probably a getCert message?
                log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response");
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request");
                return;
            }
            // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure
            sendBinaryBytes(reply, response, "application/x-pki-message", null);
        } else if (operation.equals("GetCACert")) {
            // The response has the content type tagged as application/x-x509-ca-cert. 
            // The body of the response is a DER encoded binary X.509 certificate. 
            // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509>
            // IF we are not an RA, which in case we should return the same thing as GetCACertChain
            log.info("Got SCEP cert request for CA '" + message + "'");
            if (chain != null) {
                if (chain.length > 1) {
                    // We are an RA, so return the same as GetCACertChain, but with other content type
                    getCACertChain(message, remoteAddr, response, alias, raks, false);
                } else {
                    // The CA certificate is no 0
                    X509Certificate cert = (X509Certificate) chain[0];
                    if (chain.length > 1) {
                        cert = (X509Certificate) chain[1];
                    }
                    log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
                    log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr);
                    sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null);
                }
            } else {
                log.error("No CA certificates found");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACertChain")) {
            // The response for GetCACertChain is a certificates-only PKCS#7 
            // SignedDatato carry the certificates to the end entity, with a 
            // Content-Type of application/x-x509-ca-ra-cert-chain.
            log.info("Got SCEP cert chain request for CA '" + message + "'");
            getCACertChain(message, remoteAddr, response, alias, raks, true);
        } else if (operation.equals("GetCACaps")) {
            // The response for GetCACaps is a <lf> separated list of capabilities

            /*
             "GetNextCACert"       CA Supports the GetNextCACert message.
             "POSTPKIOperation"    PKIOPeration messages may be sent via HTTP POST.
             "SHA-1"               CA Supports the SHA-1 hashing algorithm in 
                               signatures and fingerprints.  If present, the
                               client SHOULD use SHA-1.  If absent, the client
                               MUST use MD5 to maintain backward compatability.
             "Renewal"             Clients may use current certificate and key to
                               authenticate an enrollment request for a new
                               certificate.  
             */
            log.info("Got SCEP CACaps request for CA '" + message + "'");
            response.setContentType("text/plain");
            response.getOutputStream().print("POSTPKIOperation\nSHA-1");
        }
    } catch (java.lang.ArrayIndexOutOfBoundsException ae) {
        log.error("Empty or invalid request received.", ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage());
    } catch (Exception e) {
        log.error("Error in ScepRAServlet:", e);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private static void loadCA() throws Exception {
    KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12");

    File file = new File("test/resources/testdata/keys/testCA.p12");

    FileInputStream input = new FileInputStream(file);

    caKeyStore.load(input, "test".toCharArray());

    rootCertificate = (X509Certificate) caKeyStore.getCertificate("root");
    caCertificate = (X509Certificate) caKeyStore.getCertificate("ca");
    caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null);

    assertNotNull(caCertificate);/* w w w.jav a  2 s.  c o m*/
    assertNotNull(caPrivateKey);
}

From source file:be.agiv.security.AGIVSecurity.java

/**
 * Constructor for X509 credentials. The certificate and corresponding
 * private key are loaded from a PKCS#12 keystore file.
 * /* w ww.  ja v a2 s.co m*/
 * @param ipStsLocation
 *            the location of the IP-STS WS-Trust web service.
 * @param rStsLocation
 *            the location of the R-STS WS-Trust web service.
 * @param rStsRealm
 *            the AGIV R-STS realm.
 * @param pkcs12File
 *            the PKCS#12 keystore file.
 * @param pkcs12Password
 *            the PKCS#12 keystore password.
 * @throws SecurityException
 *             gets thrown in case of a PKCS#12 keystore error.
 * @see AGIVSecurity#AGIVSecurity(String, String, X509Certificate,
 *      PrivateKey)
 */
public AGIVSecurity(String ipStsLocation, String rStsLocation, String rStsRealm, File pkcs12File,
        String pkcs12Password) throws SecurityException {
    this.ipStsLocation = ipStsLocation;
    this.rStsLocation = rStsLocation;
    this.rStsRealm = rStsRealm;
    this.username = null;
    this.password = null;

    InputStream pkcs12InputStream;
    try {
        pkcs12InputStream = new FileInputStream(pkcs12File);
    } catch (FileNotFoundException e) {
        throw new SecurityException("PKCS#12 file does not exist: " + pkcs12File.getAbsolutePath());
    }
    Provider sunJSSEProvider = Security.getProvider("SunJSSE");
    try {
        KeyStore keyStore;
        if (null != sunJSSEProvider) {
            // avoid older BouncyCastle implementations
            keyStore = KeyStore.getInstance("PKCS12", sunJSSEProvider);
        } else {
            keyStore = KeyStore.getInstance("PKCS12");
        }
        keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = aliases.nextElement();
        this.certificate = (X509Certificate) keyStore.getCertificate(alias);
        this.privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
    } catch (Exception e) {
        LOG.error("error loading PKCS#12 keystore: " + e.getMessage(), e);
        throw new SecurityException("error loading PKCS#12 certificate: " + e.getMessage(), e);
    }
    this.externalIpStsClient = null;
    this.secureConversationTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.rStsSecurityTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.stsListeners = new CopyOnWriteArrayList<STSListener>();
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Lists keystore contents on STDOUT. Output is similar to keytool -list -v.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors.//from   w w  w .  j av  a 2s . co m
 */
protected void list(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final Enumeration<String> aliases = store.aliases();
    System.out.println("");
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        System.out.println("Alias name: " + alias);
        System.out.println("Creation date: " + store.getCreationDate(alias));
        if (store.isKeyEntry(alias)) {
            System.out.println("Entry type: keyEntry");

            final Certificate[] chain = store.getCertificateChain(alias);
            System.out.println("Certificate chain length: " + chain.length);
            for (int i = 0; i < chain.length; i++) {
                System.out.println("===== Certificate [" + i + "] =====");
                printCertificate(chain[i]);
            }
        } else {
            System.out.println("Entry type: trustedCertEntry");
            System.out.println("Certificate details:");
            printCertificate(store.getCertificate(alias));
        }
        System.out.println("");
        System.out.println("");
    }
}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * The subjectRDN argument is either an X500Principal or a BouncyCastle X509Name instance.
 *//*from  w  w w .  j a va 2  s.c om*/
private Vector getAlias(Object subjectRDN, KeyStore store) throws WSSecurityException {
    // Store the aliases found
    Vector aliases = new Vector();
    Certificate cert = null;

    try {
        for (Enumeration e = store.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();

            Certificate[] certs = store.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a  result.
                cert = store.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
                certs = new Certificate[] { cert };
            } else {
                cert = certs[0];
            }
            if (cert instanceof X509Certificate) {
                X500Principal foundRDN = ((X509Certificate) cert).getSubjectX500Principal();
                Object certName = createBCX509Name(foundRDN.getName());

                if (subjectRDN.equals(certName)) {
                    aliases.add(alias);
                }
            }
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore", null, e);
    }
    return aliases;
}

From source file:org.aselect.server.request.handler.xsaml20.Saml20_Metadata.java

/**
 * Read meta data public key cert.//from  ww  w. j a v  a  2  s. co  m
 * 
 * @param sWorkingDir
 *            the s working dir
 * @throws ASelectException
 *             the a select exception
 */
private void readMetaDataPublicKeyCert(String sWorkingDir) throws ASelectException {
    String sMethod = "readMetaDataPublicKeyCert";

    try {
        StringBuffer sbKeystoreLocation = new StringBuffer(sWorkingDir);
        sbKeystoreLocation.append(File.separator);
        sbKeystoreLocation.append("aselectserver");
        sbKeystoreLocation.append(File.separator);
        sbKeystoreLocation.append("keystores");
        sbKeystoreLocation.append(File.separator);
        sbKeystoreLocation.append(PUBLIC_KEYSTORE_NAME);
        _systemLogger.log(Level.INFO, MODULE, sMethod, "Read:" + sbKeystoreLocation);

        File fKeystore = new File(sbKeystoreLocation.toString());
        if (!fKeystore.exists()) {
            StringBuffer sbError = new StringBuffer("Keystore cannot be found: ");
            sbError.append(sbKeystoreLocation.toString());
            _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString());
            throw new ASelectException(Errors.ERROR_ASELECT_NOT_FOUND);
        }

        KeyStore ksASelect = KeyStore.getInstance("JKS");
        ksASelect.load(new FileInputStream(sbKeystoreLocation.toString()), null);

        Enumeration<?> enumAliases = ksASelect.aliases();
        while (enumAliases.hasMoreElements()) {
            String sAlias = (String) enumAliases.nextElement();

            sAlias = sAlias.toLowerCase();
            if (sAlias.equals(getPublicKeyAlias())) { // server_id A-Select IdP
                java.security.cert.X509Certificate x509Cert = (java.security.cert.X509Certificate) ksASelect
                        .getCertificate(sAlias);

                String encodedCert = new String(Base64.encodeBase64(x509Cert.getEncoded()));
                _systemLogger.log(Level.INFO, MODULE, sMethod, "Found public key alias for : "
                        + getPublicKeyAlias() + " retrieved encoded signing certificate");
                setSigningCertificate(encodedCert);
            }
        }
        if (getSigningCertificate() == null) {
            _systemLogger.log(Level.WARNING, MODULE, sMethod,
                    "No alias found for idp public key with name : " + getPublicKeyAlias());
            throw new ASelectException(Errors.ERROR_ASELECT_CONFIG_ERROR);
        }
    } catch (Exception e) {
        StringBuffer sbError = new StringBuffer(" Error loading public keys from directory: '");
        sbError.append(sWorkingDir);
        sbError.append("'");
        _systemLogger.log(Level.WARNING, MODULE, sMethod, sbError.toString(), e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    }
}

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

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

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

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

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

                break;
            }
        }
    } catch (KeyStoreException e) {

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

        throw new CertificateException(errMsg);
    }

    return x509issuer;
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

/**
 * Populate the available server public keys into a local static HashMap. This method is not
 * thread safe./* w  w  w.jav  a 2 s.c  o  m*/
 */
public static void initCertsMap(Properties props) throws Exception {

    certificateMap = new HashMap();
    certificateFilePath = props.getProperty(PUBLIC_KEY_FILE_PROP);
    if (certificateFilePath != null && certificateFilePath.length() > 0) {
        KeyStore ks = KeyStore.getInstance("JKS");
        String keyStorePass = props.getProperty(PUBLIC_KEY_PASSWD_PROP);
        char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
        FileInputStream keystorefile = new FileInputStream(certificateFilePath);
        try {
            ks.load(keystorefile, passPhrase);
        } finally {
            keystorefile.close();
        }
        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            Certificate cert = ks.getCertificate(alias);
            if (cert instanceof X509Certificate) {
                String subject = ((X509Certificate) cert).getSubjectDN().getName();
                certificateMap.put(subject, cert);
            }
        }
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);// w w w.j  a v a  2  s  .c om
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}