SecureRandom nextBytes() method in Java


The number of random bytes as specified by the user can be obtained using the nextBytes() method in the class java.security.SecureRandom. This method requires a single parameter i.e. a random byte array and it returns the random bytes as specified by the user.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.security.*;
import java.util.*;
public class Demo {
   public static void main(String[] argv) {
      try {
         SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
         String s = "Apple";
         byte[] arrB = s.getBytes();
         System.out.println("The Byte array before the operation is: " + Arrays.toString(arrB));
         sRandom.nextBytes(arrB);
         System.out.println("The Byte array after the operation is: " + Arrays.toString(arrB));
      } catch (NoSuchAlgorithmException e) {
         System.out.println("Error!!! NoSuchAlgorithmException");
      } catch (ProviderException e) {
         System.out.println("Error!!! ProviderException");
      }
   }
}

Output

The Byte array before the operation is: [65, 112, 112, 108, 101]
The Byte array after the operation is: [110, -119, -65, -84, 54]

Now let us understand the above program.

The nextBytes() method is used to obtain the number of random bytes as specified by the user.

Using this, the byte array before and after the operation is displayed. A code snippet that demonstrates is given as follows −

try {
    SecureRandom sRandom = SecureRandom.getInstance("SHA1PRNG");
    String s = "Apple";
    byte[] arrB = s.getBytes();
    System.out.println("The Byte array before the operation is: " + Arrays.toString(arrB));
    sRandom.nextBytes(arrB);
    System.out.println("The Byte array after the operation is: " + Arrays.toString(arrB));
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements