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:au.edu.monash.merc.capture.util.httpclient.ssl.EasySSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {/*  w  w w .j  ava 2 s.com*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { (TrustManager) new EasyX509TrustManager(null) },
                new SecureRandom());
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}

From source file:com.ephesoft.dcma.batch.service.EphesoftSSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {/*from   ww w  . ja v a2 s  . c om*/
        final SSLContext context = SSLContext.getInstance("SSL");
        context.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        return context;
    } catch (final Exception exception) {
        LOGGER.error(exception.getMessage(), exception);
        throw new HttpClientError(exception.toString());
    }
}

From source file:dk.netarkivet.harvester.harvesting.MetadataFileWriterTester.java

public void testMetadataFileWriterWarc() {
    File metafile = new File("metadata.warc");
    MetadataFileWriter mdfw = MetadataFileWriterWarc.createWriter(metafile);

    String uri = "http://www.netarkivet.dk/";
    long ctm = System.currentTimeMillis();

    SecureRandom random = new SecureRandom();
    byte[] payload = new byte[8192];
    random.nextBytes(payload);//from   www. j a v a2  s  .com

    try {
        mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload);
        mdfw.close();
    } catch (IOException e) {
        e.printStackTrace();
        Assert.fail("Unexpected exception!");
    }

    metafile.deleteOnExit();

    File metadataArcFile = new File(TestInfo.WORKING_DIR, "42-metadata-1.warc");
    MetadataFileWriter mfwa = MetadataFileWriterWarc.createWriter(metadataArcFile);
    ((MetadataFileWriterWarc) mfwa).insertInfoRecord(new ANVLRecord());
    for (File f : logsDir.listFiles()) {
        mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain");
    }
}

From source file:it.zero11.acme.Acme.java

private static SSLContext getTrustAllCertificateSSLContext()
        throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override// ww w . j a v a2 s . com
        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

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

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

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    return sc;
}

From source file:org.opencastproject.kernel.http.impl.HttpClientImpl.java

/**
 * Creates a new client that can deal with all kinds of oddities with regards to http/https connections.
 * /*from  w  w w.  j a  va  2  s.c o  m*/
 * @return the client
 */
private DefaultHttpClient makeHttpClient() {

    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    try {
        logger.debug("Installing forgiving hostname verifier and trust managers");
        X509TrustManager trustManager = createTrustManager();
        X509HostnameVerifier hostNameVerifier = createHostNameVerifier();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());
        SSLSocketFactory ssf = new SSLSocketFactory(sslContext, hostNameVerifier);
        ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", 443, ssf));
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    } catch (KeyManagementException e) {
        logger.error("Error creating context to handle TLS connections: {}", e.getMessage());
    }

    return defaultHttpClient;
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 *///from w  w w .ja va2s .c  o m
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.EasyIgnoreSSLProtocolSocketFactory.java

private static SSLContext createEasySSLContext() {
    try {/* w w w . jav a2s.c o  m*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { (TrustManager) new DefaultEasyX509TrustManager() },
                new SecureRandom());
        return context;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        throw new HttpClientError(e.toString());
    }
}

From source file:ch.fihlon.moodini.business.token.control.TokenService.java

private Challenge generateChallenge() {
    final int requiredLength = currentlyRequiredChallengeLength();
    final StringBuilder challengeBuilder = new StringBuilder(requiredLength);
    final Random random = new SecureRandom();
    while (challengeBuilder.length() < requiredLength) {
        final char randomChar = CHALLENGE_CHARACTERS.charAt(random.nextInt(CHALLENGE_CHARACTERS.length()));
        challengeBuilder.append(randomChar);
    }/*from  ww  w  . ja  v  a2 s .  co m*/
    return new Challenge(challengeBuilder.toString());
}

From source file:org.xdi.net.SslDefaultHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {/*from  w  w w  .jav  a  2  s.  co  m*/
        TrustManager[] trustManagers = this.trustManagers;
        if (useTrustManager) {
            trustManagers = getTrustManagers();
        }

        KeyManager[] keyManagers = null;
        if (useKeyManager) {
            keyManagers = getKeyManagers();
        }

        SSLContext ctx = SSLContext.getInstance("TLS");

        ctx.init(keyManagers, trustManagers, new SecureRandom());

        // Pass the keystore to the SSLSocketFactory
        SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        return sf;
    } catch (Exception ex) {
        throw new IllegalArgumentException("Failed to load keystore", ex);
    }

}

From source file:com.hellblazer.jackal.configuration.GossipHeartbeatAndDiscoveryConfig.java

@Bean
@Primary//from ww  w. j av  a  2 s.c  o  m
public Gossip gossip() throws IOException {
    return new Gossip(systemView(), new SecureRandom(), communications(), gossipConfiguration.interval,
            gossipConfiguration.unit, failureDetectorFactory, partitionIdentity);
}