List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:org.smartplatforms.oauth2.SmartClientUserDetailsService.java
@Override public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException { try {/* w w w. j a v a 2 s . c o m*/ ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientId); if (client != null) { String password = Strings.nullToEmpty(client.getClientSecret()); if (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 password = new BigInteger(512, new SecureRandom()).toString(16); } boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(client.getAuthorities()); authorities.add(ROLE_CLIENT); if (adminClients.contains(client.getClientId())) { GrantedAuthority roleClient = new SimpleGrantedAuthority("ROLE_ADMIN"); authorities.add(roleClient); } return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } else { throw new UsernameNotFoundException("Client not found: " + clientId); } } catch (InvalidClientException e) { throw new UsernameNotFoundException("Client not found: " + clientId); } }
From source file:com.hybridbpm.core.util.HybridbpmCoreUtil.java
public static String generateToken(String username) throws NoSuchAlgorithmException, UnsupportedEncodingException { try {// ww w .j av a2 s .c o m SecureRandom random = new SecureRandom(); String token_data = UUID.randomUUID().toString() + username + System.nanoTime() + new BigInteger(32, random).toString(32); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(token_data.getBytes("UTF-8")); byte[] bytes = md.digest(); return new HexBinaryAdapter().marshal(bytes); } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } return null; }
From source file:org.cloudfoundry.identity.uaa.login.feature.InvitationsIT.java
@Test public void testSendInvite() throws Exception { int randomInt = new SecureRandom().nextInt(); String userEmail = "user" + randomInt + "@example.com"; int receivedEmailSize = simpleSmtpServer.getReceivedEmailSize(); signIn(testAccounts.getUserName(), testAccounts.getPassword()); webDriver.findElement(By.linkText("Invite Users")).click(); assertEquals("Send an invite", webDriver.findElement(By.tagName("h1")).getText()); webDriver.findElement(By.name("email")).sendKeys(userEmail); webDriver.findElement(By.xpath("//input[@value='Send invite']")).click(); assertEquals("Invite sent", webDriver.findElement(By.tagName("h1")).getText()); assertEquals(receivedEmailSize + 1, simpleSmtpServer.getReceivedEmailSize()); Iterator receivedEmail = simpleSmtpServer.getReceivedEmail(); SmtpMessage message = (SmtpMessage) receivedEmail.next(); receivedEmail.remove();/* w w w . j av a2 s. c o m*/ assertEquals(userEmail, message.getHeaderValue("To")); assertThat(message.getBody(), containsString("Accept Invite")); String link = testClient.extractLink(message.getBody()); assertTrue(link.contains("/invitations/accept")); webDriver.get(link); assertEquals("Create your account", webDriver.findElement(By.tagName("h1")).getText()); webDriver.findElement(By.name("password")).sendKeys("secret"); webDriver.findElement(By.name("password_confirmation")).sendKeys("secret"); webDriver.findElement(By.xpath("//input[@value='Create account']")).click(); assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?")); webDriver.findElement(By.xpath("//*[text()='" + userEmail + "']")).click(); webDriver.findElement(By.linkText("Sign Out")).click(); webDriver.findElement(By.name("username")).sendKeys(userEmail); webDriver.findElement(By.name("password")).sendKeys("secret"); webDriver.findElement(By.xpath("//input[@value='Sign in']")).click(); assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?")); }
From source file:com.spotify.sshagenttls.CertHttpsHandler.java
public void handle(final HttpsURLConnection conn) { final CertKey certKey; try {/*from ww w. j a va 2s . c o m*/ certKey = createCertKey(); } catch (IOException | GeneralSecurityException e) { if (failOnCertError) { throw new RuntimeException(e); } else { LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. " + "No cert will be sent with request.", getCertSource(), e.toString()); LOG.debug("full exception fromPaths setting up ClientCertificate follows", e); return; } } final Certificate cert = certKey.cert(); final PrivateKey key = certKey.key(); // Generate a keystore password. // Do all this locally to not make copies of the password in memory. final SecureRandom random = new SecureRandom(); final int numBytes = 60; final char[] keyStorePassword = new char[numBytes]; for (int i = 0; i < numBytes; i++) { // Only use ASCII characters for the password. The corresponding integer range is [32, 126]. keyStorePassword[i] = (char) (random.nextInt(95) + 32); } try { // We're creating a keystore in memory and putting the cert & key into it. // The keystore needs a password when we put the key into it, even though it's only going to // exist for the lifetime of the process. So we just have some random password that we use. final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", cert); keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, keyStorePassword).build(); // Clear out arrays that had password Arrays.fill(keyStorePassword, '\0'); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more. throw new RuntimeException(e); } }
From source file:be.integrationarchitects.web.dragdrop.servlet.impl.DragDropServlet.java
@Override public void init(ServletConfig servletConfig) throws ServletException { random = new SecureRandom(); String str_cfg = servletConfig.getInitParameter("cfg"); Class c = null;//from w w w. j a v a2 s.c o m try { c = Class.forName(str_cfg); cfg = (DragDropServletConfig) c.newInstance(); logger = cfg.getLogger(); //used in 500.jsp for error logging servletConfig.getServletContext().setAttribute("mycfg", cfg); } catch (Exception e) { System.err.println(e.getMessage()); throw new ServletException(e); } utils = new DragDropServletUtils(cfg.getFolder(), cfg.checkHash(), logger); logger.logDebug(".....................................Init drag drop servlet ok:" + str_cfg + ":" + cfg.getHandler() + ":" + cfg.getFolder()); }
From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java
/** * Main constructor./* ww w . j a v a 2 s . c o m*/ * * @param secretKeySpec * the AES secret key to protect the handle (confidentiality). * @param macSecretKeySpec * the MAC secret key to protect the handle (integrity). */ public StatelessServerAssociationStore(SecretKeySpec secretKeySpec, SecretKeySpec macSecretKeySpec) { int length = secretKeySpec.getEncoded().length; if (length != 16 && length != 24 && length != 32) { throw new IllegalArgumentException("secret key should be 16/24/32 bytes"); } this.secretKeySpec = secretKeySpec; this.macSecretKeySpec = macSecretKeySpec; this.secureRandom = new SecureRandom(); this.secureRandom.setSeed(System.currentTimeMillis()); }
From source file:org.mitre.oauth2.service.impl.DefaultClientUserDetailsService.java
@Override public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException { try {/*from w ww .j av a2 s. co m*/ ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientId); if (client != null) { String password = Strings.nullToEmpty(client.getClientSecret()); 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 password = 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(clientId, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } else { throw new UsernameNotFoundException("Client not found: " + clientId); } } catch (InvalidClientException e) { throw new UsernameNotFoundException("Client not found: " + clientId); } }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSTransformer.java
public static String getKeyFileString(PrivateKey privKey, char[] pwd) throws Exception { CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); PEMWriter pemWriter = new PEMWriter(new PrintWriter(cbb.getOutputStream())); cbb.getOutputStream().flush();//from w w w .j a v a 2 s . c om cbb.getOutputStream().close(); if (pwd != null) { JcePEMEncryptorBuilder encryptorBuilder = new JcePEMEncryptorBuilder(DES_EDE3_CBC); encryptorBuilder.setProvider(JCE_PROVIDER); encryptorBuilder.setSecureRandom(new SecureRandom()); pemWriter.writeObject(privKey, encryptorBuilder.build(pwd)); } else { pemWriter.writeObject(privKey); } pemWriter.flush(); pemWriter.close(); String keyFile = StreamUtil.stream2Bytes(cbb.getInputStream(), StandardCharsets.UTF_8); cbb.getInputStream().close(); cbb.clear(); return keyFile; }
From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java
/** * Open an URL connection. If HTTPS, accepts any certificate even if not * valid, and connects to any host name. * /*from w w w. jav a2 s .c o m*/ * @param url * The destination URL, HTTP or HTTPS. * @return The URLConnection. * @throws IOException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static URLConnection getConnection(URL url) throws IOException, NoSuchAlgorithmException, KeyManagementException { URLConnection conn = url.openConnection(); if (conn instanceof HttpsURLConnection) { // Trust all certificates SSLContext context = SSLContext.getInstance("TLS"); context.init(new KeyManager[0], TRUST_MANAGER, new SecureRandom()); SSLSocketFactory socketFactory = context.getSocketFactory(); ((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory); // Allow all hostnames ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); } conn.setConnectTimeout(SOCKET_TIMEOUT); conn.setReadTimeout(SOCKET_TIMEOUT); return conn; }
From source file:UUIDGenerator.java
private static synchronized void initializeForType1() { if (RANDOM != null) return;/*from ww w .j a v a2 s . com*/ // note that secure random is very slow the first time // it is used; consider switching to a standard random RANDOM = new SecureRandom(); _seq = (short) RANDOM.nextInt(MAX_14BIT); byte[] ip = null; try { ip = InetAddress.getLocalHost().getAddress(); } catch (IOException ioe) { throw new RuntimeException(ioe); } IP = new byte[6]; RANDOM.nextBytes(IP); System.arraycopy(ip, 0, IP, 2, ip.length); }