List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java
private static SSLContext newNaiveSslContext() { try {/*from w ww . j a va 2s. c om*/ SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[] {}, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); return ctx; } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new RuntimeException(e); } }
From source file:com.amazonaws.cognito.sync.devauth.client.AmazonCognitoSampleDeveloperAuthenticationClient.java
/** * Creates a 128 bit random string..// w w w .j a va 2 s . c o m */ public static String generateRandomString() { SecureRandom random = new SecureRandom(); byte[] randomBytes = random.generateSeed(16); String randomString = new String(Hex.encodeHex(randomBytes)); return randomString; }
From source file:com.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java
private X509Certificate generateCertificate(KeyPair keyPair, String dn, String sigAlg) throws OperatorCreationException, CertificateException { ContentSigner sigGen = new JcaContentSignerBuilder(sigAlg).build(keyPair.getPrivate()); Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000); X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + dn), new BigInteger(64, new SecureRandom()), startDate, endDate, new X500Name("CN=" + dn), keyPair.getPublic());/*from w w w .j a v a2 s . c o m*/ X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:be.e_contract.mycarenet.common.SessionKey.java
/** * Generator constructor. Creates a new MyCareNet session key. * /*from w w w .j av a 2 s .co m*/ * @param keySize * the RSA key size. */ public SessionKey(int keySize) { KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance("RSA"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("RSA algo not available", e); } SecureRandom random = new SecureRandom(); try { keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException("unsupported key size: " + keySize); } this.keyPair = keyPairGenerator.generateKeyPair(); }
From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@BeforeClass public static void setupClass() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048, new SecureRandom()); CA_KEY_PAIR = keyGen.generateKeyPair(); CA_CERT = PKITestUtils.generateNewCACert(CA_KEY_PAIR.getPublic(), TEST_CA_DN, null, CA_KEY_PAIR.getPrivate(), TEST_CA_DN); }
From source file:co.cask.cdap.gateway.router.NettyRouterHttpsTest.java
@Override protected DefaultHttpClient getHTTPClient() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override// www .j av a 2 s . c o m public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException { // } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 10101, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); // apache HttpClient version >4.2 should use BasicClientConnectionManager ClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry); return new DefaultHttpClient(cm); }
From source file:im.whistle.crypt.Crypt.java
/** * Encrypts a message.//from w w w.j a va 2s . c o m * @param args Arguments: data, publicKey[, privateKey] * @param callback Callback */ public static void encrypt(JSONArray args, AsyncCallback<JSONArray> callback) { try { PRNGProvider.init(); // Ensure OpenSSL fix // Get the arguments String data = args.getString(0); String pub = args.getString(1); String priv = null; if (args.length() == 3) { priv = args.getString(2); } String sig = null; // Convert everything into byte arrays byte[] dataRaw = data.getBytes("utf-8"); byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT); // Generate random AES key and IV byte[] aesKey = new byte[AES_BYTES]; new SecureRandom().nextBytes(aesKey); byte[] aesIv = new byte[16]; // Block size new SecureRandom().nextBytes(aesIv); Cipher c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv)); // Encrypt data with AES byte[] encData = c.doFinal(dataRaw); // Encrypt aes data with RSA X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw); KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding", "BC"); c.init(Cipher.ENCRYPT_MODE, kf.generatePublic(publicKeySpec)); c.update(aesKey); c.update(aesIv); byte[] encKey = c.doFinal(); // Concatenate and transform byte[] encRaw = new byte[encKey.length + encData.length]; System.arraycopy(encKey, 0, encRaw, 0, encKey.length); System.arraycopy(encData, 0, encRaw, encKey.length, encData.length); encKey = null; encData = null; String enc = new String(Base64.encode(encRaw /* needed for sign */, Base64.NO_WRAP), "utf-8"); // Sign if (priv != null) { // Fail on error (no try-catch) byte[] privRaw = Base64.decode(stripKey(priv), Base64.DEFAULT); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privRaw); Signature s = Signature.getInstance("SHA1withRSA", "BC"); s.initSign(kf.generatePrivate(privateKeySpec)); s.update(encRaw); sig = new String(Base64.encode(s.sign(), Base64.NO_WRAP), "utf-8"); } JSONArray res = new JSONArray(); res.put(enc); res.put(sig); callback.success(res); } catch (Exception ex) { Log.w("whistle", "Encrypt error: " + ex.getMessage(), ex); callback.error(ex); } }
From source file:eu.trentorise.smartcampus.permissionprovider.auth.google.GoogleAuthHelper.java
/** * Generates a secure state token.//from w w w .j a va 2 s . c o m */ private String generateStateToken() { SecureRandom sr1 = new SecureRandom(); return "google;" + sr1.nextInt(); }
From source file:com.ovea.facebook.client.DefaultFacebookClient.java
public DefaultFacebookClient(String client_id, String client_secret, String redirect_uri) { this.clientId = client_id; this.clientSecret = client_secret; this.redirectUri = redirect_uri; try {/*from w ww. j a va2 s. c o m*/ SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }, new SecureRandom()); sslSocketFactory = new SSLSocketFactory(sslContext); //noinspection deprecation sslSocketFactory.setHostnameVerifier(new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } catch (NoSuchAlgorithmException e) { throw new FacebookException(e.getMessage(), e); } catch (KeyManagementException e) { throw new FacebookException(e.getMessage(), e); } }
From source file:org.mitre.oauth2.service.impl.UriEncodedClientUserDetailsService.java
@Override public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException { try {/*from w w w. j ava 2 s . c o m*/ String decodedClientId = UriUtils.decode(clientId, "UTF-8"); ClientDetailsEntity client = clientDetailsService.loadClientByClientId(decodedClientId); if (client != null) { String encodedPassword = UriUtils.encodeQueryParam(Strings.nullToEmpty(client.getClientSecret()), "UTF-8"); if (config.isHeartMode() || // if we're running HEART mode turn off all client secrets (client.getTokenEndpointAuthMethod() != null && (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)))) { // Issue a random password each time to prevent password auth from being used (or skipped) // for private key or shared key clients, see #715 encodedPassword = new BigInteger(512, new SecureRandom()).toString(16); } boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; Collection<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities()); authorities.add(ROLE_CLIENT); return new User(decodedClientId, encodedPassword, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } else { throw new UsernameNotFoundException("Client not found: " + clientId); } } catch (UnsupportedEncodingException | InvalidClientException e) { throw new UsernameNotFoundException("Client not found: " + clientId); } }