Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

SecureRandom — cryptographic randomness

SecureRandom generates cryptographically strong random values. nextBytes fills the supplied byte array.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[16];
random.nextBytes(bytes);

java.security.SecureRandom provides cryptographically strong randomness. new SecureRandom() selects a default implementation; the algorithm depends on security providers.

nextBytes(bytes) fills an existing array. Allow automatic seeding: an earlier setSeed can prevent automatic seed acquisition. Do not supply predictable seeds. A fixed seed does not guarantee a portable, repeatable sequence.

Depending on the implementation, nextBytes may block while gathering entropy. The example generates random bytes but prints only the array length, making the expected text constant.

Examples

import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) {
        SecureRandom random = new SecureRandom();
        byte[] bytes = new byte[16];
        random.nextBytes(bytes);
        System.out.println("Generated bytes: " + bytes.length);
    }
}

Result

Generated bytes: 16

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources