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:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

private void trustAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = { new X509TrustManager() {
        @Override//from   w ww.  j  a va2  s.co m
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(final X509Certificate[] certs, final String authType) {
            //
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] certs, final String authType) {
            //
        }
    } };
    final SSLContext sc = SSLContext.getInstance("SSL");
    final HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(final String arg0, final SSLSession arg1) {
            return true;
        }
    };
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hv);
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.OverviewServlet.java

public OverviewServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.serverList = new ServerList(settingsFactory);
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);/*  w w  w.j ava 2  s.c  o m*/
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));
}

From source file:com.orange.cloud.servicebroker.filter.core.IntegrationTestConfiguration.java

@Bean
SecureRandom random() {
    return new SecureRandom();
}

From source file:com.ntsync.android.sync.client.ClientKeyHelper.java

/**
 * /*from w ww . ja  va 2  s  .co m*/
 * Get Private Key or create a new one.
 * 
 * @param account
 *            the account we're syncing
 * @return Private Key
 * @throws InvalidKeyException
 */
@SuppressLint("TrulyRandom")
public static SecretKey getOrCreatePrivateKey(Account account, AccountManager accountManager)
        throws IOException, InvalidKeyException {
    SecretKey key = getPrivateKey(account, accountManager);
    if (key == null) {
        Log.i(TAG, "Create new private Key");

        String pwd = PasswortGenerator.createPwd(PWD_WORD_LEN);

        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[SALT_LENGHT];
        random.nextBytes(salt);

        key = createKey(account, accountManager, pwd, salt, false, null);
    }
    return key;
}

From source file:com.mde.potdroid.helpers.WebsiteInteraction.java

public Boolean login(String password) throws Exception {

    // first, create new user agent
    // and recreate the httpclient
    SecureRandom random = new SecureRandom();
    String uAgent = new BigInteger(50, random).toString(32);
    SharedPreferences.Editor editor = mSettings.edit();
    editor.putString("unique_uagent", uAgent);
    editor.commit();//from w w  w . j a  va2  s  . co  m
    mHttpClient = new DefaultHttpClient();
    mHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Apache-HttpClient/potdroid " + mSettings.getString("unique_uagent", "potdroid"));

    // add login data
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    String username = mSettings.getString("user_name", "");
    if (username.equals("") || password.equals("")) {
        return false;
    }
    nvps.add(new BasicNameValuePair("login_username", username));
    nvps.add(new BasicNameValuePair("login_password", password));
    nvps.add(new BasicNameValuePair("login_lifetime", PotUtils.COOKIE_LIFETIME));

    // create the request
    HttpPost httpost = new HttpPost(PotUtils.LOGIN_URL);
    httpost.setEntity(new UrlEncodedFormEntity(nvps, PotUtils.DEFAULT_ENCODING));

    // execute the form
    HttpResponse response = mHttpClient.execute(httpost);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), PotUtils.DEFAULT_ENCODING));

    // fetch the result of the http request and save it as a string
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    String input = sb.toString();

    // check if the login worked, e.g. one was redirected to SSO.php..
    Pattern pattern = Pattern.compile("http://forum.mods.de/SSO.php\\?UID=([0-9]+)[^']*");
    Matcher m = pattern.matcher(input);

    if (m.find()) {
        // set user id
        editor.putInt("user_id", Integer.valueOf(m.group(1)));
        editor.commit();

        // url for the setcookie found, send a request
        HttpGet cookieUrl = new HttpGet(m.group(0));

        mHttpClient.execute(cookieUrl);

        // store cookie data
        List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("MDESID")) {
                editor.putString("cookie_name", cookie.getName());
                editor.putString("cookie_value", cookie.getValue());
                editor.putString("cookie_url", cookie.getDomain());
                editor.putString("cookie_path", cookie.getPath());
                editor.commit();
            }
        }
        return true;
    }

    return false;
}

From source file:de.codecentric.jira.jenkins.plugin.servlet.RecentBuildsServlet.java

public RecentBuildsServlet(TemplateRenderer templateRenderer, JiraAuthenticationContext authenticationContext,
        PluginSettingsFactory settingsFactory, ApplicationProperties applicationProperties) {
    this.templateRenderer = templateRenderer;
    this.authenticationContext = authenticationContext;
    this.client = new HttpClient(new MultiThreadedHttpConnectionManager());
    this.serverList = new ServerList(settingsFactory);

    //test if jiraversion < 4.3
    IsPriorToJiraVersion isPrior = new IsPriorToJiraVersion(applicationProperties);
    isPrior.setmaxMajorVersion(4);//from ww w  . j  av a 2 s. c o  m
    isPrior.setmaxMinorVersion(3);
    this.old = isPrior.shouldDisplay(null);

    client.getParams().setAuthenticationPreemptive(true);

    //set SSLContext to accept all certificates
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SecureProtocolSocketFactory secureProtocolSocketFactory = new SSLProtocolSocketFactory();

    Protocol.registerProtocol("https",
            new Protocol("https", (ProtocolSocketFactory) secureProtocolSocketFactory, 443));

}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created
 * along with the initialization vectory. The member variable vEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk.//from  www  .j ava  2  s  . c om
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    vSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(vSalt);
    Db("generated salt :" + Hex.encodeHexString(vSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* Derive the key, given password and salt.
     *
     * in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
     * The end user must also install them (not compiled in) so beware.
     * see here:  http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
     */
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = vEcipher.getParameters();

    // get the initialization vectory and store as member var
    vInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("vInitVec is :" + Hex.encodeHexString(vInitVec));
}

From source file:ee.ria.xroad.proxy.serverproxy.HttpClientCreator.java

private static SSLConnectionSocketFactory createSSLSocketFactory() throws Exception {
    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(createServiceKeyManager(), new TrustManager[] { new ServiceTrustManager() }, new SecureRandom());

    log.info("SSL context successfully created");

    return new CustomSSLSocketFactory(ctx, SystemProperties.getProxyClientTLSProtocols(),
            SystemProperties.getProxyClientTLSCipherSuites(), NoopHostnameVerifier.INSTANCE);
}

From source file:com.pipinan.githubcrawler.GithubCrawler.java

/**
 * Just to avoid the ssl exception when using HttpClient to access https url
 *
 * @return/*from  ww  w. j a va  2  s. c o  m*/
 */
private HttpClient getHttpClient() {
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

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

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        e.printStackTrace();
        return HttpClientBuilder.create().build();
    }
}

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

private static SSLConnectionSocketFactory createSSLSocketFactory(InternalSSLKey authKey) throws Exception {
    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(getKeyManager(authKey), new TrustManager[] { new OpMonitorTrustManager() }, new SecureRandom());

    return new SSLConnectionSocketFactory(ctx.getSocketFactory(), new String[] { CryptoUtils.SSL_PROTOCOL },
            CryptoUtils.getINCLUDED_CIPHER_SUITES(), NoopHostnameVerifier.INSTANCE);
    // We don't need hostname verification
}