实现说明
SecureRandom 令牌与 HexFormat的核心是类 ApiKeyIssuer和函数 main。
使用要点
- 直接运行文件,输出会带上标签,比如
token length =、prefix =、roundtrip matches =——输出的每一行都能指回产生它的那次调用。
常见问题
运行「SecureRandom 令牌与 HexFormat」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 token length =、prefix =、roundtrip matches = 这类标签。
核心语句
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);
代码示例
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));
}
}