SecureRandom Token Bytes HexFormat

Generate session tokens from SecureRandom bytes and render them with HexFormat, keeping 256 bits of entropy and predictable output formatting.

JavaSecurity Boundaries

Code

snippet
import java.security.SecureRandom;
import java.util.HexFormat;

public class ApiKeyIssuer {

    public static void main(String[] args) {
        SecureRandom random = new SecureRandom(); // 密码学强随机,勿用 Random 造令牌

        byte[] raw = new byte[32]; // 256 bit 熵
        random.nextBytes(raw);

        // 小写十六进制:一个字节展开成两个字符
        HexFormat hex = HexFormat.of();
        String token = hex.formatHex(raw);
        System.out.println("token length = " + token.length());

        // 展示格式:大写 + 冒号分隔,只取前 4 个字节
        HexFormat pretty = HexFormat.ofDelimiter(":").withUpperCase();
        System.out.println("prefix = " + pretty.formatHex(raw, 0, 4));

        // 反向解析:十六进制串还原为字节,可校验外来令牌格式
        System.out.println("roundtrip matches = " + hex.formatHex(hex.parseHex(token)).equals(token));
    }
}

How the snippet works

Count the class ApiKeyIssuer and the function main as the entire surface area of SecureRandom Token Bytes HexFormat.

Applying it

Each run prints the 3 labeled blocks token length =, prefix =, roundtrip matches = in source order.

Statements that matter

SecureRandom random = new SecureRandom(); // 密码学强随机,勿用 Random 造令牌
byte[] raw = new byte[32]; // 256 bit 熵
random.nextBytes(raw);
HexFormat pretty = HexFormat.ofDelimiter(":").withUpperCase();
String token = hex.formatHex(raw);

Interactive Tools for This Topic

FAQ

What does SecureRandom Token Bytes HexFormat print when run?
Running the file directly is enough — expect labeled output lines such as `token length =`, `prefix =`, `roundtrip matches =`.