Example usage for java.security SecureRandom SecureRandom

List of usage examples for java.security SecureRandom SecureRandom

Introduction

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

Prototype

public SecureRandom() 

Source Link

Document

Constructs a secure random number generator (RNG) implementing the default random number algorithm.

Usage

From source file:com.fujitsu.dc.test.jersey.HttpClientFactory.java

/**
 * SSLSocket?./*from w w w . j  ava 2s. co  m*/
 * @return ???SSLSocket
 */
private static SSLSocketFactory createInsecureSSLSocketFactory() {
    // CHECKSTYLE:OFF
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }

    try {
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                // System.out.println("getAcceptedIssuers =============");
                X509Certificate[] ret = new X509Certificate[0];
                return ret;
            }

            public final void checkClientTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkClientTrusted =============");
            }

            public final void checkServerTrusted(final X509Certificate[] certs, final String authType) {
                // System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (KeyManagementException e1) {
        throw new RuntimeException(e1);
    }
    // CHECKSTYLE:ON

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
    // socketFactory.setHostnameVerifier((X509HostnameVerifier)
    // hostnameVerifier);

    return socketFactory;
}

From source file:com.base.net.volley.toolbox.HurlStack.java

private SSLSocketFactory getDefaultSSLSocketFactory() {
    SSLSocketFactory mySSLSocketFactory = null;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from w  ww  .j  av  a 2s  .  com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        mySSLSocketFactory = sc.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return mySSLSocketFactory;
}

From source file:com.intel.cryptostream.CryptoCodecTest.java

private void cryptoCodecTest(int count, String encCodecClass, String decCodecClass, byte[] iv)
        throws IOException, GeneralSecurityException {
    CryptoCodec encCodec = null;//from  w w w.jav a2 s .  com
    try {
        encCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(encCodecClass));
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto codec!");
    }
    LOG.info("Created a Codec object of type: " + encCodecClass);

    // Generate data
    SecureRandom random = new SecureRandom();
    byte[] originalData = new byte[count];
    byte[] decryptedData = new byte[count];
    random.nextBytes(originalData);
    LOG.info("Generated " + count + " records");

    // Encrypt data
    ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
    CryptoOutputStream out = new CryptoOutputStream(encryptedData, encCodec, bufferSize, key, iv);
    out.write(originalData, 0, originalData.length);
    out.flush();
    out.close();
    LOG.info("Finished encrypting data");

    CryptoCodec decCodec = null;
    try {
        decCodec = (CryptoCodec) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(decCodecClass));
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto codec!");
    }
    LOG.info("Created a Codec object of type: " + decCodecClass);

    // Decrypt data
    CryptoInputStream in = new CryptoInputStream(new ByteArrayInputStream(encryptedData.toByteArray()),
            decCodec, bufferSize, key, iv);

    // Check
    int remainingToRead = count;
    int offset = 0;
    while (remainingToRead > 0) {
        int n = in.read(decryptedData, offset, decryptedData.length - offset);
        if (n >= 0) {
            remainingToRead -= n;
            offset += n;
        }
    }

    Assert.assertArrayEquals("originalData and decryptedData not equal", originalData, decryptedData);

    LOG.info("SUCCESS! Completed checking " + count + " records");
}

From source file:org.couchpotato.CouchPotato.java

private CouchPotato(String scheme, String hostname, int port, String path, String api, String username,
        String password, boolean trustAll, String trustMe) {
    this.scheme = scheme;
    this.hostName = hostname;
    this.port = port;
    this.path = path;
    this.api = api;
    this.username = username;
    this.password = password;
    this.trustAll = trustAll;

    if (this.username == null)
        this.username = "";
    if (this.password == null)
        this.password = "";

    // Configure SSL behavior based on user preferences
    Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
    HostnameVerifier verifier;/*from ww  w.j  a  v  a 2s . c om*/
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager(trustAll, trustMe) },
                new SecureRandom());
        if (trustAll) {
            verifier = new AllowAllHostnameVerifier();
        } else {
            verifier = new StrictHostnameVerifier();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    } catch (NoSuchAlgorithmException e) {

    } catch (KeyManagementException e) {

    } catch (KeyStoreException e) {

    }
}

From source file:co.cask.cdap.security.server.ExternalMTLSAuthenticationServerTestBase.java

private HttpClient getHTTPClient(KeyManager[] kms, TrustManager[] tms) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(kms, tms, new SecureRandom());
    // only for test purposes ignoring check of certificate hostname matching host on which server runs
    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", getAuthServerPort(), sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    // Apache HttpClient version >4.2 should use BasicClientConnectionManager
    ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
    return new DefaultHttpClient(cm);
}

