Example usage for java.util Random nextBytes

List of usage examples for java.util Random nextBytes

Introduction

In this page you can find the example usage for java.util Random nextBytes.

Prototype

public void nextBytes(byte[] bytes) 

Source Link

Document

Generates random bytes and places them into a user-supplied byte array.

Usage

From source file:org.apache.accumulo.server.test.TestIngest.java

public static byte[] genRandomValue(Random random, byte dest[], int seed, int row, int col) {
    random.setSeed((row ^ seed) ^ col);/*w w w  .  j av a2  s.c o  m*/
    random.nextBytes(dest);
    toPrintableChars(dest);

    return dest;
}

From source file:jBittorrentAPI.utils.Utils.java

/**
 * Generate the client id, which is a fixed string of length 8 concatenated with 12 random bytes
 * @return byte[]//from   ww w.j  a  v  a2  s . com
 */
public static byte[] generateID() {
    byte[] id = new byte[12];

    Random r = new Random(System.currentTimeMillis());
    r.nextBytes(id);
    return Utils.concat("-UT3200-".getBytes(), id);
}

From source file:org.apache.hadoop.hdfs.DFSTestUtil.java

public static void createFile(FileSystem fs, Path fileName, long fileLen, short replFactor, long seed)
        throws IOException {
    if (!fs.mkdirs(fileName.getParent())) {
        throw new IOException("Mkdirs failed to create " + fileName.getParent().toString());
    }//  w w  w .  j a  v  a2  s. co m
    FSDataOutputStream out = null;
    try {
        out = fs.create(fileName, replFactor);
        byte[] toWrite = new byte[1024];
        Random rb = new Random(seed);
        long bytesToWrite = fileLen;
        while (bytesToWrite > 0) {
            rb.nextBytes(toWrite);
            int bytesToWriteNext = (1024 < bytesToWrite) ? 1024 : (int) bytesToWrite;

            out.write(toWrite, 0, bytesToWriteNext);
            bytesToWrite -= bytesToWriteNext;
        }
        out.close();
        out = null;
    } finally {
        IOUtils.closeStream(out);
    }
}

From source file:io.undertow.server.security.DigestAuthenticationAuthTestCase.java

private static String createNonce() {
    // This if just for testing so we are not concerned with how securely the client side nonce is.
    Random rand = new Random();
    byte[] nonceBytes = new byte[32];
    rand.nextBytes(nonceBytes);

    return HexConverter.convertToHexString(nonceBytes);
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

@BeforeClass
public static void beforeClass() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    classPath = KeyStoreTestUtil.getClasspathDir(TestHopsworksRMAppSecurityActions.class);
    byte[] jwtIssuerSecret = new byte[32];
    Random rand = new Random();
    rand.nextBytes(jwtIssuerSecret);
    jwtIssuer = new MockJWTIssuer(jwtIssuerSecret);
}

From source file:org.gradle.caching.internal.tasks.AbstractTaskOutputPackagingBenchmark.java

private static ImmutableList<DataSource> createInputFiles(int fileCount, int minFileSize, int maxFileSize,
        DataAccessor accessor) throws IOException {
    Random random = new Random(1234L);
    ImmutableList.Builder<DataSource> inputs = ImmutableList.builder();
    for (int idx = 0; idx < fileCount; idx++) {
        String name = "input-" + idx + ".bin";
        int fileSize = minFileSize + random.nextInt(maxFileSize - minFileSize);
        byte[] buffer = new byte[fileSize];
        random.nextBytes(buffer);
        DataSource input = accessor.createSource(name, buffer, Level.Trial);
        inputs.add(input);//from   w  ww  .  ja  v  a2s  . c om
    }
    return inputs.build();
}

From source file:MyServlet.UserController.java

public static String hashAndSalt(String password) throws NoSuchAlgorithmException {
    Random r = new SecureRandom();
    byte[] saltBytes = new byte[32];
    r.nextBytes(saltBytes);
    salt = Base64.encodeBase64String(saltBytes);
    return hashPassword(password + salt);
}

From source file:org.apache.hadoop.hdfs.TestLookasideCache.java

