在原生镜像中,如何替换默认的 SecureRandom 以加速启动?
解读
国内金融、政企项目全面拥抱 GraalVM 原生镜像以缩短冷启动、降低内存,但 Shiro 默认用 NativePRNG 或 SHA1PRNG,在镜像构建期会触发 /dev/random 阻塞,导致首次登录接口 5~30 s 卡顿,直接被判“性能不达标”。面试官想确认两点:
- 你是否知道阻塞根因在 SecureRandom 的熵源;
- 能否在不破坏安全合规的前提下,用 Shiro 扩展点 把算法换成非阻塞实现,并保证原生镜像里零反射、零资源遗漏。
知识点
- Shiro 加密入口:
DefaultSecurityManager.credentialsMatcher→PasswordService→RandomNumberGenerator→SecureRandom; - RandomNumberGenerator 是 Shiro 提供的 SPI,默认实现
SecureRandomNumberGenerator在静态代码块初始化SecureRandom; - GraalVM native-image 构建时,若类初始化发生在构建期,则随机种子被固化,运行期再重新播种会触发阻塞;
- 国内等保/信创要求:不能简单降级为 UNIX_PRNG 或固定种子,需用 DRBG 或 NonceAndIv 方案,并通过国密局备案;
- Quarkus/Shiro 扩展 已内置
SubstituteSecureRandom示例,可借鉴其 @Substitute 与 @TargetClass 做法做条件替换。
答案
- 自定义 NonBlockingRandomNumberGenerator 实现
RandomNumberGenerator接口,内部持有new SecureRandom("NativePRNGNonBlocking")(在 Linux 上映射到 /dev/urandom),彻底避开阻塞; - 在
shiro.ini或 Java Config 中显式注入:DefaultSecurityManager sm = new DefaultSecurityManager(); sm.setRandomNumberGenerator(new NonBlockingRandomNumberGenerator()); SecurityUtils.setSecurityManager(sm); - 为 GraalVM 添加 JNI 与资源 配置:
- resource-config.json 中开放
/dev/urandom; - reflection-config.json 注册
NonBlockingRandomNumberGenerator无参构造;
- resource-config.json 中开放
- 若使用 Spring Boot + Shiro Starter,用
ShiroCustomizerBean 替换:@Bean public ShiroCustomizer shiroCustomizer() { return (manager) -> manager.setRandomNumberGenerator(new NonBlockingRandomNumberGenerator()); } - 构建命令加
-H:+ReportExceptionStackTraces验证启动日志中 SecureRandom 初始化耗时 < 50 ms,即达标。
拓展思考
- 国密场景:可再把
SecureRandom换成 BouncyCastle 的 SM2DRBG,只需在自定义类里Security.addProvider(new BouncyCastleProvider()),并同步把 DRBG 参数写进META-INF/native-image的 proxy-config.json,避免动态代理缺失; - 多租户云原生:把
RandomNumberGenerator做成 TenantAware Bean,每个租户用隔离的 /dev/urandom 文件描述符,防止高并发场景下 fd 耗尽; - 审计合规:在
NonBlockingRandomNumberGenerator里加 Micrometer 指标,把每次生成随机数的 熵源、耗时、字节数 打到 Prometheus,方便等保测评时出具“随机数质量未降级”证据链。