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:AmazonDynamoDBSample.java

private static void oneTimeAddWarrants() {

    String jsonString = "";

    try {/* w  ww.j  a  v  a2 s  . c o m*/
        jsonString = readFile("./json/warrants.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
        System.out.println(e);
    }

    try {
        JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
        JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

        //System.out.println("row lengths: " + rows.length());

        set2 = new HashSet<>();

        for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
            JSONObject element = rows.getJSONObject(j); // Get the element object

            String defendant = element.getString("Defendant");

            String strarr[] = defendant.split(" ");
            String temp = strarr[1];
            int len = strarr[0].length();
            strarr[0] = strarr[0].substring(0, len - 1);
            strarr[1] = strarr[0];
            strarr[0] = temp;

            String firstLast = strarr[0] + strarr[1];
            firstLast = firstLast.toLowerCase();

            set2.add(firstLast);
            //System.out.println(firstLast);

            int zipCode = 0;
            Boolean isZipCodeNull = element.isNull("ZIP Code");
            if (!isZipCodeNull)
                zipCode = element.getInt("ZIP Code");
            String dob = element.getString("Date of Birth");
            String caseNumber = element.getString("Case Number");

            String firstLastDOB = firstLast + dob;

            // pick a ssn from list
            String ssn = ssnList.get(ssnCounter);
            ssnCounter--;
            ssnHashMap.put(firstLast, ssn);

            // compute salt
            final Random ran = new SecureRandom();
            byte[] salt = new byte[32];
            ran.nextBytes(salt);
            String saltString = Base64.encodeBase64String(salt);

            //System.out.println("saltstring: " + saltString);
            saltHashMap.put(firstLast, saltString);

            // compute ripemd160 hash of ssn + salt
            String saltPlusSsn = saltString + ssn;
            //System.out.println("salt plus ssn: " + saltPlusSsn);

            String resultingHash = "";
            try {
                byte[] r = saltPlusSsn.getBytes("US-ASCII");
                RIPEMD160Digest d = new RIPEMD160Digest();
                d.update(r, 0, r.length);
                byte[] o = new byte[d.getDigestSize()];
                d.doFinal(o, 0);
                ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
                Hex.encode(o, baos);
                resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

                hashedssnHashMap.put(firstLast, resultingHash);
            } catch (UnsupportedEncodingException e) {
                System.out.println(e);
            } catch (IOException i) {
                System.out.println(i);
            }

            //compareNames();

            Map<String, AttributeValue> item = newWarrantItem(firstLast, firstLastDOB, resultingHash, defendant,
                    zipCode, dob, caseNumber);
            PutItemRequest putItemRequest = new PutItemRequest("warrants-table", item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);

        }
    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }
}

From source file:password.pwm.util.secure.SecureEngine.java

public static void benchmark(final Writer outputData) throws PwmUnrecoverableException, IOException {
    final int testIterations = 10 * 1000;
    final Random random = new Random();
    final byte[] noise = new byte[1024 * 10];
    final PwmSecurityKey key = new PwmSecurityKey(PwmRandom.getInstance().newBytes(1024));
    for (int i = 0; i < 10; i++) {
        for (final PwmBlockAlgorithm alg : PwmBlockAlgorithm.values()) {
            final Instant startTime = Instant.now();
            for (int j = 0; j < testIterations; j++) {
                random.nextBytes(noise);
                SecureEngine.encryptToString(JavaHelper.binaryArrayToHex(noise), key, alg);
            }/*from w w w. j  ava  2 s .  c  o m*/
            final TimeDuration executionDuration = TimeDuration.fromCurrent(startTime);
            outputData.write("processed " + testIterations + " iterations using " + alg.toString() + " ("
                    + alg.getLabel() + ") in " + executionDuration.getTotalMilliseconds() + "ms");
            outputData.write("\n");
        }
    }
}

From source file:org.apache.hadoop.yarn.util.TestFSDownload.java

static void createFile(FileContext files, Path p, int len, Random r) throws IOException {
    FSDataOutputStream out = null;/*from w  w  w  . j  av  a2 s  .co m*/
    try {
        byte[] bytes = new byte[len];
        out = files.create(p, EnumSet.of(CREATE, OVERWRITE));
        r.nextBytes(bytes);
        out.write(bytes);
    } finally {
        if (out != null)
            out.close();
    }
}

From source file:AmazonDynamoDBSample.java

