Java Code Examples for java.util.Random.nextBytes()

The following are Jave code examples for showing how to use nextBytes() of the java.util.Random class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AndroidRTC   File: GlRectDrawerTest.java   View Source Code Vote up 6 votes
@Test
@SmallTest
public void testRgbRendering() {
  // Create EGL base with a pixel buffer as display output.
  final EglBase eglBase = EglBase.create(null, EglBase.CONFIG_PIXEL_BUFFER);
  eglBase.createPbufferSurface(WIDTH, HEIGHT);
  eglBase.makeCurrent();

  // Create RGB byte buffer plane with random content.
  final ByteBuffer rgbPlane = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 3);
  final Random random = new Random(SEED);
  random.nextBytes(rgbPlane.array());

  // Upload the RGB byte buffer data as a texture.
  final int rgbTexture = GlUtil.generateTexture(GLES20.GL_TEXTURE_2D);
  GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
  GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, rgbTexture);
  GLES20.glTexImage2D(GLES20.GL_TEXTURE_2D, 0, GLES20.GL_RGB, WIDTH, HEIGHT, 0, GLES20.GL_RGB,
      GLES20.GL_UNSIGNED_BYTE, rgbPlane);
  GlUtil.checkNoGLES2Error("glTexImage2D");

  // Draw the RGB frame onto the pixel buffer.
  final GlRectDrawer drawer = new GlRectDrawer();
  drawer.drawRgb(rgbTexture, RendererCommon.identityMatrix(), WIDTH, HEIGHT, 0 /* viewportX */,
      0 /* viewportY */, WIDTH, HEIGHT);

  // Download the pixels in the pixel buffer as RGBA. Not all platforms support RGB, e.g. Nexus 9.
  final ByteBuffer rgbaData = ByteBuffer.allocateDirect(WIDTH * HEIGHT * 4);
  GLES20.glReadPixels(0, 0, WIDTH, HEIGHT, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, rgbaData);
  GlUtil.checkNoGLES2Error("glReadPixels");

  // Assert rendered image is pixel perfect to source RGB.
  assertByteBufferEquals(WIDTH, HEIGHT, stripAlphaChannel(rgbaData), rgbPlane);

  drawer.release();
  GLES20.glDeleteTextures(1, new int[] {rgbTexture}, 0);
  eglBase.release();
}
 
Example 2
Project: GitHub   File: FilesSample.java   View Source Code Vote up 6 votes
public File createTempFile(String namePart, int byteSize) {
    try {
        File f = File.createTempFile(namePart, "_handled", getCacheDir());
        FileOutputStream fos = new FileOutputStream(f);
        Random r = new Random();
        byte[] buffer = new byte[byteSize];
        r.nextBytes(buffer);
        fos.write(buffer);
        fos.flush();
        fos.close();
        return f;
    } catch (Throwable t) {
        Log.e(LOG_TAG, "createTempFile failed", t);
    }
    return null;
}
 
Example 3
Project: hadoop   File: TestContainerLocalizer.java   View Source Code Vote up 6 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
static DataInputBuffer createFakeCredentials(Random r, int nTok)
      throws IOException {
    Credentials creds = new Credentials();
    byte[] password = new byte[20];
    Text kind = new Text();
    Text service = new Text();
    Text alias = new Text();
    for (int i = 0; i < nTok; ++i) {
      byte[] identifier = ("idef" + i).getBytes();
      r.nextBytes(password);
      kind.set("kind" + i);
      service.set("service" + i);
      alias.set("token" + i);
      Token token = new Token(identifier, password, kind, service);
      creds.addToken(alias, token);
    }
    DataOutputBuffer buf = new DataOutputBuffer();
    creds.writeTokenStorageToStream(buf);
    DataInputBuffer ret = new DataInputBuffer();
    ret.reset(buf.getData(), 0, buf.getLength());
    return ret;
  }
 
Example 4
Project: guava-mock   File: HashTestUtils.java   View Source Code Vote up 6 votes
private static void assertHashStringEquivalence(HashFunction hashFunction, Random random) {
  // Test that only data and data-order is important, not the individual operations.
  new EqualsTester()
      .addEqualityGroup(
          hashFunction.hashUnencodedChars("abc"),
          hashFunction.newHasher().putUnencodedChars("abc").hash(),
          hashFunction.newHasher().putUnencodedChars("ab").putUnencodedChars("c").hash(),
          hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("bc").hash(),
          hashFunction.newHasher().putUnencodedChars("a").putUnencodedChars("b")
              .putUnencodedChars("c").hash(),
          hashFunction.newHasher().putChar('a').putUnencodedChars("bc").hash(),
          hashFunction.newHasher().putUnencodedChars("ab").putChar('c').hash(),
          hashFunction.newHasher().putChar('a').putChar('b').putChar('c').hash())
      .testEquals();

  int size = random.nextInt(2048);
  byte[] bytes = new byte[size];
  random.nextBytes(bytes);
  String string = new String(bytes);
  assertEquals(hashFunction.hashUnencodedChars(string),
      hashFunction.newHasher().putUnencodedChars(string).hash());
  for (Charset charset : CHARSETS) {
    assertEquals(hashFunction.hashString(string, charset),
        hashFunction.newHasher().putString(string, charset).hash());
  }
}
 
Example 5
Project: safetynet   File: MainActivity.java   View Source Code Vote up 6 votes
private byte[] getRequestNonce() {

        String data = String.valueOf(System.currentTimeMillis());

        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[24];
        Random random = new Random();
        random.nextBytes(bytes);
        try {
            byteStream.write(bytes);
            byteStream.write(data.getBytes());
        } catch (IOException e) {
            return null;
        }

        return byteStream.toByteArray();
    }
 
Example 6
Project: java-android-websocket-client   File: WebSocketClient.java   View Source Code Vote up 6 votes
/**
 * Starts the WebSocket connection
 *
 * @throws IOException
 */
private void startConnection() throws IOException {
    bos = new BufferedOutputStream(socket.getOutputStream(), 65536);

    byte[] key = new byte[16];
    Random random = new Random();
    random.nextBytes(key);
    String base64Key = Base64.encodeBase64String(key);

    byte[] handshake = createHandshake(base64Key);
    bos.write(handshake);
    bos.flush();

    InputStream inputStream = socket.getInputStream();
    verifyServerHandshake(inputStream, base64Key);

    writerThread.start();

    notifyOnOpen();

    bis = new BufferedInputStream(socket.getInputStream(), 65536);
    read();
}
 
Example 7
Project: GDH   File: EncDecTest.java   View Source Code Vote up 6 votes
@Test
public void testEncryption2() {
    String algo = "AES/OFB/PKCS5Padding";
    byte[] iv = new byte[16];
    Random random = new SecureRandom();
    random.nextBytes(iv);

    byte[] key = new byte[16];
    random.nextBytes(key);
    SecretKey seckey = new SecretKeySpec(key, "AES");

    String dec = null;
    try {
        CipherAgent agent = new CipherAgentImpl(algo);
        byte[] enc = agent.encrypt(algo, iv, seckey);
        dec = agent.decrypt(enc, iv, seckey);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }

    Assert.assertTrue(algo.equals(dec));
}
 
Example 8
Project: PACE   File: SignedIteratorTest.java   View Source Code Vote up 5 votes
@Test
public void iteratorColVisTest() throws Exception {
  Random random = new Random();
  List<Entry<Key,Value>> entries = new ArrayList<>();

  for (int i = 0; i < 100; i++) {
    byte[] bytes = new byte[32 * 4];
    random.nextBytes(bytes);
    entries.add(new SimpleImmutableEntry<>(new Key(Arrays.copyOfRange(bytes, 0, 32), Arrays.copyOfRange(bytes, 32, 64), Arrays.copyOfRange(bytes, 64, 96),
        "secret".getBytes(VISIBILITY_CHARSET), (long) 0, false), new Value(Arrays.copyOfRange(bytes, 96, 128))));
  }

  EntrySigner signer = getSigner("config2.ini", aliceKeyContainers.get(ValueSigner.RSA_PKCS1));
  List<Entry<Key,Value>> signedEntries = new ArrayList<>(entries.size());
  for (Entry<Key,Value> entry : entries) {
    signedEntries.add(signer.sign(entry, true));
  }

  EntrySigner verifier = getSigner("config2.ini", bobKeyContainers.get(ValueSigner.RSA_PKCS1));
  Iterator<Entry<Key,Value>> entriesIterator = entries.iterator();
  SignedInlineScannerIterator signedIterator = new SignedInlineScannerIterator(signedEntries.iterator(), verifier);

  while (entriesIterator.hasNext()) {
    assertThat("should return all entries", signedIterator.hasNext(), is(true));
    assertThat("should return same entry", entriesIterator.next(), equalTo(signedIterator.next()));
  }
  assertThat("should not return any more entries", signedIterator.hasNext(), is(false));
}
 
Example 9
Project: hadoop   File: TestCheckpoint.java   View Source Code Vote up 5 votes
static void writeFile(FileSystem fileSys, Path name, int repl)
  throws IOException {
  FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf()
      .getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096),
      (short) repl, blockSize);
  byte[] buffer = new byte[TestCheckpoint.fileSize];
  Random rand = new Random(TestCheckpoint.seed);
  rand.nextBytes(buffer);
  stm.write(buffer);
  stm.close();
}
 
Example 10
Project: hadoop-oss   File: TestTFileByteArrays.java   View Source Code Vote up 5 votes
@Test
public void testFailureKeyLongerThan64K() throws IOException {
  if (skip)
    return;
  byte[] buf = new byte[64 * K + 1];
  Random rand = new Random();
  rand.nextBytes(buf);
  try {
    writer.append(buf, "valueX".getBytes());
  } catch (IndexOutOfBoundsException e) {
    // noop, expecting exceptions
  }
  closeOutput();
}
 
Example 11
Project: GitHub   File: HuffmanTest.java   View Source Code Vote up 5 votes
@Test public void roundTripForRequestAndResponse() throws IOException {
  String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (int i = 0; i < s.length(); i++) {
    assertRoundTrip(ByteString.encodeUtf8(s.substring(0, i)));
  }

  Random random = new Random(123456789L);
  byte[] buf = new byte[4096];
  random.nextBytes(buf);
  assertRoundTrip(ByteString.of(buf));
}
 
Example 12
Project: jetedge   File: ByteLimiter.java   View Source Code Vote up 5 votes
@Override
public Supplier<Byte> generateSupplier(Random random) {
    return () -> {
        byte[] bytes = new byte[1];
        random.nextBytes(bytes);
        return bytes[0];
    };
}
 
Example 13
Project: openjdk-jdk10   File: DigestMD5Base.java   View Source Code Vote up 5 votes
protected static final byte[] generateNonce() {

        // SecureRandom random = new SecureRandom();
        Random random = new Random();
        byte[] randomData = new byte[RAW_NONCE_SIZE];
        random.nextBytes(randomData);

        byte[] nonce = new byte[ENCODED_NONCE_SIZE];

        // Base64-encode bytes
        byte a, b, c;
        int j = 0;
        for (int i = 0; i < randomData.length; i += 3) {
            a = randomData[i];
            b = randomData[i+1];
            c = randomData[i+2];
            nonce[j++] = (byte)(pem_array[(a >>> 2) & 0x3F]);
            nonce[j++] = (byte)(pem_array[((a << 4) & 0x30) + ((b >>> 4) & 0xf)]);
            nonce[j++] = (byte)(pem_array[((b << 2) & 0x3c) + ((c >>> 6) & 0x3)]);
            nonce[j++] = (byte)(pem_array[c & 0x3F]);
        }

        return nonce;

        // %%% For testing using RFC 2831 example, uncomment the following 2 lines
        // System.out.println("!!!Using RFC 2831's cnonce for testing!!!");
        // return "OA6MHXh6VqTrRk".getBytes();
    }
 
Example 14
Project: openjdk-jdk10   File: Test4513830.java   View Source Code Vote up 5 votes
public boolean execute() throws Exception {
    Random rdm = new Random();
    byte[] plainText=new byte[125];
    rdm.nextBytes(plainText);

    Cipher ci = Cipher.getInstance(ALGO+"/"+MODE+"/"+PADDING, "SunJCE");

    // TEST FIX 4513830
    KeyGenerator kg = KeyGenerator.getInstance(ALGO, "SunJCE");
    kg.init(KEYSIZE*8);
    SecretKey key = kg.generateKey();

    ci.init(Cipher.DECRYPT_MODE, key);
    int recoveredTextLength = ci.getOutputSize(16);

    if (recoveredTextLength != 16) {
        throw new Exception("output size should not increase when decrypting!");
    }

    // BONUS TESTS
    // 1. call getOutputSize with various lengths and see if
    // the returned size is correct.
    for (int i=0; i<TEXTLENGTHS.length; i++) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        int cipherTextLength = ci.getOutputSize(TEXTLENGTHS[i]);
        if (cipherTextLength != 32) {
            throw new Exception("output size " + cipherTextLength
                                + " for input size " + TEXTLENGTHS[i]
                                + " when encrypting is wrong!");
        }
    }

    // passed all tests...hooray!
    return true;
}
 
Example 15
Project: openjdk-jdk10   File: ReinitMac.java   View Source Code Vote up 5 votes
@Override
public void main(Provider p) throws Exception {
    if (p.getService("Mac", "HmacMD5") == null) {
        System.out.println(p + " does not support HmacMD5, skipping");
        return;
    }
    Random random = new Random();
    byte[] data1 = new byte[10 * 1024];
    random.nextBytes(data1);
    byte[] keyData = new byte[16];
    random.nextBytes(keyData);
    SecretKeySpec key = new SecretKeySpec(keyData, "Hmac");
    Mac mac = Mac.getInstance("HmacMD5", p);
    mac.init(key);
    mac.init(key);
    mac.update(data1);
    mac.init(key);
    mac.doFinal();
    mac.doFinal();
    mac.update(data1);
    mac.doFinal();
    mac.reset();
    mac.reset();
    mac.init(key);
    mac.reset();
    mac.update(data1);
    mac.reset();

    System.out.println("All tests passed");
}
 
Example 16
Project: Wurst-MC-1.12   File: LogSpammerMod.java   View Source Code Vote up 5 votes
@Override
public void onEnable()
{
	random = new Random();
	payload = new PacketBuffer(Unpooled.buffer());
	
	byte[] rawPayload = new byte[random.nextInt(128)];
	random.nextBytes(rawPayload);
	payload.writeBytes(rawPayload);
	
	wurst.events.add(UpdateListener.class, this);
}
 
Example 17
Project: QDrill   File: TestTableGenerator.java   View Source Code Vote up 4 votes
public static void generateHBaseDataset2(HBaseAdmin admin, String tableName, int numberRegions) throws Exception {
  if (admin.tableExists(tableName)) {
    admin.disableTable(tableName);
    admin.deleteTable(tableName);
  }

  HTableDescriptor desc = new HTableDescriptor(tableName);
  desc.addFamily(new HColumnDescriptor("f"));

  if (numberRegions > 1) {
    admin.createTable(desc, Arrays.copyOfRange(SPLIT_KEYS, 0, numberRegions-1));
  } else {
    admin.createTable(desc);
  }

  HTable table = new HTable(admin.getConfiguration(), tableName);

  int rowCount = 0;
  byte[] bytes = null;
  final int numColumns = 5;
  Random random = new Random();
  int iteration = 0;
  while (rowCount < 1000) {
    char rowKeyChar = 'a';
    for (int i = 0; i < numberRegions; i++) {
      Put p = new Put((""+rowKeyChar+iteration).getBytes());
      for (int j = 1; j <= numColumns; j++) {
        bytes = new byte[5000]; random.nextBytes(bytes);
        p.add("f".getBytes(), ("c"+j).getBytes(), bytes);
      }
      table.put(p);

      ++rowKeyChar;
      ++rowCount;
    }
    ++iteration;
  }

  table.flushCommits();
  table.close();

  admin.flush(tableName);
}
 
