java中DEC密钥与密钥种子

本文探讨了一种使用DEC加密时遇到的问题,在不同环境下同一密钥种子产生的密钥不一致,导致无法正确解密。问题根源在于SecureRandom的实现依赖于不同的安全提供者,从而影响密钥的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    最近用到了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生成密钥。这种做法有可能不地道,但至少解决了当前问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值