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:grails.plugin.springsecurity.authentication.encoding.PBKDF2PasswordEncoder.java

public String encodePassword(String rawPass, Object saltIgnored) {
    char[] password = rawPass.toCharArray();

    // Generate a random salt
    byte[] salt = new byte[SALT_BYTE_SIZE];
    new SecureRandom().nextBytes(salt);

    // Hash the password
    byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);

    // format iterations:salt:hash
    return PBKDF2_ITERATIONS + ":" + toHex(salt) + ":" + toHex(hash);
}

From source file:com.whynot.checkOtrade.web.ws.LoginController.java

/**
 *     ?, ?  //from w ww.  j a  v a 2 s.c o  m
 * ?? ?? - ? 
 *  ?     -,
 *  ?  .
 * @param data
 * @return
 */
@RequestMapping(value = "rest/login", method = RequestMethod.POST)
public @ResponseBody String login(LoginData data) {
    String response = "null";
    System.out.println(data.getLogin() + " :: " + data.getPassword());
    Account acc = us.findByEmail(data.getLogin());
    System.out.println("acc :: " + acc);
    if (acc == null) {
        return response;
    }
    System.out.println("acc :: " + acc);
    if (acc.getPassword().equals(data.getPassword())) {
        SecureRandom random = new SecureRandom();
        response = new BigInteger(130, random).toString(32);
    }
    usermap.put(response, acc);
    return response;
}

From source file:com.villemos.ispace.httpcrawler.HttpClientConfigurer.java

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;//from   www  . j  a v  a2  s.  co m

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {
        client = new DefaultHttpClient();
    }

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:LoginAcceptanceTests.java

@Before
public void setUp() throws Exception {
    int randomInt = new SecureRandom().nextInt();

    adminClientToken = testClient.getOAuthAccessToken(adminClientId, adminClientSecret, "client_credentials",
            "clients.write");

    scimClientId = "acceptance-scim-" + randomInt;
    testClient.createScimClient(adminClientToken, scimClientId);

    scimClientToken = testClient.getOAuthAccessToken(scimClientId, "scimsecret", "client_credentials",
            "scim.read,scim.write");

    userName = "acceptance-" + randomInt + "@example.com";
    testClient.createUser(scimClientToken, userName, userName, "password", true);

    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.akita.io._FakeSSLSocketFactory.java

private _FakeSSLSocketFactory() {
    super();/*from   www .ja  va 2 s.c  o  m*/
    TrustManager[] tm = new TrustManager[] { new _FakeX509TrustManager() };
    try {
        this.sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
        this.sslcontext.init(null, tm, new SecureRandom());
        this.socketfactory = this.sslcontext.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
    } catch (KeyManagementException e) {
    }
}

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

@Before
public void setUp() throws IOException {
    Random random = new SecureRandom();
    random.nextBytes(key);
    random.nextBytes(iv);
}

From source file:com.wudaosoft.net.httpclient.SSLContextBuilder.java

public SSLContext buildPKCS12() {

    Args.notEmpty(password, "password");
    Args.notNull(cert, "cert");

    char[] pwd = password.toCharArray();

    try {/*from  www  .j av  a 2  s.  c  o  m*/
        KeyStore ks = KeyStore.getInstance("PKCS12");

        ks.load(cert.openStream(), pwd);

        //  & ?
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, pwd);

        //  SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());

        return sslContext;
    } catch (Exception e) {
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        throw new RuntimeException(e);
    }
}

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

public JceAesCtrCryptoCodec() {
    provider = CryptoStreamUtils.getJCEProvider();
    final String secureRandomAlg = CryptoStreamUtils.getSecureRandomAlg();
    try {//  ww w  . j  a v  a2s  .c  o m
        random = (provider != null) ? SecureRandom.getInstance(secureRandomAlg, provider)
                : SecureRandom.getInstance(secureRandomAlg);
    } catch (GeneralSecurityException e) {
        LOG.warn(e.getMessage());
        random = new SecureRandom();
    }
}