From source file:com.frostwire.http.HttpClient.java

private static SSLSocketFactory buildSSLSocketFactory() {
    try {//from  w ww  .  j av  a 2 s  .c o m
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, new TrustManager[] { new AllX509TrustManager() }, new SecureRandom());
        SSLSocketFactory d = sc.getSocketFactory();
        return new WrapSSLSocketFactory(d);
    } catch (Throwable e) {
        LOG.error("Unable to create custom SSL socket factory", e);
    }

    return null;
}

From source file:org.apache.cloudstack.storage.datastore.util.NexentaNmsClient.java

protected DefaultHttpClient getHttpsClient() {
    try {/* w  ww  .ja  v a  2 s  .  c  o m*/
        SSLContext sslContext = SSLUtils.getSSLContext();
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sslContext.init(null, new TrustManager[] { tm }, new SecureRandom());

        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();

        registry.register(new Scheme("https", nmsUrl.getPort(), socketFactory));

        BasicClientConnectionManager mgr = new BasicClientConnectionManager(registry);

        return new DefaultHttpClient(mgr);
    } catch (NoSuchAlgorithmException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    } catch (KeyManagementException ex) {
        throw new CloudRuntimeException(ex.getMessage());
    }
}

From source file:com.farmafene.commons.cas.HttpClientFactory.java

public DefaultHttpClient getClient() throws IllegalArgumentException {
    DefaultHttpClient httpClient = null;
    URL u = null;/*w w w.j  a v  a2 s .c  om*/
    try {
        u = new URL(loginURL.toLowerCase());
    } catch (MalformedURLException e) {
        IllegalArgumentException ex = new IllegalArgumentException("Error", e);
        logger.error("Excepcion en el login", ex);
        throw ex;
    }
    if ("https".equals(u.getProtocol())) {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, new TrustManager[] { this }, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            IllegalArgumentException ex = new IllegalArgumentException("Error", e);
            logger.error("Excepcion en el login", ex);
            throw ex;
        } catch (KeyManagementException e) {
            IllegalArgumentException ex = new IllegalArgumentException("Error", e);
            logger.error("Excepcion en el login", ex);
            throw ex;
        }
        SSLSocketFactory sf = new SSLSocketFactory(sslContext, this);
        Scheme httpsScheme = new Scheme("https", u.getPort() == -1 ? HTTPS_DEFAULT_PORT : u.getPort(), sf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        Scheme httpScheme = new Scheme("http", HTTP_DEFAULT_PORT, new PlainSocketFactory());
        schemeRegistry.register(httpScheme);

        ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
        httpClient = new DefaultHttpClient(cm);
    } else {
        httpClient = new DefaultHttpClient();
    }
    if (null != proxyHost) {
        if (logger.isDebugEnabled()) {
            logger.debug("Existe proxy: " + this);
        }
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    return httpClient;
}

From source file:ee.ria.xroad.proxy.testsuite.DummyService.java

private ServerConnector createSslConnector() throws Exception {
    PKCS12 consumer = TestCertUtil.getConsumer();
    serverCert = consumer.cert;//  w w  w .  j a  v  a2 s  .c o  m
    serverKey = consumer.key;

    SslContextFactory cf = new SslContextFactory(false);
    cf.setNeedClientAuth(true);

    cf.setIncludeCipherSuites(CryptoUtils.getINCLUDED_CIPHER_SUITES());
    cf.setSessionCachingEnabled(true);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(new KeyManager[] { new DummyServiceKeyManager() },
            new TrustManager[] { new DummyServiceTrustManager() }, new SecureRandom());

    cf.setSslContext(ctx);

    return new ServerConnector(this, cf);
}

From source file:ai.serotonin.backup.Backup.java

private File encryptFile(final File file) throws Exception {
    final SecureRandom random = new SecureRandom();
    final byte[] salt = random.generateSeed(8);
    final String saltStr = Hex.encodeHexString(salt);

    final SecretKey secret = createSecretKey(salt);

    final Cipher cipher = createCipher();
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    final AlgorithmParameters params = cipher.getParameters();
    final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
    final String ivStr = Hex.encodeHexString(iv);

    final File encryptedFile = new File(file.getParent(), saltStr + "_" + ivStr + "_" + file.getName());

    cipherizeFile(file, encryptedFile, cipher);

    file.delete();// ww w.j  av  a2  s . com

    LOG.info("Encrypted backup file to " + encryptedFile.getPath() + ", "
            + FileUtils.byteCountToDisplaySize(encryptedFile.length()));
    return encryptedFile;
}