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.hadoop.hbase.io.hfile.TestHFileBlock.java

static int writeTestKeyValues(HFileBlock.Writer hbw, int seed, boolean includesMemstoreTS, boolean useTag)
        throws IOException {
    List<KeyValue> keyValues = new ArrayList<KeyValue>();
    Random randomizer = new Random(42l + seed); // just any fixed number

    // generate keyValues
    for (int i = 0; i < NUM_KEYVALUES; ++i) {
        byte[] row;
        long timestamp;
        byte[] family;
        byte[] qualifier;
        byte[] value;

        // generate it or repeat, it should compress well
        if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
            row = keyValues.get(randomizer.nextInt(keyValues.size())).getRow();
        } else {/*w  w w . j  a va2 s .com*/
            row = new byte[FIELD_LENGTH];
            randomizer.nextBytes(row);
        }
        if (0 == i) {
            family = new byte[FIELD_LENGTH];
            randomizer.nextBytes(family);
        } else {
            family = keyValues.get(0).getFamily();
        }
        if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
            qualifier = keyValues.get(randomizer.nextInt(keyValues.size())).getQualifier();
        } else {
            qualifier = new byte[FIELD_LENGTH];
            randomizer.nextBytes(qualifier);
        }
        if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
            value = keyValues.get(randomizer.nextInt(keyValues.size())).getValue();
        } else {
            value = new byte[FIELD_LENGTH];
            randomizer.nextBytes(value);
        }
        if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) {
            timestamp = keyValues.get(randomizer.nextInt(keyValues.size())).getTimestamp();
        } else {
            timestamp = randomizer.nextLong();
        }
        if (!useTag) {
            keyValues.add(new KeyValue(row, family, qualifier, timestamp, value));
        } else {
            keyValues.add(new KeyValue(row, family, qualifier, timestamp, value,
                    new Tag[] { new Tag((byte) 1, Bytes.toBytes("myTagVal")) }));
        }
    }

    // sort it and write to stream
    int totalSize = 0;
    Collections.sort(keyValues, KeyValue.COMPARATOR);

    for (KeyValue kv : keyValues) {
        totalSize += kv.getLength();
        if (includesMemstoreTS) {
            long memstoreTS = randomizer.nextLong();
            kv.setMvccVersion(memstoreTS);
            totalSize += WritableUtils.getVIntSize(memstoreTS);
        }
        hbw.write(kv);
    }
    return totalSize;
}

From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java

public Settings() {
    try {/*from  ww w  .ja va2 s . c  om*/
        String parentClass = new Exception().getStackTrace()[1].getClassName();
        this.prefs = Preferences.userNodeForPackage(Class.forName(parentClass));
        Random r = new SecureRandom();

        //Set IV
        this.iv = prefs.getByteArray("DRUGS", null);

        //Pick Random PWD
        byte[] b = new byte[128];
        r.nextBytes(b);
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        sha.update(b);
        String sHash = new String(Base64.encodeBase64(sha.digest()));

        String password = prefs.get("LAYOUT", sHash);
        if (password.equals(sHash))
            prefs.put("LAYOUT", sHash);

        //Keep 'em Guessing
        r.nextBytes(b);
        sha.update(b);
        prefs.put("PASSWORD", new String(Base64.encodeBase64(sha.digest())));

        //Set Random Salt
        byte[] tSalt = new byte[8];
        r.nextBytes(tSalt);
        byte[] salt = prefs.getByteArray("HIMALAYAN", tSalt);
        if (Arrays.equals(salt, tSalt))
            prefs.putByteArray("HIMALAYAN", salt);

        /* Derive the key, given password and salt. */
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128);
        SecretKey tmp = factory.generateSecret(spec);
        this.secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(RSAx509CertGen.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:it.jnrpe.net.JNRPEProtocolPacket.java

/**
 * Initializes the arrays with random data. Not sure it is really needed...
 *///  ww w .  j a  v a  2 s.c  o m
private void initRandomBuffer() {
    Random rnd = new Random(System.currentTimeMillis());

    rnd.nextBytes(byteBufferAry);
    rnd.nextBytes(dummyBytesAry);
}

From source file:org.standard.bestpratice.security.Secure.java

public void encodeRampartNonce() {
    Random random = null;
    try {//from  w  ww .j av a  2s  .  com
        random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
    } catch (final NoSuchAlgorithmException ex) {
        LOG.error("Sha 1 not find", ex);
    }
    final byte[] r = new byte[16];
    random.nextBytes(r);
    String nonceBase64 = Base64.encodeBase64String(r);

    LOG.debug(r.toString());
    nonceBase64 = nonceBase64.replaceAll("[\r\n]+", "");
    LOG.debug(nonceBase64);
    LOG.debug("saut de ligne");
    //dHxHn8NcEjzaQ4KQX6j27Q==
    //ZlMIni/fEyY4qpBCJXAIxQ==
    //tAzmLb8dbvHtHARq1EF5OQ==
    //0BoFd08zqh1z8htR9WqtrUCayXY=
}

From source file:org.apache.accumulo.test.UserCompactionStrategyIT.java

void writeRandomValue(Connector c, String tableName, int size) throws Exception {
    Random rand = new Random();

    byte data1[] = new byte[size];
    rand.nextBytes(data1);

    BatchWriter bw = c.createBatchWriter(tableName, new BatchWriterConfig());

    Mutation m1 = new Mutation("r" + rand.nextInt(909090));
    m1.put("data", "bl0b", new Value(data1));

    bw.addMutation(m1);//from  www.  j a v a  2s .  co  m
    bw.close();
    c.tableOperations().flush(tableName, null, null, true);
}

From source file:org.apache.hadoop.hbase.regionserver.throttle.TestFlushWithThroughputController.java

private Store generateAndFlushData() throws IOException {
    HBaseAdmin admin = TEST_UTIL.getHBaseAdmin();
    if (admin.tableExists(tableName)) {
        admin.disableTable(tableName);//w  w w  .j av  a 2s.  c o  m
        admin.deleteTable(tableName);
    }
    Table table = TEST_UTIL.createTable(tableName, family);
    Random rand = new Random();
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            byte[] value = new byte[256 * 1024];
            rand.nextBytes(value);
            table.put(new Put(Bytes.toBytes(i * 10 + j)).addColumn(family, qualifier, value));
        }
        admin.flush(tableName);
    }
    return getStoreWithName(tableName);
}

