SecureRandom Token Bytes HexFormat
Generate session tokens from SecureRandom bytes and render them with HexFormat, keeping 256 bits of entropy and predictable output formatting.
Code
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
JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Byte Size ConverterShow one byte count in every unit side by side, using decimal (kB/MB/GB) or binary (KiB/MiB/GiB) standards.
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 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.