SecureRandom nextBytes() method in Java with Examples
Last Updated :
04 Dec, 2018
The nextBytes() method of java.security.SecureRandom class is used to generate a user-specified number of random bytes.
If a call to setSeed had not occurred previously, the first call to this method forces this SecureRandom object to seed itself. This self-seeding will not occur if setSeed was previously called.
Syntax:
public void nextBytes(byte[] bytes)
Parameters: This method takes the array to be filled in with random bytes as parameter .
Note:
- The programs will not run on online IDE.
- Every time Secure Random class will generate random output.
Below are the examples to illustrate the nextBytes() method:
Example 1:
import java.security.*;
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
SecureRandom sr = SecureRandom.getInstance( "SHA1PRNG" );
String str = "Tajmahal" ;
byte [] b = str.getBytes();
System.out.println( "Byte array before operation : " + Arrays.toString(b));
sr.nextBytes(b);
System.out.println( "Byte array after operation : " + Arrays.toString(b));
}
catch (NoSuchAlgorithmException e) {
System.out.println( "Exception thrown : " + e);
}
catch (ProviderException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [-79, -110, -18, -31, -54, -36, 63, -61]
Note: The following program throws the following Exception on GeeksForGeeks IDE but it will run efficiently on any Command Prompt(JDK)
Exception thrown : java.security.ProviderException: init failed
Example 2:
import java.security.*;
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
{
try {
SecureRandom sr = new SecureRandom( new byte [] { 1 , 2 , 3 , 4 });
String str = "Tajmahal" ;
byte [] b = str.getBytes();
System.out.println( "Byte array before operation : " + Arrays.toString(b));
sr.nextBytes(b);
System.out.println( "Byte array after operation : " + Arrays.toString(b));
}
catch (ProviderException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Byte array before operation : [84, 97, 106, 109, 97, 104, 97, 108]
Byte array after operation : [-14, 77, 123, 121, 116, 50, -89, -86]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...