Example 18
Project: openjdk-jdk10   File: TestCurves.java   View Source Code Vote up 4 votes
@Override
public void main(Provider p) throws Exception {
    if (p.getService("KeyAgreement", "ECDH") == null) {
        System.out.println("Not supported by provider, skipping");
        return;
    }

    if (isBadNSSVersion(p)) {
        return;
    }

    if (isBadSolarisSparc(p)) {
        return;
    }

    // Check if this is sparc for later failure avoidance.
    boolean sparc = false;
    if (props.getProperty("os.arch").equals("sparcv9")) {
        sparc = true;
        System.out.println("This is a sparcv9");
    }

    Random random = new Random();
    byte[] data = new byte[2048];
    random.nextBytes(data);

    List<ECParameterSpec> curves = getKnownCurves(p);
    for (ECParameterSpec params : curves) {
        System.out.println("Testing " + params + "...");
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", p);
        kpg.initialize(params);
        KeyPair kp1, kp2;

        kp1 = kpg.generateKeyPair();
        kp2 = kpg.generateKeyPair();

        testSigning(p, "SHA1withECDSA", data, kp1, kp2);
        // Check because Solaris ncp driver does not support these but
        // Solaris metaslot causes them to be run.
        try {
            testSigning(p, "SHA224withECDSA", data, kp1, kp2);
            testSigning(p, "SHA256withECDSA", data, kp1, kp2);
            testSigning(p, "SHA384withECDSA", data, kp1, kp2);
            testSigning(p, "SHA512withECDSA", data, kp1, kp2);
        } catch (ProviderException e) {
            if (sparc) {
                Throwable t = e.getCause();
                if (t instanceof sun.security.pkcs11.wrapper.PKCS11Exception &&
                    t.getMessage().equals("CKR_ATTRIBUTE_VALUE_INVALID")) {
                    System.out.print("-Failure not uncommon.  Probably pre-T4.");
                } else {
                    throw e;
                }
            } else {
                throw e;
            }
        }
        System.out.println();

        KeyAgreement ka1 = KeyAgreement.getInstance("ECDH", p);
        ka1.init(kp1.getPrivate());
        ka1.doPhase(kp2.getPublic(), true);
        byte[] secret1 = ka1.generateSecret();

        KeyAgreement ka2 = KeyAgreement.getInstance("ECDH", p);
        ka2.init(kp2.getPrivate());
        ka2.doPhase(kp1.getPublic(), true);
        byte[] secret2 = ka2.generateSecret();

        if (Arrays.equals(secret1, secret2) == false) {
            throw new Exception("Secrets do not match");
        }
    }

    System.out.println("OK");
}
 
Example 19
Project: hadoop   File: RandomDatum.java   View Source Code Vote up 4 votes
public RandomDatum(Random random) {
  length = 10 + (int) Math.pow(10.0, random.nextFloat() * 3.0);
  data = new byte[length];
  random.nextBytes(data);
}
 
Example 20
Project: CorePatch   File: GdiffTest.java   View Source Code Vote up 4 votes
/**
 * A test to exercise all of the data inline opcodes (commands 1..246)
 */
@Test
public void testInlineDataCommands() throws IOException {
  // We never read "input" so create an single, empty one.
  File inputFile = File.createTempFile("testExample", null);
  FileOutputStream writeInputFile = new FileOutputStream(inputFile);
  writeInputFile.close();
  RandomAccessFile readInputFile = new RandomAccessFile(inputFile, "r");

  // First 5 bytes for copying into each patch
  byte[] magicAndVersion = new byte[] {
      (byte) 0xd1, (byte) 0xff, (byte) 0xd1, (byte) 0xff, (byte) 4 };

  // Use a pseudo random source to fill each data stream differently
  Random random = new Random();

  for (int spanLength = 1; spanLength <= 246; spanLength++) {
    // Generate data array (save for later to compare against output)
    byte[] data = new byte[spanLength];
    random.setSeed(spanLength);
    random.nextBytes(data);

    // The patch will consist of the following data:
    //  magic+version
    //  command "n"
    //  "n" bytes
    //  EOF
    int patchLength = 5 + 1 + spanLength + 1;
    byte[] patch = new byte[patchLength];
    System.arraycopy(magicAndVersion, 0, patch, 0, magicAndVersion.length);
    patch[5] = (byte) spanLength;
    System.arraycopy(data, 0, patch, 6, spanLength);
    patch[6 + spanLength] = 0;  // EOF

    // Create "patch" file - this is just a stream
    ByteArrayInputStream patchStream = new ByteArrayInputStream(patch);

    // Create "output" file - this is just a stream
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);

    // Run the patch and check the output file
    long outputLength = Gdiff.patch(readInputFile, patchStream, outputStream, data.length);
    Assert.assertEquals(spanLength, outputLength);
    Assert.assertArrayEquals(data, outputStream.toByteArray());
  }
}