List of usage examples for java.security SecureRandom SecureRandom
public SecureRandom()
From source file:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {/*from w ww .j ava2s . c o m*/ Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; // agent.get() // agent.get() SSLContext sslContext = SSLContext.getInstance("TLSv1"); 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); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); MechanizeAgent agent = new MechanizeAgent(); Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com"); cookie2.getHttpCookie().setPath("/"); cookie2.getHttpCookie().setSecure(false); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:com.amazon.alexa.avs.auth.companionapp.CodeChallengeWorkflow.java
/** * As per Proof Key/SPOP protocol Version 10 * @return a random 32 sized octet sequence from allowed range *///from ww w . jav a 2s . c o m private byte[] generateRandomOctetSequence() { SecureRandom random = new SecureRandom(); byte[] octetSequence = new byte[32]; random.nextBytes(octetSequence); return octetSequence; }
From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java
private SSLConnectionSocketFactory getInsecureSSLSocketFactory() { if (insecureSSLSocketFactory == null) { SSLContext sc;// ww w . j a v a 2s . co m try { sc = SSLContext.getInstance("SSL"); sc.init(null, INSECURE_TRUST_MANAGERS, new SecureRandom()); insecureSSLSocketFactory = new SSLConnectionSocketFactory(sc, INSECURE_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } } return insecureSSLSocketFactory; }
From source file:com.ntsync.shared.ContactGroup.java
/** * Serialize this ContactGroup for transporting to a server * /*from w w w . j av a 2s . c o m*/ * @param secret * @param pwdSaltBase64 * @return null if serializing failed. */ public byte[] toDTO(Key secret, String pwdSaltBase64) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE); AEADBlockCipher ecipher = CryptoHelper.getCipher(); byte[] iv = new byte[CryptoHelper.IV_LEN]; SecureRandom random = new SecureRandom(); StringBuilder hashValue = new StringBuilder(); hashValue.append(pwdSaltBase64); hashValue.append(title); out.write(GroupConstants.ROWID); byte[] rowId = String.valueOf(rawId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME); SyncDataHelper.writeInt(out, rowId.length); out.write(rowId); JsonFactory json = new JsonFactory(); StringWriter writer = new StringWriter(); JsonGenerator g = json.createGenerator(writer); g.writeStartObject(); writeField(g, GroupConstants.TITLE, title); writeField(g, GroupConstants.NOTES, notes); g.writeEndObject(); g.close(); String textData = writer.toString(); CryptoHelper.writeValue(secret, out, ecipher, iv, random, GroupConstants.TEXTDATA, textData); if (lastModified != null) { writeRawValue(out, GroupConstants.MODIFIED, String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } if (deleted) { writeRawValue(out, GroupConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } if (sourceId != null) { writeRawValue(out, GroupConstants.SERVERROW_ID, sourceId.getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); } MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(hashValue.toString().getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME)); byte[] hash = md.digest(); writeRawValue(out, GroupConstants.HASH, hash); return out.toByteArray(); } catch (final Exception ex) { LOG.error("Error converting ContactGroup to ByteStream: " + ex.toString(), ex); } return null; }
From source file:org.sakuli.services.forwarder.icinga2.Icinga2RestCient.java
private SSLContext getTrustEverythingSSLContext() { try {/*from w w w .jav a2 s. c o m*/ final SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }, new SecureRandom()); return sslContext; } catch (Exception e) { throw new SakuliRuntimeException("Unable to create SSL-Context", e); } }
From source file:com.greenline.hrs.admin.util.encrypt.DESUtil.java
/** * Description ?/*w w w . j a v a2 s. c o m*/ * * @param data * @param key byte * @return * @throws Exception */ private static byte[] decrypt(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.DECRYPT_MODE, securekey, sr); return cipher.doFinal(data); }
From source file:evaluation.loadGenerator.mixPacketLevelTraffic.MPL_FS_Poisson.java
public MPL_FS_Poisson(MPL_FixedScheduleLoadGenerator owner) { this.settings = owner.getSettings(); this.experimentStart = owner.getScheduler().now() + TimeUnit.SECONDS.toNanos(2); this.startOfPeriod = experimentStart; int numberOfClients = settings.getPropertyAsInt("MPL-POISSON-NUMBER_OF_CLIENTS"); String str_avgSendsPerPulse = settings.getProperty("MPL-POISSON-AVERAGE_PACKETS_PER_PULSE"); if (RandomVariable.isRandomVariable(str_avgSendsPerPulse)) { this.AVG_SENDS_PER_PERIOD = RandomVariable.createRandomVariable(str_avgSendsPerPulse); } else {//from ww w .j a v a2 s. c o m float float_avgSendsPerPulse = Float.parseFloat(str_avgSendsPerPulse); float_avgSendsPerPulse = float_avgSendsPerPulse * (float) numberOfClients; if (float_avgSendsPerPulse < 1f) this.AVG_SENDS_PER_PERIOD = new FakeRandom(1); else this.AVG_SENDS_PER_PERIOD = new FakeRandom(Math.round(float_avgSendsPerPulse)); } this.PULSE_LENGTH = (long) (settings.getPropertyAsFloat("MPL-POISSON-PULSE_LENGTH") * 1000000000f); this.random = new SecureRandom(); this.randomDataImpl = new RandomDataImpl(); this.randomDataImpl.reSeed(this.random.nextLong()); System.out.println("LOAD_GENERATOR: start at " + experimentStart); // create client owner.getLoadGenerator().commandLineParameters.gMixTool = ToolName.CLIENT; this.client = new AnonNode(owner.getLoadGenerator().commandLineParameters); int dstPort = settings.getPropertyAsInt("SERVICE_PORT1"); this.scheduleTarget = new MPL_BasicWriter(this, client.IS_DUPLEX, dstPort); // determine number of clients and lines; create ClientWrapper objects etc this.clientsArray = new MPL_ClientWrapper[numberOfClients]; CommunicationDirection cm = client.IS_DUPLEX ? CommunicationDirection.DUPLEX : CommunicationDirection.SIMPLEX_SENDER; for (int i = 0; i < numberOfClients; i++) { clientsArray[i] = new MPL_ClientWrapper(i); clientsArray[i].socket = client.createDatagramSocket(cm, true, true, client.ROUTING_MODE != RoutingMode.CASCADE); } if (client.IS_DUPLEX) { this.replyReceiver = new MPL_ReplyReceiver(clientsArray, settings); //this.replyReceiver.registerObserver(this); this.replyReceiver.start(); } }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException { secureRandom = new SecureRandom(); this.vaultPath = vaultPath; this.encryptionMode = encryptionMode; File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME); if (!headerFile.exists()) { try {/* ww w.j a va2 s .c om*/ KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(AES_KEY_SIZE_BIT); Key encryptionKey = keyGenerator.generateKey(); byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase); } catch (Exception e) { Util.log("Cannot create vault header!"); e.printStackTrace(); } } try { FileInputStream headerInputStream = new FileInputStream(headerFile); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); e.printStackTrace(); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); } catch (InvalidKeyException e) { throw new InvalidKeyException("Passphrase is wrong!"); } catch (Exception e) { Util.log("Cannot decrypt AES key"); e.printStackTrace(); } }
From source file:com.msopentech.thali.utilities.universal.HttpKeySSLSocketFactory.java
public HttpKeySSLSocketFactory(final PublicKey serverPublicKey, final KeyStore clientKeyStore, final char[] clientPassPhrase) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { super((KeyStore) null); final ThaliPublicKeyComparer thaliPublicKeyComparer = serverPublicKey == null ? null : new ThaliPublicKeyComparer(serverPublicKey); TrustManager trustManager = new X509TrustManager() { @Override/*from w ww. j a va2s .co m*/ public void checkClientTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { throw new RuntimeException( "We should not have gotten a client trusted call, authType was:" + authType); } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String authType) throws CertificateException { //TODO: We actually need to restrict authTypes to known secure ones if (serverPublicKey == null) { return; } PublicKey rootPublicKey = x509Certificates[x509Certificates.length - 1].getPublicKey(); if (thaliPublicKeyComparer.KeysEqual(rootPublicKey) == false) { throw new RuntimeException("Presented server root key does not match expected server root key"); } } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, clientPassPhrase); sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { trustManager }, new SecureRandom()); this.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); }
From source file:dk.netarkivet.harvester.harvesting.metadata.MetadataFileWriterTester.java
@Test public void testMetadataFileWriterWarc() throws IOException { File metafile = getOutputArcFile("metadata.warc"); MetadataFileWriter mdfw = MetadataFileWriterWarc.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 w w. j a v a2s. c o m mdfw.write(uri, "application/binary", "127.0.0.1", ctm, payload); mdfw.close(); metafile.deleteOnExit(); File metadataArcFile = getOutputArcFile("42-metadata-1.warc"); MetadataFileWriter mfwa = MetadataFileWriterWarc.createWriter(metadataArcFile); ((MetadataFileWriterWarc) mfwa).insertInfoRecord(new ANVLRecord()); for (File f : logsDir.listFiles()) { mfwa.writeFileTo(f, "metadata://netarkivet.dk/crawl/logs/" + f.getName(), "text/plain"); } }