List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:keyserver.KeyServerServlet.java
private String createKeyForUser(User _user) { SecureRandom srand = new SecureRandom(); byte[] iv = new byte[512]; srand.nextBytes(iv);//from ww w .j av a 2 s. c o m MessageDigest md = null; // This block initializes the MessageDigest try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { // Not going to happen. Every implementation of Java is required // to support SHA-256, please see here: // http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html } md.update(iv); byte[] hash = md.digest(); return new String(Base64.encode(hash)); }
From source file:com.hellblazer.jackal.configuration.GossipHeartbeatAndDiscoveryConfig.java
@Bean @Primary// ww w . j av a 2s . c om public SystemView systemView() throws IOException { return new SystemView(new SecureRandom(), communications().getLocalAddress(), seedHosts, gossipConfiguration.quarantineDelay, gossipConfiguration.unreachableNodeDelay); }
From source file:io.coala.capability.online.FluentHCOnlineCapability.java
@Override public void initialize() throws NoSuchAlgorithmException, KeyManagementException { synchronized (FluentHCOnlineCapability.class) { if (setup) return; if (!getBinder().inject(ConfiguringCapability.class).getProperty(TRUST_MANAGER_DISABLED_PROPERTY_KEY) .getBoolean(TRUST_MANAGER_DISABLED_PROPERTY_DEFAULT)) return; final SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DummyTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); setup = true;/*from ww w . j av a2s . c o m*/ } }
From source file:org.ckan.Connection.java
/** * Makes a POST request/*w ww. j a v a 2 s . c o m*/ * * Submits a POST HTTP request to the CKAN instance configured within * the constructor, returning the entire contents of the response. * * @param path The URL path to make the POST request to * @param data The data to be posted to the URL * @returns The String contents of the response * @throws A CKANException if the request fails */ protected String post(String path, String data) throws CKANException { URL url = null; try { url = new URL(this.m_host + ":" + this.m_port + path); } catch (MalformedURLException mue) { System.err.println(mue); return null; } String body = ""; BasicClientConnectionManager bccm = null; ClientConnectionManager cm = null; try { /***********************************************************************/ 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; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); //bccm = new BasicClientConnectionManager(schemeRegistry); // apache HttpClient version >4.2 should use BasicClientConnectionManager cm = new SingleClientConnManager(schemeRegistry); /***********************************************************************/ } catch (KeyManagementException kme) { System.out.println("Con ex: " + kme.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println("Con ex: " + nsae.getMessage()); } //HttpClient httpclient = new DefaultHttpClient(cm); HttpClient httpclient = new DefaultHttpClient(); try { HttpPost postRequest = new HttpPost(url.toString()); postRequest.setHeader("X-CKAN-API-Key", this._apikey); StringEntity input = new StringEntity(data); input.setContentType("application/json"); postRequest.setEntity(input); HttpResponse response = httpclient.execute(postRequest); int statusCode = response.getStatusLine().getStatusCode(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String line = ""; while ((line = br.readLine()) != null) { body += line; } } catch (IOException ioe) { System.out.println(ioe); } finally { httpclient.getConnectionManager().shutdown(); } return body; }
From source file:edu.kit.dama.rest.util.auth.impl.BearerTokenAuthenticator.java
@Override public IAuthorizationContext obtainAuthorizationContext(HttpContext hc, GroupId groupId) throws UnauthorizedAccessAttemptException { String token = hc.getRequest().getHeaderValue("Authorization");//getQueryParameters().getFirst("authToken"); if (token == null) { throw new UnauthorizedAccessAttemptException("No authorization header entry provided."); }/*from w w w .j a v a2s. c om*/ if (token.startsWith("Bearer ")) { LOGGER.debug("Starting bearer token authentication."); if (tokenInfoServiceUrl != null) { LOGGER.debug("Validating provided bearer token using info service at '{}'.", tokenInfoServiceUrl); //if validate, do this ClientConfig config = new DefaultClientConfig(); try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { TRUST_MANAGER }, new SecureRandom()); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(VERIFIER, ctx)); com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config); WebResource webResource = client.resource(new URL(tokenInfoServiceUrl).toURI()); String result = webResource.header("Authorization", token).get(String.class); LOGGER.debug("Service returned result {}. Checking 'exp' property.", result); JSONObject resultObject = new JSONObject(result); long expiresAt = resultObject.getLong("exp"); LOGGER.debug("Token exp property is set to value {}.", expiresAt); if (System.currentTimeMillis() > expiresAt) { throw new UnauthorizedAccessAttemptException( "The provided bearer token has expired at timestamp " + expiresAt + "."); } } catch (NoSuchAlgorithmException | KeyManagementException ex) { throw new UnauthorizedAccessAttemptException( "Failed to perform secured access to token info service.", ex); } catch (MalformedURLException | URISyntaxException ex) { throw new UnauthorizedAccessAttemptException( "Failed to access token info service due to a malformed URL.", ex); } } //still valid or not checked...remove 'Bearer ' part and continue LOGGER.debug("Token validation succeeded/skipped. Proceeding with authentication"); token = token.replaceFirst("Bearer ", ""); } else { throw new UnauthorizedAccessAttemptException( "No bearer token provided in authorization header. Token is '" + token + "'"); } IMetaDataManager manager = MetaDataManagement.getMetaDataManagement().getMetaDataManager(); manager.setAuthorizationContext(AuthorizationContext.factorySystemContext()); try { String tokenKey = CryptUtil.stringToSHA1(token); LOGGER.debug("Obtaining service access token for key {}", tokenKey); ServiceAccessToken accessToken = ServiceAccessUtil.getAccessToken(manager, tokenKey, getAuthenticatorId()); if (accessToken == null) { throw new UnauthorizedAccessAttemptException("No access token obtained for tokenKey '" + tokenKey + "' and serviceId '" + getAuthenticatorId() + "'"); } LOGGER.debug("Building and returning AuthorizationContext for user {}", accessToken.getUserId()); //no secret handling needed for the moment as only the token is validated return buildAuthorizationContext(new UserId(accessToken.getUserId()), groupId); } catch (UnauthorizedAccessAttemptException | EntityNotFoundException ex) { throw new UnauthorizedAccessAttemptException( "The access using the provided HttpContext has not been authorized.", ex); } finally { manager.close(); } }
From source file:edu.hm.muse.controller.Logincontroller.java
@RequestMapping(value = "/adminlogin.secu", method = RequestMethod.GET) public ModelAndView showAdminLoginScreen(HttpSession session) { ModelAndView mv = new ModelAndView("adminlogin"); mv.addObject("msg", "Enter password"); SecureRandom random = new SecureRandom(); int token = random.nextInt(); mv.addObject("csrftoken", token); session.setAttribute("csrftoken", token); return mv;/*from ww w . ja v a 2s .c o m*/ }
From source file:org.wso2.carbon.apimgt.authenticator.oidc.ui.common.Util.java
/** * Create a cryptographically random nonce/state and return * @return randomString/*from ww w .j ava 2s . c o m*/ */ public static String createRandomString() { return new BigInteger(50, new SecureRandom()).toString(16); }
From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java
@Override public String getEncryptedLicense(PublicKey targetKey) throws SystemStateException, OperationException { byte[] licenseAsBytes; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(this); licenseAsBytes = bos.toByteArray(); } catch (IOException ex) { throw new OperationException("An error occured while serializing the license", ex); }//www . j ava 2 s .co m SecureRandom random = new SecureRandom(); Cipher aescipher; Cipher rsacipher; KeyGenerator aesgenerator; Key symkey; try { aesgenerator = KeyGenerator.getInstance(symmetricKeyType, provider); aesgenerator.init(128, random); symkey = aesgenerator.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SystemStateException("The specified symkey could not be generated.", ex); } try { aescipher = Cipher.getInstance(symmetricEncoding, provider); rsacipher = Cipher.getInstance(asymmetricEncoding, provider); aescipher.init(Cipher.ENCRYPT_MODE, symkey); rsacipher.init(Cipher.ENCRYPT_MODE, targetKey); } catch (NoSuchAlgorithmException | NoSuchProviderException | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) { throw new SystemStateException("The specified encryption provider or algorithm was not found", ex); } String encryptedLicense; try { byte[] encryptedsymkey = rsacipher.doFinal(symkey.getEncoded()); byte[] encryptedlicense = aescipher.doFinal(licenseAsBytes); byte[] licenseWithKey = new byte[encryptedsymkey.length + encryptedlicense.length]; System.arraycopy(encryptedsymkey, 0, licenseWithKey, 0, encryptedsymkey.length); System.arraycopy(encryptedlicense, 0, licenseWithKey, encryptedsymkey.length, encryptedlicense.length); encryptedLicense = Base64.encodeBase64String(licenseWithKey); } catch (IllegalBlockSizeException | BadPaddingException ex) { throw new OperationException("Could not encode to base64", ex); } return encryptedLicense; }
From source file:edu.utah.further.core.xml.xquery.basex.BaseXServerBean.java
/** * Set the default admin/admin password to a random 130 bit String * //w w w. j a va 2 s .c om * @return */ private String changeAdminPassword() { final StringBuilder sb = new StringBuilder(); // Set the admin password to a random 130 bit String sb.append("ALTER USER admin " + DigestUtils.md5DigestAsHex((new BigInteger(130, new SecureRandom()).toString(32)).getBytes())); return sb.toString(); }
From source file:immf.MyWiser.java
private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) { InputStream keyis = null;/*www.ja v a 2s . c o m*/ try { keyis = new FileInputStream(keystoreFile); KeyStore keyStore = KeyStore.getInstance(keyType); keyStore.load(keyis, keypasswd.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, keypasswd.toCharArray()); SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), null, new SecureRandom()); return context.getSocketFactory(); } catch (Exception e) { e.printStackTrace(); return (SSLSocketFactory) SSLSocketFactory.getDefault(); } finally { try { keyis.close(); } catch (Exception e) { } } }