Java Tutorial/Security/Secure Random
Версия от 17:44, 31 мая 2010; (обсуждение)
Generating a Secure Random Number
import java.security.SecureRandom;
public class Main {
public static void main(String[] argv) throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[1024 / 8];
sr.nextBytes(bytes);
}
}
Secure Random Demo
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class MainClass {
public static void main(String[] args) throws NoSuchAlgorithmException {
int numBytes = (new Integer("1111")).intValue();
long seed = 01;
if (args.length > 1)
seed = (new Long("1111111111")).longValue();
SecureRandom srand = SecureRandom.getInstance("SHA1PRNG");
if (seed != 01)
srand.setSeed(seed);
byte[] bytes = new byte[numBytes];
srand.nextBytes(bytes);
System.out.println(new String(bytes));
}
}
Seed a Secure Random
import java.security.SecureRandom;
public class MainClass {
public static void main(String args[]) throws Exception {
SecureRandom ran = SecureRandom.getInstance("SHA1PRNG", "SUN");
ran.setSeed(101L);
ran.setSeed(101L);
byte[] seeds = ran.getSeed(24);
for (int i = 0; i < seeds.length; i++) {
System.out.println("Seed[" + i + "]:" + seeds[i]);
}
}
}