You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Windows环境下SecureRandom NativePRNG运行失败?如何解决?

Java中Windows系统使用NativePRNG失败的原因及替代方案

问题场景

以下代码在Windows系统运行时会抛出NoSuchAlgorithmException异常:

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        SecureRandom srand = SecureRandom.getInstance("NativePRNG");
        System.out.println(srand.nextInt());
    }
}

失败原因

NativePRNG是Linux/Unix系统专属的SecureRandom算法实现,它依赖系统的/dev/random或/dev/urandom设备获取熵源生成安全随机数。而Windows系统没有这类设备,也未实现该算法,因此调用时会抛出算法不存在的异常。

解决方案

在Windows系统上,使用平台专属的Windows-PRNG算法即可实现等价的安全随机数生成功能,该算法会调用Windows系统的CryptGenRandomAPI来获取安全随机数。

另外需要说明:Java 10及以上版本中,默认已在<JDK>\conf\security\java.security文件中设置crypto.policy=unlimited,无需手动修改该配置。

修改后的示例代码:

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class Main {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        SecureRandom srand = SecureRandom.getInstance("Windows-PRNG");
        System.out.println(srand.nextInt());
    }
}

内容的提问来源于stack exchange,提问作者Bhaskar13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:50:43