List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:io.personium.core.utils.HttpClientFactory.java
/** * SSLSocket?./* ww w. java 2 s. c o m*/ * @return ???SSLSocket */ private static SSLSocketFactory createInsecureSSLSocketFactory() { // CHECKSTYLE:OFF SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e1) { throw new RuntimeException(e1); } try { sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); X509Certificate[] ret = new X509Certificate[0]; return ret; } public void checkClientTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); } catch (KeyManagementException e1) { throw new RuntimeException(e1); } // CHECKSTYLE:ON HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier); // socketFactory.setHostnameVerifier((X509HostnameVerifier) // hostnameVerifier); return socketFactory; }
From source file:com.miapc.ipudong.Application.java
@Bean public RestTemplate getRestTemplate() { SSLContext sslcontext = null; Set<KeyManager> keymanagers = new LinkedHashSet<>(); Set<TrustManager> trustmanagers = new LinkedHashSet<>(); try {/*from ww w. j a v a 2s.co m*/ trustmanagers.add(new HttpsTrustManager()); KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]); TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]); sslcontext = SSLContexts.custom().build(); sslcontext.init(km, tm, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(factory); // ?3? httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)); // ????Keep-Alive httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); List<Header> headers = new ArrayList<>(); headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate")); headers.add(new BasicHeader("Accept-Language", "zh-CN")); headers.add(new BasicHeader("Connection", "Keep-Alive")); headers.add(new BasicHeader("Authorization", "reslibu")); httpClientBuilder.setDefaultHeaders(headers); CloseableHttpClient httpClient = httpClientBuilder.build(); if (httpClient != null) { // httpClient??RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); // clientHttpRequestFactory.setConnectTimeout(60 * 1000); // ???SocketTimeout clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000); // ???? clientHttpRequestFactory.setConnectionRequestTimeout(5000); // ?truePOSTPUT????false? // clientHttpRequestFactory.setBufferRequestBody(false); // ? List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); RestTemplate restTemplate = new RestTemplate(messageConverters); restTemplate.setRequestFactory(clientHttpRequestFactory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); return restTemplate; } else { return null; } }
From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java
public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception { SSLContext 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; }//from ww w .j av a2 s . c om public void checkClientTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String arg0) { // TODO Auto-generated method stub return super.isRedirectable(arg0); } @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // TODO Auto-generated method stub return super.isRedirected(request, response, context); } }).setDefaultCookieStore(new BasicCookieStore()) .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0") .build(); Executor exec = Executor.newInstance(httpclient); URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html"); String fullURL = ub.build().toASCIIString(); Request req = HttpUtils.get(fullURL, sp); HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); String tgtID = readData(exec, req, monitor); String action = getFormAction(tgtID); if (action != null) { action = action.replaceFirst("/", ""); int indx = action.indexOf(";jsession"); if (indx >= 0) action = action.substring(0, indx); } else action = "cas/login"; String url = srv.getUrl(); if (!url.endsWith("/")) url += "/"; ub = new URIBuilder(url + action); // fullURL = ub.build().toASCIIString(); req = HttpUtils.get(fullURL, sp); proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); tgtID = readData(exec, req, monitor); action = getFormAction(tgtID); action = action.replaceFirst("/", ""); ub = new URIBuilder(url + action); Map<String, String> map = getInputs(tgtID); Form form = Form.form(); for (String key : map.keySet()) { if (key.equals("btn-reset")) continue; else if (key.equals("username")) { form.add(key, srv.getUser()); continue; } else if (key.equals("password")) { form.add(key, Pass.getPass(srv.getPassword())); continue; } form.add(key, map.get(key)); } // req = HttpUtils.post(ub.build().toASCIIString(), form, sp); if (proxy != null) req.viaProxy(proxy); // Header header = null; readData(exec, req, monitor); // for (Header h : headers) { // for (HeaderElement he : h.getElements()) { // if (he.getName().equals("CASTGC")) { // header = new BasicHeader("Cookie", h.getValue()); // break; // } // } // } ub = new URIBuilder(url + action); url = sp.getUrl(); if (!url.endsWith("/")) url += "/"; ub.addParameter("service", url + "j_spring_security_check"); req = HttpUtils.get(ub.build().toASCIIString(), sp); if (proxy != null) req.viaProxy(proxy); // req.addHeader("Accept", // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value"); req.addHeader("Referrer", sp.getUrl()); // req.addHeader(header); String html = readData(exec, req, monitor); Matcher matcher = ahrefPattern.matcher(html); while (matcher.find()) { Map<String, String> attributes = parseAttributes(matcher.group(1)); String v = attributes.get("href"); int ind = v.indexOf("ticket="); if (ind > 0) { return v.substring(ind + "ticket=".length()); } } return null; }
From source file:Crypto.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 mEcipher is created to be used * by the class later on when either creating a CipherOutputStream, or encrypting a buffer * to be written to disk./*w ww . j a va2s . c o m*/ * * @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 mSalt = new byte[SALT_LEN]; SecureRandom rnd = new SecureRandom(); rnd.nextBytes(mSalt); Db("generated salt :" + Hex.encodeHexString(mSalt)); 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(mPassword.toCharArray(), mSalt, 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 */ mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mEcipher.init(Cipher.ENCRYPT_MODE, secret); AlgorithmParameters params = mEcipher.getParameters(); // get the initialization vectory and store as member var mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV(); Db("mInitVec is :" + Hex.encodeHexString(mInitVec)); }
From source file:com.azaptree.services.security.domain.config.impl.HashServiceConfig.java
@Override public HashService getHashService() { if (hashService != null) { return hashService; }//from ww w . j av a 2 s . c o m final DefaultHashService service = new DefaultHashService(); service.setGeneratePublicSalt(true); service.setPrivateSalt(ByteSource.Util.bytes(privateSalt)); service.setHashAlgorithmName(hashAlgorithmName); service.setHashIterations(hashIterations); final SecureRandomNumberGenerator rng = new SecureRandomNumberGenerator(); rng.setDefaultNextBytesSize(secureRandomNumberGeneratorNextBytesSize); final SecureRandom random = new SecureRandom(); final byte rngSeed[] = new byte[20]; random.nextBytes(rngSeed); rng.setSeed(rngSeed); service.setRandomNumberGenerator(rng); hashService = service; return service; }
From source file:fshp.FSHP.java
/** * Returns the hash of <tt>passwd</tt> * * @param passwd Byte representation of clear text password. * @param salt Byte representation of salt to be used in hashing. * @param saltlen Length of the salt. Should be 0 if a salt is already * provided. If salt is null, saltlen bytes of salt will be * auto generated.// www . ja va 2 s. c o m * @param rounds Number of hashing rounds. * @param variant FSHP variant indicating the behaviour and/or * <ul> * <li><tt>0: SHA-1</tt> <em>(not recommended)</em></li> * <li><tt>1: SHA-256</tt></li> * <li><tt>2: SHA-384</tt></li> * <li><tt>3: SHA-512</tt></li> * </ul> * * @return FSHP hash of <tt>passwd</tt> */ public static String crypt(byte[] passwd, byte[] salt, int saltlen, int rounds, int variant) throws Exception { // Ensure we have sane values for salt length and rounds. if (saltlen < 0) saltlen = 0; if (rounds < 1) rounds = 1; if (salt == null) { salt = new byte[saltlen]; new SecureRandom().nextBytes(salt); } else saltlen = salt.length; HashMap<Integer, String> algoMap = new HashMap<Integer, String>(); algoMap.put(0, "SHA-1"); algoMap.put(1, "SHA-256"); algoMap.put(2, "SHA-384"); algoMap.put(3, "SHA-512"); MessageDigest md; try { if (!algoMap.containsKey(variant)) throw new NoSuchAlgorithmException(); md = MessageDigest.getInstance(algoMap.get(variant)); } catch (NoSuchAlgorithmException e) { throw new Exception("Unsupported FSHP variant " + variant); } md.update(salt); md.update(passwd); byte[] digest = md.digest(); for (int i = 1; i < rounds; i++) { md.reset(); md.update(digest); digest = md.digest(); } String meta = "{FSHP" + variant + "|" + saltlen + "|" + rounds + "}"; byte[] saltdigest = new byte[salt.length + digest.length]; System.arraycopy(salt, 0, saltdigest, 0, salt.length); System.arraycopy(digest, 0, saltdigest, salt.length, digest.length); byte[] b64saltdigest = Base64.encodeBase64(saltdigest); return meta + new String(b64saltdigest, "US-ASCII"); }
From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java
private HttpURLConnection getConnection(String urlString) throws MalformedURLException, IOException, NoSuchAlgorithmException, KeyManagementException { if (urlString.startsWith("https://")) { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); HttpsURLConnection connection = (HttpsURLConnection) ProxyConfiguration.open(new URL(urlString)); connection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String arg0, SSLSession arg1) { return true; }/*from w w w. j a va 2 s .c o m*/ }); return connection; } else if (urlString.contains("@")) { URL passedURL = new URL(urlString); String creds = urlString.substring(urlString.indexOf("//") + 2, urlString.indexOf("@")); String userName = creds.substring(0, creds.indexOf(":")); String passWord = creds.substring(creds.indexOf(":") + 1, creds.length()); String userPassword = userName + ":" + passWord; // TODO cambiar implementacin de Base64 String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); // TODO soporta proxy? HttpURLConnection connection = (HttpURLConnection) passedURL.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); return connection; } else { return (HttpURLConnection) ProxyConfiguration.open(new URL(urlString)); } }
From source file:com.example.android.vault.EncryptedDocument.java
/** * Create an encrypted document./*from w w w .j av a 2 s.co m*/ * * @param docId the expected {@link Document#COLUMN_DOCUMENT_ID} to be * validated when reading metadata. * @param file location on disk where the encrypted document is stored. May * not exist yet. */ public EncryptedDocument(long docId, File file, SecretKey dataKey, SecretKey macKey) throws GeneralSecurityException { mRandom = new SecureRandom(); mCipher = Cipher.getInstance("AES/CTR/NoPadding"); mMac = Mac.getInstance("HmacSHA256"); if (dataKey.getEncoded().length != DATA_KEY_LENGTH) { throw new IllegalArgumentException("Expected data key length " + DATA_KEY_LENGTH); } if (macKey.getEncoded().length != MAC_KEY_LENGTH) { throw new IllegalArgumentException("Expected MAC key length " + MAC_KEY_LENGTH); } mDocId = docId; mFile = file; mDataKey = dataKey; mMacKey = macKey; }
From source file:io.stallion.services.SecureTempTokens.java
public String idToRandomString(Long id) { SecureRandom random = new SecureRandom(); Integer rand = random.nextInt(); Long n = rand * 1000000000 + id; return Base64.getEncoder().encodeToString(BigInteger.valueOf(n).toByteArray()); }
From source file:com.vuzix.samplewebrtc.android.SessionChannel.java
public SessionChannel(String serverUrl, String session) { String userId = new BigInteger(USER_ID_BITS, new SecureRandom()).toString(USER_ID_RADIX); mServerToClientUrl = serverUrl + "/stoc/" + session + "/" + userId; mClientToServerUrl = serverUrl + "/ctos/" + session + "/" + userId; open();// w w w.j av a 2 s. c om }