From source file:org.jbpm.mock.EsbActionHandler.java

public void execute(ExecutionContext executionContext) {
    log.debug("invoking " + esbCategoryName + "::" + esbServiceName);
    try {//from  w  w w.  j ava  2s.  c o  m
        for (Iterator i = bpmToEsbVars.elementIterator(); i.hasNext();) {
            Element bpmToEsbVar = (Element) i.next();
            String var = bpmToEsbVar.attributeValue("bpm");
            Object value = executionContext.getVariable(var);
            log.debug("read " + value + " from variable " + var);
        }
        Random random = new Random();
        for (Iterator i = esbToBpmVars.elementIterator(); i.hasNext();) {
            Element esbToBpmVar = (Element) i.next();
            String var = esbToBpmVar.attributeValue("bpm");
            byte[] value = new byte[random.nextInt(2048)];
            random.nextBytes(value);
            executionContext.setVariable(var, value);
            log.debug("wrote " + value.length + " bytes to variable " + var);
        }
        executionContext.leaveNode();
    } catch (RuntimeException e) {
        if (DbPersistenceService.isPersistenceException(e))
            throw e;
        log.debug("possibly recoverable exception in esb action", e);
        executionContext.leaveNode(exceptionTransition);
    }
}

From source file:org.broadinstitute.gatk.utils.io.IOUtilsUnitTest.java

private byte[] getDeterministicRandomData(int size) {
    Utils.resetRandomGenerator();/*from www.ja v  a 2s .  com*/
    Random rand = Utils.getRandomGenerator();

    byte[] randomData = new byte[size];
    rand.nextBytes(randomData);

    return randomData;
}

From source file:com.palantir.atlasdb.schema.stream.StreamTest.java

private long storeAndCheckExpiringByteStreams(int size) throws IOException {
    final byte[] bytesToStore = new byte[size];
    Random rand = new Random();
    rand.nextBytes(bytesToStore);

    final long id = timestampService.getFreshTimestamp();
    StreamTestWithHashStreamStore store = StreamTestWithHashStreamStore.of(txManager,
            StreamTestTableFactory.of());
    store.storeStream(id, new ByteArrayInputStream(bytesToStore), 5, TimeUnit.SECONDS);

    verifyLoadingStreams(id, bytesToStore, store);

    return id;//from  w w  w. j  a  va2  s  .c om
}

From source file:org.openacs.HostsBean.java

public void RequestConnectionUDP(String url, String user, String pass) throws Exception {
    DatagramSocket s = new DatagramSocket(null);
    s.setReuseAddress(true);/*from  w w w .j av a 2s.  c o m*/
    s.bind(new InetSocketAddress(Application.getSTUNport()));
    String ts = Long.toString(Calendar.getInstance().getTimeInMillis());
    String id = ts;
    Random rnd = new Random();
    byte[] nonceArray = new byte[16];
    rnd.nextBytes(nonceArray);

    String cn = cvtHex.cvtHex(nonceArray);
    url = url.substring(6);
    String[] u = url.split(":");

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    String data = ts + id + user + cn;
    byte[] rawHmac = mac.doFinal(data.getBytes());
    String signature = cvtHex.cvtHex(rawHmac);
    String req = "GET http://" + url + "?ts=" + ts + "&id=" + id + "&un=" + user + "&cn=" + cn + "&sig="
            + signature + " HTTP/1.1\r\n\r\n";

    byte[] breq = req.getBytes();
    DatagramPacket packet = new DatagramPacket(breq, breq.length);
    packet.setAddress(InetAddress.getByName(u[0]));
    packet.setPort(Integer.parseInt(u[1]));
    s.send(packet);
}