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.springcryptoutils.core.cipher.symmetric.KeyGeneratorImpl.java

public void afterPropertiesSet() throws NoSuchAlgorithmException, NoSuchProviderException {
    if ((provider == null) || (provider.length() == 0)) {
        generator = javax.crypto.KeyGenerator.getInstance(algorithm);
    } else {//w ww . j  a va 2  s.co  m
        generator = javax.crypto.KeyGenerator.getInstance(algorithm, provider);
    }
    generator.init(new SecureRandom());
}

From source file:org.apache.falcon.resource.channel.SecureHTTPChannel.java

@Override
protected Client getClient() throws Exception {
    Properties properties = StartupProperties.get();
    String keyStoreFile = properties.getProperty("keystore.file", "conf/prism.keystore");
    String password = properties.getProperty("keystore.password", "falcon-prism-passwd");
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(// ww w. j a v a  2 s  . c  o m
            new KeyManager[] { KeyManagerUtils.createClientKeyManager(new File(keyStoreFile), password) },
            new TrustManager[] { TrustManagerUtils.getValidateServerCertificateTrustManager() },
            new SecureRandom());
    DefaultClientConfig config = new DefaultClientConfig();
    config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
            new HTTPSProperties(new AllowAllHostnameVerifier(), sslContext));
    LOG.info("Configuring client with " + new File(keyStoreFile).getAbsolutePath());
    return Client.create(config);
}

From source file:info.fcrp.keepitsafe.bean.UserBeanTest.java

private String generatePublicKey() throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PublicKey pubKey = kp.getPublic();

    return Base64.encodeBase64String(pubKey.getEncoded());
}

From source file:fi.vm.kapa.identification.adapter.utils.AuthenticationHandlerUtils.java

public String createToken() {
    return new BigInteger(64, new SecureRandom()).toString(16);
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Creates a {@link OkHttpClient} to start a TLS connection.
 *
 * @param cookies list of cookies to include in the client.
 * @return new http client./*from w ww.j av  a2  s  .  c om*/
 */
public static OkHttpClient sslOkHttpClient(List<HttpCookie> cookies) {
    checkNotNull(cookies);

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }

    SSLSocketFactory socketFactory = sslContext.getSocketFactory();

    OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory)
            .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false);

    client.setRetryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookies.forEach(c -> cookieManager.getCookieStore().add(null, c));
    client.setCookieHandler(cookieManager);
    return client;
}

From source file:ldap.ActiveLoginImpl.java

public ActiveLoginImpl() {
    random = new SecureRandom();
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey priKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();

    Cipher c = Cipher.getInstance("RSA");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, pubKey);
    c.update(plainBytes);//from   w ww  . j  av  a2 s  .com

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, priKey);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:com.pingidentity.adapters.idp.mobileid.restservice.MssRequestHandlerRest.java

/**
 * Creates a random transaction id beginning with 'pf'
 * //from w ww  .j av  a 2s  .  co  m
 * @param digits
 *            number of digits without 'pf'
 * @return the generated transaction id
 */
public static String createTransId(int digits) {

    final String VALUES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    SecureRandom rand = new SecureRandom();
    rand.setSeed(System.currentTimeMillis());
    StringBuffer randBuffer = new StringBuffer("pf");
    for (int i = 0; i < digits; i++) {
        randBuffer.append(VALUES.charAt(rand.nextInt(VALUES.length())));
    }
    return randBuffer.toString();
}

From source file:com.allstate.client.ssl.SSLUtils.java

public static SSLSocketFactory getMergedSocketFactory(Security securityOne, Security securityTwo)
        throws GeneralSecurityException {
    X509KeyManager keyManagerOne = getKeyManager(securityOne.getKeyStore(), securityOne.getKeyStorePassword());
    X509KeyManager keyManagerTwo = getKeyManager(securityTwo.getKeyStore(), securityTwo.getKeyStorePassword());

    X509TrustManager trustManager = getMultiTrustManager(getTrustManager(securityOne.getTrustStore()),
            getTrustManager(securityTwo.getTrustStore()));

    SSLContext context = SSLContext.getInstance(securityOne.getSslContextProtocol());
    boolean strictHostVerification = securityOne.isStrictHostVerification()
            && securityTwo.isStrictHostVerification();

    context.init(new KeyManager[] { keyManagerOne, keyManagerTwo }, new TrustManager[] { trustManager },
            new SecureRandom());
    X509HostnameVerifier verifier = strictHostVerification ? SSLSocketFactory.STRICT_HOSTNAME_VERIFIER
            : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    return new SSLSocketFactory(context, verifier);
}

From source file:org.mifos.module.sms.provider.RestAdapterProvider.java

@SuppressWarnings("unused")
public OkHttpClient createClient() {

    final OkHttpClient client = new OkHttpClient();

    final TrustManager[] certs = new TrustManager[] { new X509TrustManager() {

        @Override/*from w  w  w .j ava2  s.c o m*/
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
        }
    } };

    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (final java.security.GeneralSecurityException ex) {
    }

    try {
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession session) {
                return true;
            }
        };
        client.setHostnameVerifier(hostnameVerifier);
        client.setSslSocketFactory(ctx.getSocketFactory());
    } catch (final Exception e) {
    }

    return client;
}