博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于 java中的SecureRandom在linux中每次生成不同结果
阅读量:4709 次
发布时间:2019-06-10

本文共 1760 字,大约阅读时间需要 5 分钟。

使用AES算法的时候,会发现下面的代码在windows每次产生确定的结果,但Linux就不同,导致无法正确解密

public static String encrypt(String content, String password) {    try {        KeyGenerator kgen = KeyGenerator.getInstance("AES");        kgen.init(128, new SecureRandom(password.getBytes()));        SecretKey secretKey = kgen.generateKey();        byte[] enCodeFormat = secretKey.getEncoded();        SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");        Cipher cipher = Cipher.getInstance("AES");// 创建密码器        byte[] byteContent = content.getBytes("utf-8");        cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化        byte[] result = cipher.doFinal(byteContent);        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");        random.setSeed(password.getBytes());        kgen.init(128, random);        return parseByte2HexStr(result); // 加密    } catch (Exception e) {        System.out.print(e);    }    return null;}

原因在于加红的部分SecureRaom的生成,Linux下默认的算法是“NativePRNG”, 而windows下默认是“SHA1PRNG”(sun提供的算法)

对于这两种算法

相同点:  1. 都是伪随即算法,  2. 默认都是阻塞式不同点:  1. SHA1PRNG使用的seed是在系统启动时就指定的,而NativePRNG会在内核中随机取得(这也是Linux下每次结果不同的原因)  2. 正是因为每次随机取,NativePRNG开销要更大些

 虽然Linux认为最佳随机算法是NativePRNG(安全因素),但使用每次都变化的radom是无法正确解密的,所以并不适用于此种场合。

 

解决办法

SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );secureRandom.setSeed(password.getBytes());kgen.init(128, secureRandom);

另外,这两种算法都是阻塞式算法,会读取/var/random,如果想非阻塞,启动时加上下面参数

Djava.security=file:/dev/urandom

 

参考:

http://www.cjsdn.net/Doc/JDK50/java/security/SecureRandom.html

https://docs.oracle.com/javase/7/docs/api/java/security/SecureRandom.html

http://calvin1978.blogcn.com/articles/securerandom.html

https://stackoverflow.com/questions/27622625/securerandom-with-nativeprng-vs-sha1prng

 

转载于:https://www.cnblogs.com/roostinghawk/p/8384057.html

你可能感兴趣的文章
arrow:让Python的日期与时间变的更好
查看>>
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
Java并发编程
查看>>
Git Stash用法
查看>>
sql server 2008学习8 sql server存储和索引结构
查看>>
Jquery radio选中
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>
[CCF2015.09]题解
查看>>
[NYIST15]括号匹配(二)(区间dp)
查看>>
json_value.cpp : fatal error C1083: 无法打开编译器生成的文件:No such file or directory
查看>>