List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:wsattacker.plugin.intelligentdos.requestSender.Http4RequestSenderImpl.java
private SSLSocketFactory get() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllManager() }; // Install the all-trusting trust manager try {//from ww w .ja va 2s.c o m SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); return new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (RuntimeException e) { ; } catch (Exception e) { ; } return null; }
From source file:SandBox.testing.PageFetcher.java
public PageFetcher(CrawlConfig config) { super(config); HttpParams params = new BasicHttpParams(); HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); paramsBean.setVersion(HttpVersion.HTTP_1_1); paramsBean.setContentCharset("UTF-8"); paramsBean.setUseExpectContinue(false); params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString()); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout()); params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout()); params.setBooleanParameter("http.protocol.handle-redirects", false); SSLContext sslContext = null; try {// w ww.j a v a 2 s . c o m sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); //SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); if (config.isIncludeHttpsPages()) { schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); } connectionManager = new PoolingClientConnectionManager(schemeRegistry); connectionManager.setMaxTotal(config.getMaxTotalConnections()); connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost()); httpClient = new DefaultHttpClient(connectionManager, params); if (config.getProxyHost() != null) { if (config.getProxyUsername() != null) { httpClient.getCredentialsProvider().setCredentials( new AuthScope(config.getProxyHost(), config.getProxyPort()), new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword())); } HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort()); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { HeaderElement[] codecs = contentEncoding.getElements(); for (HeaderElement codec : codecs) { if (codec.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); if (connectionMonitorThread == null) { connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager); } connectionMonitorThread.start(); }
From source file:org.gc.googleAnalytics.AuthHelper.java
/** * Generates a secure state token./*from ww w.j a va2s.c o m*/ */ private void generateStateToken() { SecureRandom sr1 = new SecureRandom(); stateToken = "google;" + sr1.nextInt(); }
From source file:org.cloudfoundry.identity.uaa.login.feature.LoginIT.java
private String createUnverifiedUser() throws Exception { int randomInt = new SecureRandom().nextInt(); String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials", "clients.read clients.write clients.secret"); String scimClientId = "scim" + randomInt; testClient.createScimClient(adminAccessToken, scimClientId); String scimAccessToken = testClient.getOAuthAccessToken(scimClientId, "scimsecret", "client_credentials", "scim.read scim.write password.write"); String userEmail = "user" + randomInt + "@example.com"; testClient.createUser(scimAccessToken, userEmail, userEmail, "secret", false); return userEmail; }
From source file:com.muk.services.commerce.CryptoServiceImpl.java
@PostConstruct public void postConstruct() { try {/*from w w w . j a va2 s. c o m*/ final KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); temporaryKey = new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"); final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); final byte[] iv = new byte[cipher.getBlockSize()]; new SecureRandom().nextBytes(iv); ivSpec = new IvParameterSpec(iv); } catch (final NoSuchAlgorithmException ex) { LOG.error("Failed to initalize encryption key", ex); } catch (final NoSuchPaddingException padEx) { LOG.error("Failed to get cipher.", padEx); } }
From source file:com.shenit.commons.codec.DesUtils.java
/** * /* w w w. j a v a 2 s . c o m*/ * @param rawData * @param rawKey * @param mode */ private static byte[] crypt(byte[] rawData, KeySpec keySpec, int mode) { // ?DESKeySpec byte[] result = null; try { // ?DESKeySpec??SecretKey SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CODEC_DES); Key key = keyFactory.generateSecret(keySpec); if (key == null) { if (LOG.isWarnEnabled()) LOG.warn("[crypt] No key generated!"); return null; } // Cipher?? Cipher cipher = Cipher.getInstance(CODEC_DES); // DES???? cipher.init(mode, key, new SecureRandom()); // ?? // ?? result = cipher.doFinal(rawData); } catch (Exception ex) { LOG.warn("[crypt] crypt with exceptions", ex); } return result; }
From source file:com.predic8.membrane.balancer.client.LBNotificationClient.java
private String getQueryString() { String time = String.valueOf(System.currentTimeMillis()); return "balancer=" + balancer + "&cluster=" + cluster + "&host=" + host + "&port=" + port + "&time=" + time + "&nonce=" + new SecureRandom().nextLong(); }
From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java
private void sendHttpMessage() { if (mIsBitmap) { Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url); if (bitmap != null) { events.onHttpComplete(bitmap); return; }//from www. ja v a2s . c om } X509TrustManager trustManager = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE : This is where we can calculate the certificate's fingerprint, // show it to the user and throw an exception in case he doesn't like it } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } }; //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier()); // Create a trust manager that does not validate certificate chains X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager }; // Install the all-trusting trust manager SSLSocketFactory noSSLv3Factory = null; try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom()); } else { noSSLv3Factory = sc.getSocketFactory(); } HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory); } catch (GeneralSecurityException e) { } HttpsURLConnection connection = null; try { URL urlObj = new URL(url); connection = (HttpsURLConnection) urlObj.openConnection(); connection.setSSLSocketFactory(noSSLv3Factory); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost())); byte[] postData = new byte[0]; if (message != null) { postData = message.getBytes("UTF-8"); } if (msCookieManager.getCookieStore().getCookies().size() > 0) { // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';' connection.setRequestProperty("Cookie", TextUtils.join(";", msCookieManager.getCookieStore().getCookies())); } /*if (method.equals("PATCH")) { connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); connection.setRequestMethod("POST"); } else {*/ connection.setRequestMethod(method); //} if (authorization.length() != 0) { connection.setRequestProperty("Authorization", authorization); } connection.setUseCaches(false); connection.setDoInput(true); connection.setConnectTimeout(HTTP_TIMEOUT_MS); connection.setReadTimeout(HTTP_TIMEOUT_MS); // TODO(glaznev) - query request origin from pref_room_server_url_key preferences. //connection.addRequestProperty("origin", HTTP_ORIGIN); boolean doOutput = false; if (method.equals("POST") || method.equals("PATCH")) { doOutput = true; connection.setDoOutput(true); connection.setFixedLengthStreamingMode(postData.length); } if (contentType == null) { connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); } else { connection.setRequestProperty("Content-Type", contentType); } // Send POST request. if (doOutput && postData.length > 0) { OutputStream outStream = connection.getOutputStream(); outStream.write(postData); outStream.close(); } // Get response. int responseCode = 200; try { connection.getResponseCode(); } catch (IOException e) { } getCookies(connection); InputStream responseStream; if (responseCode > 400) { responseStream = connection.getErrorStream(); } else { responseStream = connection.getInputStream(); } String responseType = connection.getContentType(); if (responseType.startsWith("image/")) { Bitmap bitmap = BitmapFactory.decodeStream(responseStream); if (mIsBitmap && bitmap != null) { ThumbnailsCacheManager.addBitmapToCache(url, bitmap); } events.onHttpComplete(bitmap); } else { String response = drainStream(responseStream); events.onHttpComplete(response); } responseStream.close(); connection.disconnect(); } catch (SocketTimeoutException e) { events.onHttpError("HTTP " + method + " to " + url + " timeout"); } catch (IOException e) { if (connection != null) { connection.disconnect(); } events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage()); } catch (ClassCastException e) { e.printStackTrace(); } }
From source file:com.awstrainers.devcourse.sdkdemos.S3Test.java
@Test public void checkUploadEncryptedObject() throws Exception { // Check the next url to read about how to use strong encryption with the jdk. // http://www.oracle.com/technetwork/es/java/javase/downloads/jce-7-download-432124.html KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGenerator.genKeyPair(); // obviously that keypair should be stored somewhere, but this is just a test. EncryptionMaterials encryptionMaterials = new EncryptionMaterials(keyPair); AmazonS3 client = new AmazonS3EncryptionClient(cred, encryptionMaterials); log.info(format("Using {0} bucket to post a new encrypted file.", bucketName)); File file = createTempFile(); Bucket bucket = client.createBucket(bucketName); PutObjectResult result = client.putObject(bucket.getName(), file.getName(), file); }
From source file:com.telefonica.iot.tidoop.apiext.http.HttpClientFactory.java
/** * Gets a SchemeRegistry object accepting all the X509 certificates by default. * @return A SchemeRegistry object./* w ww . ja va 2s . com*/ */ private SchemeRegistry getSchemeRegistry() { // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0 SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")"); return null; } // try catch try { // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } // getAcceptedIssuers @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } // getAcceptedIssuers @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } // checkServerTrusted } }, new SecureRandom()); } catch (KeyManagementException e) { logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")"); return null; } // try catch if (sslContext == null) { logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)"); return null; } // if SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); return schemeRegistry; }