List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:com.vmware.identity.sts.auth.impl.UserCertAuthenticatorTest.java
@BeforeClass public static void setUp() throws Exception { // create key pair and client private key, certificate KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair userKeyPair = keyGen.generateKeyPair(); userPrivateKey = (RSAPrivateKey) userKeyPair.getPrivate(); x509Certificate = generateCertificate(userKeyPair, "User"); }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static X509Certificate generateCertificate(KeyPair keyPair, String dn, String subjectAltName) throws Exception { ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").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 ww w. j av a2 s . c om if (subjectAltName != null) { v3CertGen .addExtension(Extension.subjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.otherName, new DERSequence(new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.4.1.311.20.2.3"), new DERTaggedObject(true, 0, new DERUTF8String(subjectAltName)) })))); } X509CertificateHolder certHolder = v3CertGen.build(sigGen); X509Certificate x509Certificate = new JcaX509CertificateConverter().getCertificate(certHolder); return x509Certificate; }
From source file:com.thoughtworks.go.security.DESCipherProvider.java
private byte[] generateKey() { SecureRandom random = new SecureRandom(); random.setSeed(UUID.randomUUID().toString().getBytes()); KeyGenerationParameters generationParameters = new KeyGenerationParameters(random, DESParameters.DES_KEY_LENGTH * 8); DESKeyGenerator generator = new DESKeyGenerator(); generator.init(generationParameters); return generator.generateKey(); }
From source file:Controlador.ControladorUsuario.java
/** * Crea un codigo de recuperacion para el usuario, actualiza el usuario en * la BD con el codigo creado y la fecha de la creacion. * * @param u El usuario./*w w w .j a va 2 s .c om*/ * @return El codigo creado. */ public String crearCodigoRecuperacion(Usuario u) { SecureRandom random = new SecureRandom(); String codigo = new BigInteger(130, random).toString(32); u.setCodigo(codigo); Date d = new Date(); u.setFechaCreacionCodigo(d); usuarioDAO.actualizar(u); return codigo; }
From source file:hudson.scm.credential.SshPublicKeyCredential.java
/** * @param keyFile stores SSH private key. The file will be copied. *//* w ww.j a v a 2 s.c om*/ public SshPublicKeyCredential(String userName, String passphrase, File keyFile) throws SVNException { this.userName = userName; this.passphrase = Scrambler.scramble(passphrase); SecureRandom r = new SecureRandom(); StringBuilder buf = new StringBuilder(); for (int i = 0; i < 16; i++) { buf.append(Integer.toHexString(r.nextInt(16))); } this.id = buf.toString(); try { File savedKeyFile = getKeyFile(); System.out.println(keyFile.getAbsolutePath()); System.out.println(savedKeyFile.getAbsolutePath()); FileUtils.copyFile(keyFile, savedKeyFile); setFilePermissions(savedKeyFile, "600"); } catch (IOException e) { throw new SVNException(SVNErrorMessage.create(SVNErrorCode.AUTHN_CREDS_UNAVAILABLE, Messages.SshPublicKeyCredential_private_key_save_error()), e); } }
From source file:com.bitsofproof.supernode.core.IRCDiscovery.java
@Override public List<InetSocketAddress> discover() { List<InetSocketAddress> al = new ArrayList<InetSocketAddress>(); try {/*www .j a v a 2s .co m*/ log.trace("Connect to IRC server " + server); Socket socket = new Socket(server, port); PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); String[] answers = new String[] { "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname" }; String line; boolean stop = false; while (!stop && (line = reader.readLine()) != null) { log.trace("IRC receive " + line); for (int i = 0; i < answers.length; ++i) { if (line.contains(answers[i])) { stop = true; break; } } } String nick = "bop" + new SecureRandom().nextInt(Integer.MAX_VALUE); writer.println("NICK " + nick); writer.println("USER " + nick + " 8 * : " + nick); writer.flush(); log.trace("IRC send: I am " + nick); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 004 ", " 433 " })) { break; } } log.trace("IRC send: joining " + channel); writer.println("JOIN " + channel); writer.println("NAMES"); writer.flush(); while ((line = reader.readLine()) != null) { log.trace("IRC receive " + line); if (hasCode(line, new String[] { " 353 " })) { StringTokenizer tokenizer = new StringTokenizer(line, ":"); String t = tokenizer.nextToken(); if (tokenizer.hasMoreElements()) { t = tokenizer.nextToken(); } tokenizer = new StringTokenizer(t); tokenizer.nextToken(); while (tokenizer.hasMoreTokens()) { String w = tokenizer.nextToken().substring(1); if (!tokenizer.hasMoreElements()) { continue; } try { byte[] m = ByteUtils.fromBase58WithChecksum(w); byte[] addr = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff, 0, 0, 0, 0 }; System.arraycopy(m, 0, addr, 12, 4); al.add(new InetSocketAddress(InetAddress.getByAddress(addr), chain.getPort())); } catch (ValidationException e) { log.trace(e.toString()); } } } if (hasCode(line, new String[] { " 366 " })) { break; } } writer.println("PART " + channel); writer.println("QUIT"); writer.flush(); socket.close(); } catch (UnknownHostException e) { log.error("Can not find IRC server " + server, e); } catch (IOException e) { log.error("Can not use IRC server " + server, e); } return al; }
From source file:com.github.beat.signer.pdf_signer.TSAClient.java
/** * * @param messageImprint/*from w w w .jav a 2s.com*/ * imprint of message contents * @return the encoded time stamp token * @throws IOException * if there was an error with the connection or data from the * TSA server, or if the time stamp response could not be * validated */ public byte[] getTimeStampToken(byte[] messageImprint) throws IOException { digest.reset(); byte[] hash = digest.digest(messageImprint); // 32-bit cryptographic nonce // FIXME sicher?? SecureRandom random = new SecureRandom(); int nonce = random.nextInt(); // generate TSA request TimeStampRequestGenerator tsaGenerator = new TimeStampRequestGenerator(); tsaGenerator.setCertReq(true); ASN1ObjectIdentifier oid = getHashObjectIdentifier(digest.getAlgorithm()); TimeStampRequest request = tsaGenerator.generate(oid, hash, BigInteger.valueOf(nonce)); // get TSA response byte[] tsaResponse = getTSAResponse(request.getEncoded()); TimeStampResponse response; try { response = new TimeStampResponse(tsaResponse); response.validate(request); } catch (TSPException e) { throw new IOException(e); } TimeStampToken token = response.getTimeStampToken(); if (token == null) { throw new IOException("Response does not have a time stamp token"); } return token.getEncoded(); }
From source file:com.mobilehelix.appserver.push.PushManager.java
@PostConstruct public void init() { userPushMap = new ConcurrentHashMap<>(); idMap = new ConcurrentHashMap<>(); srandom = new SecureRandom(); }
From source file:com.daoke.mobileserver.test.TestHttps.java
public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;/* ww w . j av a 2 s . c o m*/ String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:com.stratio.qa.utils.GosecSSOUtils.java
/** * This method provide dcos and sso token to be used to generate client cookie * @return cookieToken list of token generated * @throws Exception exception//from w w w. j a v a 2s . com */ public HashMap<String, String> ssoTokenGenerator() throws Exception { String protocol = "https://"; HashMap<String, String> cookieToken = new HashMap<>(); SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom()); HttpClientContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login"); HttpClient client = HttpClientBuilder.create().setSslcontext(sslContext) .setRedirectStrategy(new LaxRedirectStrategy()) .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).build(); try { HttpResponse firstResponse = client.execute(httpGet, context); logger.debug(firstResponse.getStatusLine().toString()); Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent())); Elements code = doc.select("[name=lt]"); String loginCode = code.attr("value"); String executionCode = doc.select("[name=execution]").attr("value"); for (Header oneHeader : firstResponse.getAllHeaders()) { logger.debug(oneHeader.getName() + ":" + oneHeader.getValue()); } URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("_eventId", "submit")); params.add(new BasicNameValuePair("submit", "LOGIN")); params.add(new BasicNameValuePair("username", userName)); params.add(new BasicNameValuePair("password", passWord)); params.add(new BasicNameValuePair("lt", loginCode)); params.add(new BasicNameValuePair("execution", executionCode)); HttpPost httpPost = new HttpPost(redirect); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse secondResponse = client.execute(httpPost, context); for (Header oneHeader : secondResponse.getAllHeaders()) { logger.debug(oneHeader.getName() + ":" + oneHeader.getValue()); } HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost); client.execute(managementGet, context); for (Cookie oneCookie : context.getCookieStore().getCookies()) { logger.debug(oneCookie.getName() + ":" + oneCookie.getValue()); cookieToken.put(oneCookie.getName(), oneCookie.getValue()); } } catch (Exception e) { e.getStackTrace(); } return cookieToken; }