private static void oneTimeAddCitations() {

    String jsonString = "";

    try {/*from  www  . j ava 2s.  com*/
        jsonString = readFile("./json/citations.json", StandardCharsets.UTF_8);
    } catch (IOException e) {
        System.out.println(e);
    }

    try {
        JSONObject rootObject = new JSONObject(jsonString); // Parse the JSON to a JSONObject
        JSONArray rows = rootObject.getJSONArray("stuff"); // Get all JSONArray rows

        System.out.println("row lengths: " + rows.length());

        set1 = new HashSet<>();

        for (int j = 0; j < rows.length(); j++) { // Iterate each element in the elements array
            JSONObject element = rows.getJSONObject(j); // Get the element object

            int id = element.getInt("id");
            int citationNumber = element.getInt("citation_number");
            String citationDate = " ";
            Boolean isCitationDateNull = element.isNull("citation_date");
            if (!isCitationDateNull)
                citationDate = element.getString("citation_date");
            String firstName = element.getString("first_name");
            String lastName = element.getString("last_name");
            String firstLastName = firstName + lastName;
            firstLastName = firstLastName.toLowerCase();
            set1.add(firstLastName);

            //System.out.println(firstLastName);
            String dob = " ";
            Boolean isDobNull = element.isNull("date_of_birth");
            if (!isDobNull) {
                dob = element.getString("date_of_birth");
                dob = (dob.split(" "))[0];
            }

            // pick a ssn from list
            String ssn = ssnList.get(ssnCounter);
            ssnCounter--;
            ssnHashMap.put(firstLastName, ssn);

            System.out.println(firstLastName + " " + ssn);

            // compute salt
            final Random ran = new SecureRandom();
            byte[] salt = new byte[32];
            ran.nextBytes(salt);
            String saltString = Base64.encodeBase64String(salt);

            //System.out.println("saltstring: " + saltString);
            saltHashMap.put(firstLastName, saltString);

            // compute ripemd160 hash of ssn + salt
            String saltPlusSsn = saltString + ssn;
            //System.out.println("salt plus ssn: " + saltPlusSsn);

            String resultingHash = "";
            try {
                byte[] r = saltPlusSsn.getBytes("US-ASCII");
                RIPEMD160Digest d = new RIPEMD160Digest();
                d.update(r, 0, r.length);
                byte[] o = new byte[d.getDigestSize()];
                d.doFinal(o, 0);
                ByteArrayOutputStream baos = new ByteArrayOutputStream(40);
                Hex.encode(o, baos);
                resultingHash = new String(baos.toByteArray(), StandardCharsets.UTF_8);

                hashedssnHashMap.put(firstLastName, resultingHash);
            } catch (UnsupportedEncodingException e) {
                System.out.println(e);
            } catch (IOException i) {
                System.out.println(i);
            }

            String fldob = firstLastName + dob;
            String da = " ";
            Boolean isDaNull = element.isNull("defendant_address");
            if (!isDaNull)
                da = element.getString("defendant_address");
            String dc = " ";
            Boolean isDcNull = element.isNull("defendant_city");
            if (!isDcNull)
                dc = element.getString("defendant_city");
            String ds = " ";
            Boolean isDsNull = element.isNull("defendant_state");
            if (!isDsNull)
                ds = element.getString("defendant_state");
            String dln = " ";
            Boolean isDlnNull = element.isNull("drivers_license_number");
            if (!isDlnNull)
                dln = element.getString("drivers_license_number");
            String cd = " ";
            Boolean isCdNull = element.isNull("court_date");
            if (!isCdNull)
                cd = element.getString("court_date");
            String cl = " ";
            Boolean isClNull = element.isNull("court_location");
            if (!isClNull)
                cl = element.getString("court_location");
            String ca = " ";
            Boolean isCaNull = element.isNull("court_address");
            if (!isCaNull)
                ca = element.getString("court_address");
            /*
            Map<String, AttributeValue> item = newCitationItem(citationNumber, citationDate, firstName, lastName, firstLastName, dob, fldob, resultingHash, da, dc, ds, dln, cd, cl, ca);
            PutItemRequest putItemRequest = new PutItemRequest("citations-table", item);
            PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
            */
        }
    } catch (JSONException e) {
        // JSON Parsing error
        e.printStackTrace();
    }
}

From source file:org.apache.hadoop.mapred.TestCombineSequenceFileInputFormat.java

private static void createFiles(int length, int numFiles, Random random) throws IOException {
    Range[] ranges = createRanges(length, numFiles, random);

    for (int i = 0; i < numFiles; i++) {
        Path file = new Path(workDir, "test_" + i + ".seq");
        // create a file with length entries
        @SuppressWarnings("deprecation")
        SequenceFile.Writer writer = SequenceFile.createWriter(localFs, conf, file, IntWritable.class,
                BytesWritable.class);
        Range range = ranges[i];//from ww w.j  a v  a2 s . c  o m
        try {
            for (int j = range.start; j < range.end; j++) {
                IntWritable key = new IntWritable(j);
                byte[] data = new byte[random.nextInt(10)];
                random.nextBytes(data);
                BytesWritable value = new BytesWritable(data);
                writer.append(key, value);
            }
        } finally {
            writer.close();
        }
    }
}

From source file:org.apache.hadoop.mapreduce.lib.input.TestCombineSequenceFileInputFormat.java

private static void createFiles(int length, int numFiles, Random random, Job job) throws IOException {
    Range[] ranges = createRanges(length, numFiles, random);

    for (int i = 0; i < numFiles; i++) {
        Path file = new Path(workDir, "test_" + i + ".seq");
        // create a file with length entries
        @SuppressWarnings("deprecation")
        SequenceFile.Writer writer = SequenceFile.createWriter(localFs, job.getConfiguration(), file,
                IntWritable.class, BytesWritable.class);
        Range range = ranges[i];//from   w w w  .j  av  a2  s  .c  o  m
        try {
            for (int j = range.start; j < range.end; j++) {
                IntWritable key = new IntWritable(j);
                byte[] data = new byte[random.nextInt(10)];
                random.nextBytes(data);
                BytesWritable value = new BytesWritable(data);
                writer.append(key, value);
            }
        } finally {
            writer.close();
        }
    }
}

From source file:org.apache.blur.shell.DiscoverFileBufferSizeUtil.java

private static long readFile(PrintWriter out, Random random, int bufSize, FSDataInputStream inputStream,
        long length, int readSamples) throws IOException {
    byte[] buf = new byte[bufSize];
    long start = System.nanoTime();
    long time = 0;
    for (int i = 0; i < readSamples; i++) {
        long now = System.nanoTime();
        if (start + 5000000000l < now) {
            double complete = (((double) i / (double) readSamples) * 100.0);
            out.println(complete + "% Complete");
            out.flush();//w ww. ja v a  2 s  . co m
            start = System.nanoTime();
        }
        random.nextBytes(buf);
        long position = getPosition(bufSize, random, length);
        long s = System.nanoTime();
        int offset = 0;
        int len = bufSize;
        while (len > 0) {
            int amount = inputStream.read(position, buf, offset, len);
            len -= amount;
            offset += amount;
            position += amount;
        }
        long e = System.nanoTime();
        time += (e - s);
        length -= len;
    }
    return time;
}

From source file:org.apache.blur.shell.DiscoverFileBufferSizeUtil.java

private static long writeFile(PrintWriter out, Random random, int bufSize, FSDataOutputStream outputStream,
        long length) throws IOException {
    byte[] buf = new byte[bufSize];
    final long origLength = length;
    long start = System.nanoTime();
    long time = 0;
    while (length > 0) {
        long now = System.nanoTime();
        if (start + 5000000000l < now) {
            double complete = ((origLength - length) / (double) origLength) * 100.0;
            out.println(complete + "% Complete");
            out.flush();/*from  www .  j  a v a 2 s. c o m*/
            start = System.nanoTime();
        }
        random.nextBytes(buf);
        int len = (int) Math.min(length, bufSize);
        long s = System.nanoTime();
        outputStream.write(buf, 0, len);
        long e = System.nanoTime();
        time += (e - s);
        length -= len;
    }
    return time;
}

From source file:com.vmware.photon.controller.deployer.helpers.TestHelper.java

public static File createSourceFile(String sourceFileName, File sourceDirectory) throws IOException {
    sourceDirectory.mkdirs();//from ww  w  .java  2  s .  c  o m

    if (sourceFileName == null) {
        sourceFileName = "esxcloud-" + UUID.randomUUID().toString() + ".vib";
    }

    File sourceFile = new File(sourceDirectory, sourceFileName);
    sourceFile.createNewFile();
    OutputStream outputStream = new FileOutputStream(sourceFile);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);

    Random random = new Random();
    byte[] randomBytes = new byte[1024];
    for (int i = 0; i < 10 * 1024; i++) {
        random.nextBytes(randomBytes);
        bufferedOutputStream.write(randomBytes);
    }

    bufferedOutputStream.close();
    outputStream.close();
    return sourceFile;
}

From source file:org.freedesktop.dbus.Transport.java

public static String genGUID() {
    Random r = new Random();
    byte[] buf = new byte[16];
    r.nextBytes(buf);
    return Hex.encodeHexString(buf);
}