Friday 26 November 2021

Java: How to create an array of N random bytes

Approach 1: Using nextBytes method of Random class.

byte[] b = new byte[10];
new Random().nextBytes(b);

 

RandomByteArrayDemo1.java

package com.sample.app.arrays;

import java.util.Random;

public class RandomByteArrayDemo1 {
	
	private static void printArray(byte[] b) {
		for(byte data: b) {
			System.out.print(data + " ");
		}
	}
	
	public static void main(String args[]) {
		byte[] b = new byte[10];
		new Random().nextBytes(b);
		
		printArray(b);
	}

}

If you want to generate cryptographically non-predictable random numbers use SecureRandom class.

 

Approach 2: Using nextBytes method of SecureRandom class.

byte[] b = new byte[10];
new SecureRandom().nextBytes(b);

RandomByteArrayDemo2.java

package com.sample.app.arrays;

import java.security.SecureRandom;

public class RandomByteArrayDemo2 {
	
	private static void printArray(byte[] b) {
		for(byte data: b) {
			System.out.print(data + " ");
		}
	}
	
	public static void main(String args[]) {
		byte[] b = new byte[10];
		new SecureRandom().nextBytes(b);
		
		printArray(b);
	}

}

Approach 3: Using 'ThreadLocalRandom.current().nextBytes()' method.

byte[] b = new byte[10];
ThreadLocalRandom.current().nextBytes(b);

RandomByteArrayDemo3.java

package com.sample.app.arrays;

import java.util.concurrent.ThreadLocalRandom;

public class RandomByteArrayDemo3 {
	
	private static void printArray(byte[] b) {
		for(byte data: b) {
			System.out.print(data + " ");
		}
	}
	
	public static void main(String args[]) {
		byte[] b = new byte[10];
		ThreadLocalRandom.current().nextBytes(b);
		
		printArray(b);
	}

}



 

No comments:

Post a Comment