List of usage examples for java.util Random nextBytes
public void nextBytes(byte[] bytes)
From source file:de.tavendo.autobahn.WebSocketConnection.java
/** * Create new key for WebSockets handshake. * * @return WebSockets handshake key (Base64 encoded). *///from ww w .j a v a2 s . c o m private String newHandshakeKey() { final Random mRng = new Random(); final byte[] ba = new byte[16]; mRng.nextBytes(ba); return Base64.encodeToString(ba, Base64.NO_WRAP); }
From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java
/** * Checks the revocation status of 'cert'; first by sending on OCSP request. If that fails for any reason, then through a CRL *///from w w w . ja va 2 s . c o m @Override public void check(Certificate cert, Collection<String> unresolvedCritExts) throws CertPathValidatorException { clearResult(); Certificate cacert = getCaCert(cert); if (cacert == null) { final String msg = "No issuer CA certificate was found. An issuer CA certificate is needed to create an OCSP request and to get the right CRL"; log.info(msg); throw new CertPathValidatorException(msg); } ArrayList<String> ocspurls = getOcspUrls(cert); if (!ocspurls.isEmpty()) { BigInteger certSerialnumber = CertTools.getSerialNumber(cert); byte[] nonce = new byte[16]; final Random randomSource = new Random(); randomSource.nextBytes(nonce); OCSPReq req = null; try { req = getOcspRequest(cacert, certSerialnumber, nonce); } catch (CertificateEncodingException | OCSPException e) { if (log.isDebugEnabled()) { log.debug("Failed to create OCSP request. " + e.getLocalizedMessage()); } fallBackToCrl(cert, CertTools.getSubjectDN(cacert)); return; } SingleResp ocspResp = null; for (String url : ocspurls) { ocspResp = getOCSPResponse(url, req, cert, nonce, OCSPRespBuilder.SUCCESSFUL, 200); if (ocspResp != null) { log.info("Obtained OCSP response from " + url); break; } else { if (log.isDebugEnabled()) { log.debug("Failed to obtain an OCSP reponse from " + url); } } } if (ocspResp == null) { log.info( "Failed to check certificate revocation status using OCSP. Falling back to check using CRL"); fallBackToCrl(cert, CertTools.getSubjectDN(cacert)); } else { CertificateStatus status = ocspResp.getCertStatus(); this.ocspResponse = ocspResp; if (log.isDebugEnabled()) { log.debug("The certificate status is: " + (status == null ? "Good" : status.toString())); } if (status != null) { // status==null -> certificate OK throw new CertPathValidatorException("Certificate with serialnumber " + CertTools.getSerialNumberAsString(cert) + " was revoked"); } if (unresolvedCritExts != null) { unresolvedCritExts.remove(Extension.authorityInfoAccess.getId()); } } } else { fallBackToCrl(cert, CertTools.getSubjectDN(cacert)); if (unresolvedCritExts != null) { unresolvedCritExts.remove(Extension.cRLDistributionPoints.getId()); } } }
From source file:edu.unc.lib.dl.admin.collect.DepositBinCollectorTest.java
private void populateFile(File file, long numberBytes) throws Exception { int byteLength = 512; Random random = new Random(); long bytesRemaining = numberBytes; try (OutputStream fos = new FileOutputStream(file)) { for (; bytesRemaining > byteLength; bytesRemaining = bytesRemaining - byteLength) { byte bytes[] = new byte[byteLength]; random.nextBytes(bytes); fos.write(bytes);//from www. ja v a 2 s . com } if (bytesRemaining > 0) { byte bytes[] = new byte[(int) bytesRemaining]; random.nextBytes(bytes); fos.write(bytes); } } }
From source file:jetbrains.buildServer.clouds.azure.connector.AzureApiConnector.java
public AzureApiConnector(@NotNull final String subscriptionId, @NotNull final String managementCertificate) throws InvalidCertificateException { mySubscriptionId = subscriptionId;/*w w w . jav a 2 s .c o m*/ myKeyStoreType = KeyStoreType.pkcs12; FileOutputStream fOut; final String base64pw; final File tempFile; try { tempFile = File.createTempFile("azk", null); fOut = new FileOutputStream(tempFile); Random r = new Random(); byte[] pwdData = new byte[4]; r.nextBytes(pwdData); base64pw = Base64.encode(pwdData).substring(0, 6); } catch (IOException e) { LOG.warn("An exception while trying to create an API connector", e); throw new RuntimeException(e); } try { createKeyStorePKCS12(managementCertificate, fOut, base64pw); } catch (Exception e) { throw new InvalidCertificateException(e); } initClient(tempFile, base64pw); }
From source file:com.google.cloud.dataflow.sdk.io.CompressedSourceTest.java
/** * Generate byte array of given size./*w ww .ja va 2 s. co m*/ */ private byte[] generateInput(int size) { // Arbitrary but fixed seed Random random = new Random(285930); byte[] buff = new byte[size]; random.nextBytes(buff); return buff; }
From source file:org.apache.flink.runtime.state.DuplicatingCheckpointOutputStreamTest.java
/** * Test that all writes are duplicated to both streams and that the state reflects what was written. */// ww w . ja v a2 s. co m @Test public void testDuplicatedWrite() throws Exception { int streamCapacity = 1024 * 1024; TestMemoryCheckpointOutputStream primaryStream = new TestMemoryCheckpointOutputStream(streamCapacity); TestMemoryCheckpointOutputStream secondaryStream = new TestMemoryCheckpointOutputStream(streamCapacity); TestMemoryCheckpointOutputStream referenceStream = new TestMemoryCheckpointOutputStream(streamCapacity); DuplicatingCheckpointOutputStream duplicatingStream = new DuplicatingCheckpointOutputStream(primaryStream, secondaryStream, 64); Random random = new Random(42); for (int i = 0; i < 500; ++i) { int choice = random.nextInt(3); if (choice == 0) { int val = random.nextInt(); referenceStream.write(val); duplicatingStream.write(val); } else { byte[] bytes = new byte[random.nextInt(128)]; random.nextBytes(bytes); if (choice == 1) { referenceStream.write(bytes); duplicatingStream.write(bytes); } else { int off = bytes.length > 0 ? random.nextInt(bytes.length) : 0; int len = bytes.length > 0 ? random.nextInt(bytes.length - off) : 0; referenceStream.write(bytes, off, len); duplicatingStream.write(bytes, off, len); } } Assert.assertEquals(referenceStream.getPos(), duplicatingStream.getPos()); } StreamStateHandle refStateHandle = referenceStream.closeAndGetHandle(); StreamStateHandle primaryStateHandle = duplicatingStream.closeAndGetPrimaryHandle(); StreamStateHandle secondaryStateHandle = duplicatingStream.closeAndGetSecondaryHandle(); Assert.assertTrue(CommonTestUtils.isSteamContentEqual(refStateHandle.openInputStream(), primaryStateHandle.openInputStream())); Assert.assertTrue(CommonTestUtils.isSteamContentEqual(refStateHandle.openInputStream(), secondaryStateHandle.openInputStream())); refStateHandle.discardState(); primaryStateHandle.discardState(); secondaryStateHandle.discardState(); }
From source file:info.jtrac.JtracImpl.java
/** * this has not been factored into the util package or a helper class * because it depends on the PasswordEncoder configured *///w ww . ja v a 2s.c om public String generatePassword() { byte[] ab = new byte[1]; Random r = new Random(); r.nextBytes(ab); return passwordEncoder.encodePassword(new String(ab), null).substring(24); }
From source file:org.mn.z80util.testbench.MZ80TestBench.java
public void run() { /*//ww w. j ava 2 s . c o m * 0x00-0xff Normal commands. * 0x100-0x1ff IX-prefixed commands. * 0x200-0x2ff IY-prefixed commands. * 0x300-0x3ff CBh-prefixed commands. * 0x400-0x4ff IX/CBh * 0x500-0x5ff IY/CBh * 0x600-0x6ff EDh-prefixed commands. */ for (cmdno = 0x00; cmdno < 0x6c0; cmdno++) { commandselect: { /* Omissions */ switch (cmdno) { case 0xcb: case 0xdd: case 0xed: case 0xfd: case 0x1cb: case 0x1dd: case 0x1ed: case 0x1fd: case 0x2cb: case 0x2dd: case 0x2ed: case 0x2fd: case 0x65f: // to avoid messing with R-register case 0x677: case 0x67f: break commandselect; } /* To avoid illegal EDh zeroth page */ if ((cmdno >= 0x600) && (cmdno < 0x640)) { break commandselect; } /* To avoid illegal commands on EDh second page */ if ((cmdno >= 0x680) && (cmdno < 0x6c0) && (((cmdno & 7) >= 4) || (((cmdno & 0070) >> 3) < 4))) { break commandselect; } for (int j = 0; j < sameCommandRounds; j++) { byte[] memory = ula.getMemory(); Random rand = new Random(System.nanoTime()); rand.nextBytes(memory); processor1.reset(); processor1.setRegPair(TestZ80.PC, (short) 0x8000); processor1.setRegPair(TestZ80.SP, (short) 0x7ffe); /* Sets up the command to be tested. */ if (cmdno < 0x100) { ula.setByte((short) 0x8000, (byte) cmdno); } else if (cmdno < 0x200) { ula.setByte((short) 0x8000, (byte) 0xdd); ula.setByte((short) 0x8001, (byte) cmdno); } else if (cmdno < 0x300) { ula.setByte((short) 0x8000, (byte) 0xfd); ula.setByte((short) 0x8001, (byte) cmdno); } else if (cmdno < 0x400) { ula.setByte((short) 0x8000, (byte) 0xcb); ula.setByte((short) 0x8001, (byte) cmdno); } else if (cmdno < 0x500) { ula.setByte((short) 0x8000, (byte) 0xdd); ula.setByte((short) 0x8001, (byte) 0xcb); ula.setByte((short) 0x8003, (byte) cmdno); } else if (cmdno < 0x600) { ula.setByte((short) 0x8000, (byte) 0xfd); ula.setByte((short) 0x8001, (byte) 0xcb); ula.setByte((short) 0x8003, (byte) cmdno); } else { ula.setByte((short) 0x8000, (byte) 0xed); ula.setByte((short) 0x8001, (byte) cmdno); } dar = Disassembler.disassemble(ula.getMemory(), (short) 0x8000); /* Takes snapshot as this setup is to be applied to the other * processor also. */ byte[] initialBackup = createSnap(processor1, ula); /* Executes the command on both processors and collects results. */ processor1.setHaltState(false); processor1.executeNextCommand(); result1 = createSnap(processor1, ula); applySnap(initialBackup, processor2, ula); processor2.setHaltState(false); processor2.executeNextCommand(); result2 = createSnap(processor2, ula); if (wantGui) { reportResultsToGUI(); } else { reportResults(); } if (fail_this) { return; } } // for j=... } // commandselect switch ((cmdno & 0x700) >> 8) { case 0: msgString = "Testing normal commands"; break; case 1: msgString = "Testing IX-prefixed commands."; break; case 2: msgString = "Testing IY-prefixed commands."; break; case 3: msgString = "Testing CBh-prefixed commands."; break; case 4: msgString = "Testing IX-CBh-prefixed commands."; break; case 5: msgString = "Testing IY-CBh-prefixed commands."; break; case 6: msgString = "Testing EDh-prefixed commands."; break; } if (wantGui) { SwingUtilities.invokeLater(new Runnable() { public void run() { progressBar.setValue(cmdno); statusMessage.setText(msgString); } }); } else if ((cmdno & 7) == 0) { if ((cmdno & 0xff) == 0) { System.out.println(); System.out.println(msgString); } System.out.print("."); } } // for cmdno=... if (wantGui) { SwingUtilities.invokeLater(new Runnable() { public void run() { statusMessage.setText("Processors are compatible with each other."); okCancelButton.setText("OK"); } }); } else { System.out.println("\nOK."); } }
From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java
/** * Creates a new Cryptor with the given PRNG.<br/> * <strong>DO NOT USE IN PRODUCTION</strong>. This constructor must only be used in in unit tests. Do not change method visibility. * //from w w w. jav a 2s. co m * @param prng Fast, possibly insecure PRNG. */ Aes256Cryptor(Random prng) { byte[] bytes = new byte[AES_KEY_LENGTH_IN_BITS / Byte.SIZE]; try { prng.nextBytes(bytes); this.primaryMasterKey = new SecretKeySpec(bytes, AES_KEY_ALGORITHM); prng.nextBytes(bytes); this.hMacMasterKey = new SecretKeySpec(bytes, HMAC_KEY_ALGORITHM); } finally { Arrays.fill(bytes, (byte) 0); } }
From source file:org.apache.jackrabbit.core.data.TestCaseBase.java
/** * Test {@link MultiDataStoreAware#deleteRecord(DataIdentifier)}. *//*from w w w. ja v a 2 s. c om*/ protected void doDeleteRecordTest() throws Exception { ds = createDataStore(); Random random = randomGen; byte[] data1 = new byte[dataLength]; random.nextBytes(data1); DataRecord rec1 = ds.addRecord(new ByteArrayInputStream(data1)); byte[] data2 = new byte[dataLength]; random.nextBytes(data2); DataRecord rec2 = ds.addRecord(new ByteArrayInputStream(data2)); byte[] data3 = new byte[dataLength]; random.nextBytes(data3); DataRecord rec3 = ds.addRecord(new ByteArrayInputStream(data3)); ds.deleteRecord(rec2.getIdentifier()); assertNull("rec2 should be null", ds.getRecordIfStored(rec2.getIdentifier())); assertEquals(new ByteArrayInputStream(data1), ds.getRecord(rec1.getIdentifier()).getStream()); assertEquals(new ByteArrayInputStream(data3), ds.getRecord(rec3.getIdentifier()).getStream()); ds.close(); }