最近用到了DEC.我们把一段字符串类型的信息采用DEC加密后发送给对方,对方解密后得到明文。在开发环境上一切正常,但测试环境上对方不能正常解密。
问题出在哪里呢?
我们把密钥种子写在配置文件中,加密时利用密钥种子生成的密钥。代码如下(其中seed是密钥种子字符串,seedEnc是字符编码类型):
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom(seed.getBytes(seedEnc)));
SecretKey secretKey=generator.generateKey();
问题出在SecureRandom身上。
先看看SecureRandom的构造函数的注释:
Constructs a secure random number generator (RNG) implementing the default random number algorithm. The SecureRandom instance is seeded with the specified seed bytes.
This constructor traverses the list of registered security Providers, starting with the most preferred Provider. A new SecureRandom object encapsulating the SecureRandomSpi implementation from the first Provider that supports a SecureRandom (RNG) algorithm
is returned. If none of the Providers support a RNG algorithm, then an implementation-specific default is returned.
中文意思大致为:构造一个实现了缺省随机数算法的安全随机数生成器(RNG).SecureRandom实例以指定的字节数组作为种子。
构造函数遍历已注册的安全提供者列表(从首选提供者开始)。返回一个新的SecureRandom对象,该对象利用第一个支持SecureRandom (RNG)的提供者封装SecureRandomSpi实现。如果没有提供者支持RNG算法,将返回特定实现的缺省值。(我这蹩脚的英文诶,呵呵。)
看了这个注释,问题就相当明了了。密钥生成器依赖SecureRandom,而对于同一个密钥种子,不同的提供者可能产生不同的SecureRandom。有资料说SecureRandom本身又依赖于Random。
我们的解决办法:直接把密钥(而不是密钥种子)写在配置文件中,不再利用SecureRandom生成密钥。这种做法有可能不地道,但至少解决了当前问题。
java中DEC密钥与密钥种子
最新推荐文章于 2022-12-29 15:56:20 发布