List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java
/** * Register to listen to HTTPS.//from w w w. j a va2 s .c o m * * @param server * @param address * @throws Exception */ public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned, boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword, String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword, String[] excludedCipherSuites) throws Exception { // SSL Context Factory SslContextFactory sslContextFactory = new SslContextFactory(); if (selfSigned) { char[] passwordChars = UUID.randomUUID().toString().toCharArray(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, passwordChars); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs()); v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None")); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None")); v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption"); X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate()); keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars, new java.security.cert.Certificate[] { privateKeyCertificate }); ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream(); keyStore.store(keyStoreBaos, passwordChars); keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8); keyStorePassword = new String(passwordChars); keyManagerPassword = keyStorePassword; sslContextFactory.setTrustAll(true); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); if (StringUtils.isNotBlank(keyStoreData)) { keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray()); } else if (StringUtils.isNotBlank(keyStorePath)) { try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) { keyStore.load(inputStream, keyStorePassword.toCharArray()); } } sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePassword); if (StringUtils.isBlank(keyManagerPassword)) { keyManagerPassword = keyStorePassword; } sslContextFactory.setKeyManagerPassword(keyManagerPassword); KeyStore trustStore = null; if (StringUtils.isNotBlank(trustStoreData)) { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray()); } else if (StringUtils.isNotBlank(trustStorePath)) { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath) .getInputStream()) { trustStore.load(inputStream, trustStorePassword.toCharArray()); } } if (trustStore != null) { sslContextFactory.setTrustStore(trustStore); sslContextFactory.setTrustStorePassword(trustStorePassword); } sslContextFactory.setNeedClientAuth(mutualSsl); sslContextFactory.setExcludeCipherSuites(excludedCipherSuites); // SSL Connector ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()), new HttpConnectionFactory()); connector.setHost(address.getHostName()); connector.setPort(address.getPort()); server.addConnector(connector); }
From source file:com.jwt.security.auth.cryptographics.Crypto.java
public static String random(int length) { byte[] salt = new byte[length]; new SecureRandom().nextBytes(salt); return hex(salt); }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static ByteArrayOutputStream doGetImg(String url, String cookieStr) { InputStream in = null;/* w w w. j a va 2s .co m*/ ByteArrayOutputStream outStream = null; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setRequestProperty("Cookie", cookieStr); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); in = conn.getInputStream(); outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) != -1) { outStream.write(buffer, 0, len); } conn.disconnect(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { in.close(); } catch (Exception e) { } } return outStream; }
From source file:com.greenline.hrs.admin.util.encrypt.DESUtil.java
/** * Description ?//from ww w . j a v a 2 s . c o m * * @param data * @param key byte * @return * @throws Exception */ private static byte[] encrypt(byte[] data, byte[] key) throws GeneralSecurityException { // ???? SecureRandom sr = new SecureRandom(); // ?DESKeySpec DESKeySpec dks = new DESKeySpec(key); // ?DESKeySpec??SecretKey SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher?? Cipher cipher = Cipher.getInstance(DES); // ?Cipher cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); return cipher.doFinal(data); }
From source file:edu.utdallas.bigsecret.cipher.AesCtr.java
/** * Class constructor. Creates a Javax.Crypto.Cipher instance with AES in CTR<br> * mode, without any padding. /*from w w w .j a v a 2s.co m*/ * @param key Input key for the cipher. Should be 16, 24, or 32 bytes long * @throws Exception Throws exception if key length is not 16, 24, or 32 bytes.<br> * May throw exception based on Javax.Crypto classes. */ public AesCtr(byte[] key) throws Exception { //use default constructor for cipher.Cipher super(); //check if input key is ok if (key.length != 16 && key.length != 24 && key.length != 32) { throw new Exception("Key length should be 16, 24, or 32 bytes long"); } //set key length KEY_SIZE_BYTES = key.length; //create secret key spec instance m_keySpec = new SecretKeySpec(key, "AES"); //create cipher instance m_cipher = javax.crypto.Cipher.getInstance("AES/CTR/NoPadding"); //create secure random number generator instance m_secureRandom = new SecureRandom(); }
From source file:org.apache.falcon.request.BaseRequest.java
public static SSLContext getSslContext() throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { TrustManagerUtils.getValidateServerCertificateTrustManager() }, new SecureRandom()); return sslContext; }
From source file:com.jaspersoft.jasperserver.jaxrs.client.core.SessionStorage.java
private void initSSL(ClientBuilder clientBuilder) { try {/*from w w w . j av a 2s .c o m*/ SSLContext sslContext = SSLContext.getInstance("SSL"); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; sslContext.init(null, configuration.getTrustManagers(), new SecureRandom()); clientBuilder.sslContext(sslContext); clientBuilder.hostnameVerifier(hostnameVerifier); } catch (Exception e) { log.error("Unable inFolder init SSL context", e); throw new RuntimeException("Unable inFolder init SSL context", e); } }
From source file:org.cloudfoundry.identity.uaa.login.feature.CreateAccountIT.java
@Test public void testUserInitiatedSignup() throws Exception { String userEmail = "user" + new SecureRandom().nextInt() + "@example.com"; webDriver.get(baseUrl + "/"); webDriver.findElement(By.xpath("//*[text()='Create account']")).click(); Assert.assertEquals("Create your account", webDriver.findElement(By.tagName("h1")).getText()); int receivedEmailSize = simpleSmtpServer.getReceivedEmailSize(); webDriver.findElement(By.name("email")).sendKeys(userEmail); webDriver.findElement(By.name("password")).sendKeys("secret"); webDriver.findElement(By.name("password_confirmation")).sendKeys("secret"); webDriver.findElement(By.xpath("//input[@value='Send activation link']")).click(); Assert.assertEquals(receivedEmailSize + 1, simpleSmtpServer.getReceivedEmailSize()); Iterator receivedEmail = simpleSmtpServer.getReceivedEmail(); SmtpMessage message = (SmtpMessage) receivedEmail.next(); receivedEmail.remove();/*from w ww. j a v a 2 s . co m*/ Assert.assertEquals(userEmail, message.getHeaderValue("To")); Assert.assertThat(message.getBody(), containsString("Activate your account")); Assert.assertEquals("Create your account", webDriver.findElement(By.tagName("h1")).getText()); Assert.assertEquals("Please check email for an activation link.", webDriver.findElement(By.cssSelector(".instructions-sent")).getText()); String link = testClient.extractLink(message.getBody()); assertFalse(isEmpty(link)); webDriver.get(link); Assert.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(); Assert.assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), containsString("Where to?")); }
From source file:com.thoughtworks.go.security.CipherProvider.java
private byte[] generateKey() { SecureRandom random = new SecureRandom(); random.setSeed("go-server".getBytes()); KeyGenerationParameters generationParameters = new KeyGenerationParameters(random, DESParameters.DES_KEY_LENGTH * 8); DESKeyGenerator generator = new DESKeyGenerator(); generator.init(generationParameters); return Hex.encode(generator.generateKey()); }
From source file:dk.netarkivet.harvester.harvesting.MetadataFileWriterTester.java
public void testMetadataFileWriterArc() { File metafile = new File("metadata.arc"); MetadataFileWriter mdfw = MetadataFileWriterArc.createWriter(metafile); String uri = "http://www.netarkivet.dk/"; long ctm = System.currentTimeMillis(); SecureRandom random = new SecureRandom(); byte[] payload = new byte[8192]; random.nextBytes(payload);/*from w ww . j a v a 2 s. c o m*/ try { mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail("Unexpected exception!"); } metafile.deleteOnExit(); File metadataArcFile = new File(TestInfo.WORKING_DIR, "42-metadata-1.arc"); MetadataFileWriter mfwa = MetadataFileWriterArc.createWriter(metadataArcFile); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }