当前位置: 首页>>代码示例>>Java>>正文


Java Random.nextBytes方法代码示例

本文整理汇总了Java中java.util.Random.nextBytes方法的典型用法代码示例。如果您正苦于以下问题:Java Random.nextBytes方法的具体用法?Java Random.nextBytes怎么用?Java Random.nextBytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Random的用法示例。


在下文中一共展示了Random.nextBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testRgbRendering

import java.util.Random; //导入方法依赖的package包/类
@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();
}
 
开发者ID:lgyjg,项目名称:AndroidRTC,代码行数:39,代码来源:GlRectDrawerTest.java

示例2: createTempFile

import java.util.Random; //导入方法依赖的package包/类
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;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:17,代码来源:FilesSample.java

示例3: createFakeCredentials

import java.util.Random; //导入方法依赖的package包/类
@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;
  }
 
开发者ID:naver,项目名称:hadoop,代码行数:24,代码来源:TestContainerLocalizer.java

示例4: assertHashStringEquivalence

import java.util.Random; //导入方法依赖的package包/类
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());
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:27,代码来源:HashTestUtils.java

示例5: getRequestNonce

import java.util.Random; //导入方法依赖的package包/类
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();
    }
 
开发者ID:Learn2Crack,项目名称:safetynet,代码行数:18,代码来源:MainActivity.java

示例6: startConnection

import java.util.Random; //导入方法依赖的package包/类
/**
 * 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();
}
 
开发者ID:gusavila92,项目名称:java-android-websocket-client,代码行数:28,代码来源:WebSocketClient.java

示例7: testEncryption2

import java.util.Random; //导入方法依赖的package包/类
@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));
}
 
开发者ID:maxamel,项目名称:GDH,代码行数:23,代码来源:EncDecTest.java

示例8: iteratorColVisTest

import java.util.Random; //导入方法依赖的package包/类
@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));
}
 
开发者ID:mit-ll,项目名称:PACE,代码行数:29,代码来源:SignedIteratorTest.java

示例9: writeFile

import java.util.Random; //导入方法依赖的package包/类
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();
}
 
开发者ID:naver,项目名称:hadoop,代码行数:12,代码来源:TestCheckpoint.java

示例10: testFailureKeyLongerThan64K

import java.util.Random; //导入方法依赖的package包/类
@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();
}
 
开发者ID:nucypher,项目名称:hadoop-oss,代码行数:15,代码来源:TestTFileByteArrays.java

示例11: roundTripForRequestAndResponse

import java.util.Random; //导入方法依赖的package包/类
@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));
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:12,代码来源:HuffmanTest.java

示例12: generateSupplier

import java.util.Random; //导入方法依赖的package包/类
@Override
public Supplier<Byte> generateSupplier(Random random) {
    return () -> {
        byte[] bytes = new byte[1];
        random.nextBytes(bytes);
        return bytes[0];
    };
}
 
开发者ID:Bekreth,项目名称:jetedge,代码行数:9,代码来源:ByteLimiter.java

示例13: generateNonce

import java.util.Random; //导入方法依赖的package包/类
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();
    }
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:DigestMD5Base.java

示例14: execute

import java.util.Random; //导入方法依赖的package包/类
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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:36,代码来源:Test4513830.java

示例15: main

import java.util.Random; //导入方法依赖的package包/类
@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");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:31,代码来源:ReinitMac.java


注:本文中的java.util.Random.nextBytes方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。