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 securerandom
SecureRandom rndm = new SecureRandom();
//create byte array
byte bytes[] = new byte[40];
//generate random bytes
rndm.nextBytes(bytes);
//display the byte array
System.out.println(Arrays.toString(bytes));
}
}

Explanation

  • Line 8: We create an instance of the SecureRandom class and assign it to variable, rndm.
  • Line 11: We declare and initialize the empty byte array, bytes[], with size as 40.
  • 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.

Copyright ©2024 Educative, Inc. All rights reserved