java实现AES加密,windows加解密正常linux解密报错,SecureRandom类导致。

java实现AES加密,windows加解密正常linux解密报错,SecureRandom

报错原因:

在Java中,SecureRandom 类用于生成高质量的随机数。在Windows和Linux上,默认的算法可能会有不同。

  • Windows:默认的算orithm可能是SHA1PRNG,这是基于SHA-1算法的强随机数生成器。
  • Linux:默认的算法可能是NativePRNGBlocking或NativePRNGNonBlocking。

报错代码:

SecureRandom secureRandom = new SecureRandom()

/**
	 * 生成AES密钥
	 *
	 * @param seed 种子
	 * @return 返回AES密钥
	 * @throws NoSuchAlgorithmException 异常信息
	 */
	private static byte[] generateKey(String seed) throws Exception {
		SecureRandom secureRandom = new SecureRandom();
		secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8));
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		keyGenerator.init(128, secureRandom);
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey.getEncoded();
	}

修改后:

SecureRandom random = SecureRandom.getInstance(“SHA1PRNG”);

/**
	 * 生成AES密钥
	 *
	 * @param seed 种子
	 * @return 返回AES密钥
	 * @throws NoSuchAlgorithmException 异常信息
	 */
	private static byte[] generateKey(String seed) throws Exception {
		//1.构造密钥生成器,指定为AES算法,不区分大小写
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		//2.根据ecnodeRules规则初始化密钥生成器
		//生成一个128位的随机源,根据传入的字节数组
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(seed.getBytes(StandardCharsets.UTF_8));
		keyGenerator.init(128, random);

//		SecureRandom secureRandom = new SecureRandom();
//		secureRandom.setSeed(seed.getBytes(StandardCharsets.UTF_8));
//		keyGenerator.init(128, secureRandom);
		//3.产生原始对称密钥
		SecretKey secretKey = keyGenerator.generateKey();
		return secretKey.getEncoded();
	}

注意:

默认算法会尝试使用最佳的加密算法和源,但可能会根据Java版本和操作系统而有所不同。
如果需要确保在不同的环境中都有一致的随机数生成性能,
并且避免SecureRandom.getInstance(“SHA1PRNG”)存在CWE-328弱hash的问题,
应该使用:
SecureRandom.getInstanceStrong(),它会返回一个注册为"强"的SecureRandom实例。

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值