From source file:edu.vt.middleware.crypt.digest.DigestAlgorithmTest.java

/** @return  Test data. */
@DataProvider(name = "testdata")
public Object[][] createTestData() {
    final SecureRandom secrnd = new SecureRandom();
    final MD2 md2 = new MD2();
    md2.setRandomProvider(secrnd);//from  ww w .j a v a2 s  .co  m

    final MD4 md4 = new MD4();
    md4.setRandomProvider(secrnd);

    final MD5 md5 = new MD5();
    md5.setRandomProvider(secrnd);

    final RipeMD128 ripeMD128 = new RipeMD128();
    ripeMD128.setRandomProvider(secrnd);

    final RipeMD160 ripeMD160 = new RipeMD160();
    ripeMD160.setRandomProvider(secrnd);

    final RipeMD256 ripeMD256 = new RipeMD256();
    ripeMD256.setRandomProvider(secrnd);

    final RipeMD320 ripeMD320 = new RipeMD320();
    ripeMD320.setRandomProvider(secrnd);

    final SHA1 sha1 = new SHA1();
    sha1.setRandomProvider(secrnd);

    final SHA256 sha256 = new SHA256();
    sha256.setRandomProvider(secrnd);

    final SHA384 sha384 = new SHA384();
    sha384.setRandomProvider(secrnd);

    final SHA512 sha512 = new SHA512();
    sha512.setRandomProvider(secrnd);

    final Tiger tiger = new Tiger();
    tiger.setRandomProvider(secrnd);

    final Whirlpool whirlpool = new Whirlpool();
    whirlpool.setRandomProvider(secrnd);

    return new Object[][] { { md2, null }, { md2, md2.getRandomSalt() }, { md4, null },
            { md4, md4.getRandomSalt() }, { md5, null }, { md5, md5.getRandomSalt() }, { ripeMD128, null },
            { ripeMD128, ripeMD128.getRandomSalt() }, { ripeMD160, null },
            { ripeMD160, ripeMD160.getRandomSalt() }, { ripeMD256, null },
            { ripeMD256, ripeMD256.getRandomSalt() }, { ripeMD320, null },
            { ripeMD320, ripeMD320.getRandomSalt() }, { sha1, null }, { sha1, sha1.getRandomSalt() },
            { sha256, null }, { sha256, sha256.getRandomSalt() }, { sha384, null },
            { sha384, sha384.getRandomSalt() }, { sha512, null }, { sha512, sha512.getRandomSalt() },
            { tiger, null }, { tiger, tiger.getRandomSalt() }, { whirlpool, null },
            { whirlpool, whirlpool.getRandomSalt() }, };
}

From source file:com.linkedin.pinot.monitor.util.HttpUtils.java

/**
 * {//from  w w  w  . jav a  2  s  .  co  m
 text: "",
 attachments: [{
 title: "",
 description: "??",
 url: "",
 color: "warning|info|primary|error|muted|success"
 }]
 displayUser: {
 name: "??",
 avatarUrl: "??"
 }
 }
 * @param text
 * @return
 */

public static void postMonitorData(String text) {
    SSLContext sslContext = null;
    HttpClient client = new DefaultHttpClient();
    try {
        sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSLSocketFactory ssf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = client.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", 443, ssf));

    HttpPost httpPost = new HttpPost("https://hooks.pubu.im/services/1d2d2rwn8wb6sx");

    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, String> sender = new HashMap<String, String>();
    sender.put("name", "Monitor");
    map.put("displayUser", sender);
    List<String> list = new ArrayList<String>();
    map.put("attachments", list);

    try {
        map.put("text", text);
        InputStreamEntity httpentity = new InputStreamEntity(
                new ByteArrayInputStream(mapper.writeValueAsBytes(map)), mapper.writeValueAsBytes(map).length);
        httpPost.setEntity(httpentity);
        httpPost.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //
    }

}