private static long createTestFile(FileSystem fileSys, Path name, int repl, int numBlocks, long blocksize)
        throws IOException {
    CRC32 crc = new CRC32();
    Random rand = new Random();
    FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf().getInt("io.file.buffer.size", 4096),
            (short) repl, blocksize);
    // fill random data into file
    final byte[] b = new byte[(int) blocksize];
    for (int i = 0; i < numBlocks; i++) {
        rand.nextBytes(b);
        stm.write(b);//from w w  w.  ja va  2 s. com
        crc.update(b);
    }
    stm.close();
    return crc.getValue();
}

From source file:org.apache.hadoop.fs.TestAppendStress.java

private static void writeToFile(Random random, FSDataOutputStream out, int len, DataChecksum checksum)
        throws IOException {
    if (len == 0) {
        return;/*from  ww  w .ja v  a  2  s.c o  m*/
    }

    LOG.info("Write " + len + " bytes to file.");
    int bufferSize = 1024 * 1024;
    byte[] buffer = new byte[bufferSize];
    int toLen = len;
    while (toLen > 0) {
        random.nextBytes(buffer);
        int numWrite = Math.min(toLen, buffer.length);
        out.write(buffer, 0, numWrite);
        checksum.update(buffer, 0, numWrite);
        toLen -= numWrite;

        // randomly do sync or not.
        if (random.nextBoolean()) {
            out.sync();
        }
    }
}

From source file:org.apache.flink.runtime.blob.BlobCacheCorruptionTest.java

/**
 * Checks the GET operation fails when the downloaded file (from {@link BlobServer} or HA store)
 * is corrupt, i.e. its content's hash does not match the {@link BlobKey}'s hash.
 *
 * @param jobId//from w  ww  . ja  v a  2 s .com
 *       job ID or <tt>null</tt> if job-unrelated
 * @param blobType
 *       whether the BLOB should become permanent or transient
 * @param corruptOnHAStore
 *       whether the file should be corrupt in the HA store (<tt>true</tt>, required
 *       <tt>highAvailability</tt> to be set) or on the {@link BlobServer}'s local store
 *       (<tt>false</tt>)
 * @param config
 *       blob server configuration (including HA settings like {@link HighAvailabilityOptions#HA_STORAGE_PATH}
 *       and {@link HighAvailabilityOptions#HA_CLUSTER_ID}) used to set up <tt>blobStore</tt>
 * @param blobStore
 *       shared HA blob store to use
 * @param expectedException
 *       expected exception rule to use
 */
private static void testGetFailsFromCorruptFile(@Nullable JobID jobId, BlobKey.BlobType blobType,
        boolean corruptOnHAStore, Configuration config, BlobStore blobStore,
        ExpectedException expectedException) throws IOException {

    assertTrue("corrupt HA file requires a HA setup", !corruptOnHAStore || blobType == PERMANENT_BLOB);

    Random rnd = new Random();

    try (BlobServer server = new BlobServer(config, blobStore);
            BlobCacheService cache = new BlobCacheService(config,
                    corruptOnHAStore ? blobStore : new VoidBlobStore(),
                    new InetSocketAddress("localhost", server.getPort()))) {

        server.start();

        byte[] data = new byte[2000000];
        rnd.nextBytes(data);

        // put content addressable (like libraries)
        BlobKey key = put(server, jobId, data, blobType);
        assertNotNull(key);

        // change server/HA store file contents to make sure that GET requests fail
        byte[] data2 = Arrays.copyOf(data, data.length);
        data2[0] ^= 1;
        if (corruptOnHAStore) {
            File tmpFile = Files.createTempFile("blob", ".jar").toFile();
            try {
                FileUtils.writeByteArrayToFile(tmpFile, data2);
                blobStore.put(tmpFile, jobId, key);
            } finally {
                //noinspection ResultOfMethodCallIgnored
                tmpFile.delete();
            }

            // delete local (correct) file on server to make sure that the GET request does not
            // fall back to downloading the file from the BlobServer's local store
            File blobFile = server.getStorageLocation(jobId, key);
            assertTrue(blobFile.delete());
        } else {
            File blobFile = server.getStorageLocation(jobId, key);
            assertTrue(blobFile.exists());
            FileUtils.writeByteArrayToFile(blobFile, data2);
        }

        // issue a GET request that fails
        expectedException.expect(IOException.class);
        expectedException.expectCause(CoreMatchers.allOf(instanceOf(IOException.class),
                hasProperty("message", containsString("data corruption"))));

        get(cache, jobId, key);
    }
}