Example usage for java.security KeyStore load

List of usage examples for java.security KeyStore load

Introduction

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

Prototype

public final void load(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Loads this KeyStore from the given input stream.

Usage

From source file:biz.mosil.webtools.MosilSSLSocketFactory.java

public static HttpClient getHttpClient(HttpParams _params) {
    try {//from   w w w .  java2 s. co  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory factory = new MosilSSLSocketFactory(trustStore);
        factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpProtocolParams.setVersion(_params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(_params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), MosilWebConf.HTTP_PORT));
        registry.register(new Scheme("https", factory, MosilWebConf.SSL_PORT));

        ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(_params, registry);

        return new DefaultHttpClient(clientConnectionManager, _params);

    } catch (Exception _ex) {
        return new DefaultHttpClient();
    }
}

From source file:com.iaspec.rda.plugins.rfid.license.LicenseReader.java

public static void verifyChallengeCode(String challenge, String expect, Device device) throws RdaException {
    ChallengeVerifier verifier = ChallengeVerifier.getInstance();
    byte[] pkcs7 = Base64.decode(challenge);
    SignatureVerificationResultHolder resultHolder = null;
    try {/*from   ww w  . j a  v a 2  s  .c  o m*/
        resultHolder = verifier.verifySignature(pkcs7);
    } catch (SignatureInvalidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (CryptoException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }
    CertificateDnInfoDTO certSubjectDn = CertUtil.getCertificateSubjectInfo(resultHolder.signingCertChain[0]);
    // Handle CN checks
    String cn = certSubjectDn.getCn().get(0).toString();

    if (!cn.equalsIgnoreCase(device.getId())) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    }

    logger.debug("Signature Verification success: certSubject=["
            + resultHolder.signingCertChain[0].getSubjectDN().toString() + "], orignialContent=["
            + new String(resultHolder.originalData) + "]");

    if (!new String(resultHolder.originalData).equalsIgnoreCase(expect)) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    }

    try {
        KeyStore trustedStore = KeyStore.getInstance("JKS");
        trustedStore.load(null, null);
        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA_2.cer")); //false CA certificate

        // byte[] certBytes = IOUtils.toByteArray(new
        // FileInputStream("RDA_RFID_CA.cer"));
        byte[] certBytes = IOUtils.toByteArray(ResourceHelper.readResource("RDA_RFID_CA.cer"));

        // valid CA certificate
        X509Certificate cert = CertUtil.getX509Certificate(certBytes);
        // may add any trusted certificate (CA or Self-signed) to the
        // keystore...
        trustedStore.setCertificateEntry(cert.getSubjectDN().getName().toString(), cert);

        verifier.isCertificateTrust(resultHolder.signingCertChain[0], trustedStore, null);

        // if trusted, do CRL verification if crl can supplied
        /*
         * if
        * (!CertUtil.verifyRevoked(ResourceHelper.readResource("crl.crl"),
        * cert)) { throw new
        * RdaException(ExceptionMessages.EXCEPTION_CERTIFICATE_IS_REVOKED);
        * }
        */

    } catch (com.iaspec.rda.rfid.server.crypto.exception.CertificateNotValidException se) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_LICENSE);
    } catch (CertificateException ce) {
        throw new RdaException(ExceptionMessages.EXCEPTION_INVALID_DECRYPTED_CHALLENGE);
    } catch (RdaException e) {
        throw new RdaException(e.getMessage());
    } catch (Exception e) {
        throw new RdaException(ExceptionMessages.EXCEPTION_SYSTEM);
    }

    logger.debug("The certificate is trusted");
}

From source file:sit.web.client.HTTPTrustHelper.java

/**
 * from//from w w w.j a  v a  2  s  . c  o m
 * http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
 *
 * @param charset
 * @param port
 * @return
 */
public static HttpClient getNewHttpClient(Charset charset, int port) {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, charset.name());

        SchemeRegistry registry = new SchemeRegistry();
        //registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, port));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.amalto.workbench.utils.SSLContextProvider.java

private static KeyManager[] buildKeyManagers(String path, String storePass, String keytype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;// ww  w  .  j av  a2s.  c  o m
    try {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(keytype);
        tks.load(stream, storePass.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        kmf.init(tks, storePass.toCharArray());

        return kmf.getKeyManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.amalto.workbench.utils.SSLContextProvider.java

private static TrustManager[] buildTrustManagers(String path, String storePass, String trusttype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;/*w w  w.ja v  a 2s  . c om*/
    try {
        if (StringUtils.isEmpty(path)) {
            return new TrustManager[] { TRUST_ALL };
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(trusttype);
        tks.load(stream, storePass.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        tmf.init(tks);

        return tmf.getTrustManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:be.fedict.eid.dss.sp.servlet.PkiServlet.java

public static KeyStore.PrivateKeyEntry getPrivateKeyEntry() throws Exception {

    LOG.debug("get SP private key entry");

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    KeyStore keyStore = KeyStore.getInstance("jks");
    InputStream keystoreStream = classLoader.getResourceAsStream("sp.jks");
    keyStore.load(keystoreStream, "secret".toCharArray());

    return (KeyStore.PrivateKeyEntry) keyStore.getEntry("sp",
            new KeyStore.PasswordProtection("secret".toCharArray()));
}

From source file:co.cask.cdap.security.tools.KeyStores.java

/**
 * Create a Java key store with a stored self-signed certificate.
 * @return Java keystore which has a self signed X.509 certificate
 *//* w  w  w  .j av a  2s  . com*/
public static KeyStore generatedCertKeyStore(SConfiguration sConf, String password) {
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM);
        SecureRandom random = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM, SECURE_RANDOM_PROVIDER);
        keyGen.initialize(KEY_SIZE, random);
        // generate a key pair
        KeyPair pair = keyGen.generateKeyPair();
        int validity = sConf.getInt(Constants.Security.SSL.CERT_VALIDITY, VALIDITY);

        X509Certificate cert = getCertificate(DISTINGUISHED_NAME, pair, validity, SIGNATURE_ALGORITHM);

        KeyStore keyStore = KeyStore.getInstance(SSL_KEYSTORE_TYPE);
        keyStore.load(null, password.toCharArray());
        keyStore.setKeyEntry(CERT_ALIAS, pair.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[] { cert });
        return keyStore;
    } catch (Exception e) {
        throw new RuntimeException(
                "SSL is enabled but a key store file could not be created. A keystore is required "
                        + "for SSL to be used.",
                e);
    }
}

From source file:com.openmeap.util.SSLUtils.java

public static KeyStore loadKeyStore(InputStream keyStoreStream, String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(keyStoreStream, password.toCharArray());
    return ks;//from w ww .jav  a 2  s  . c  o  m
}

From source file:org.xacml4j.saml.XACMLAuthzDecisionQueryEndpointTest.java

private static KeyStore getKeyStore(String ksType, String resource, String ksPwd) throws Exception {
    InputStream is = null;//from  w w  w.  j av  a 2 s  . c o m
    try {
        is = XACMLAuthzDecisionQueryEndpointTest.class.getResourceAsStream(resource);
        KeyStore ks = KeyStore.getInstance(ksType);
        ks.load(is, ksPwd.toCharArray());
        return ks;
    } finally {
        Closeables.closeQuietly(is);
    }
}

From source file:com.hy.utils.pay.wx.ClientCustomSSL.java

public static void test() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("D:/10016225.p12"));
    try {//from  w w  w.j a v a  2s.  c om
        keyStore.load(instream, "10016225".toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpGet httpget = new HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");

        System.out.println("executing request" + httpget.getRequestLine());

        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}