Code example for SecureRandom

Methods: nextBytes, setSeed

0
    private static SecureRandom randomGenerator = null;
	private boolean initialized = false;
 
    private AndroidRandomGenerator() { 
        instance = this;
        randomGenerator = new SecureRandom();
        seed(); 
    } 
 
    public static AndroidRandomGenerator getInstance() { 
        if (instance == null) {
            new AndroidRandomGenerator(); 
        } 
        return instance;
    } 
     
    @Override 
    public boolean isInitialized() { 
    	return initialized;
    } 
 
 
    /** 
     * Seed the RandomGenerator from a java.security.SecureRandom source 
     */ 
    private void seed() { 
    	byte [] initArray = new byte[64];
    	randomGenerator.nextBytes(initArray);
        seed(initArray);
    } 
 
    @Override 
    public void seedUsingPcmAudio(byte[] data) {
        byte[] key = new byte[64];
        for (int i = 0; i < key.length; i++) {
            int x = 0;
            //Pick 4 random bytes from the PCM audio data, from each of the bytes  
            //take the two least significant bits and concatenate them to form 
            //the i-th byte in the seed key 
            for (int j = 0; j < 4; j++) {
                x = (x << 2) | (3 & data[randomGenerator.nextInt(data.length)]);
            } 
            key[i] = (byte) x;
        } 
        seed(key);
        initialized = true;
    } 
 
    /** 
     * Seed the random generator with a standard 20 to 64 byte byte array. 
     * 
     * @param key The seed key to use. Note that seed.length must be between 20 
     * and 64 bytes. 
     */ 
    private void seed(byte[] key) {
    	randomGenerator.setSeed(key);
    } 
 
    @Override 
    public int getInt() { 
        byte[] rand = new byte[4];