What is the SecureRandom.nextBytes() method in Java?
Overview
The nextBytes() method is used to generate cryptographically strong pseudo-random bytes. This method is provided by the SecureRandom class, which consists of methods to generate strong random numbers.
Syntax
secureRandomInstnace.nextBytes(byte_array)
Parameters
This method takes a byte_array as a parameter and fills it with cryptographically strong pseudo-random bytes.
Return value
It doesn't return anything as it is an in-place operation.
Example
import java.security.*;import java.util.*;public class main {public static void main(String[] argv){//create instance of securerandomSecureRandom rndm = new SecureRandom();//create byte arraybyte bytes[] = new byte[40];//generate random bytesrndm.nextBytes(bytes);//display the byte arraySystem.out.println(Arrays.toString(bytes));}}
Explanation
- Line 8: We create an instance of the
SecureRandomclass and assign it to variable,rndm. - Line 11: We declare and initialize the empty byte array,
bytes[], with size as40. - Line 14: We call the
nextBytes()method and pass byte array as a parameter to it, to generate cryptographically strong random bytes and fills the byte array,bytes[]. - Line 17: We display the byte array after filling it up with random bytes.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved