生成密碼隨機資料

要生成加密隨機資料的樣本:

final byte[] sample = new byte[16];

new SecureRandom().nextBytes(sample);

System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));

產生的輸出類似於:

Sample: E4F14CEA2384F70B706B53A6DF8C5EFE

注意,根據所使用的演算法,對 nextBytes() 的呼叫可能會阻塞,同時收集熵。

要指定演算法和提供程式:

final byte[] sample = new byte[16];
final SecureRandom randomness = SecureRandom.getInstance("SHA1PRNG", "SUN");

randomness.nextBytes(sample);

System.out.println("Provider: " + randomness.getProvider());
System.out.println("Algorithm: " + randomness.getAlgorithm());
System.out.println("Sample: " + DatatypeConverter.printHexBinary(sample));

產生的輸出類似於:

Provider: SUN version 1.8
Algorithm: SHA1PRNG
Sample: C80C44BAEB352FD29FBBE20489E4C0B9