java - Java 中 Cipher 对象的 init

标签 java encryption des

在java中加密数据时如下:

    SecureRandom sr = new SecureRandom();  
    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");  
    SecretKey key = keyFactory.generateSecret(dks);  
    Cipher cipher = Cipher.getInstance("DES");  
    cipher.init(Cipher.ENCRYPT_MODE, key, sr);  
    // why the sr is necessary to init a Cipher object?
    byte data[] = str.getBytes();  
    byte[] encryptedData = cipher.doFinal(data);

为什么需要 SecureRandom 对象 sr 来初始化 Cipher 对象?至于解密端,还需要一个 SecureRandom 对象,该对象与加密大小中生成的对象不同。这些SecureRandom对象仅用于奇偶校验数字吗?

最佳答案

SecureRandom 对象是可选的。如果您不选择其中之一,Java 将使用默认的随机源。请参阅 this method 的文档了解如何选择一个。

Cipher Javadocs解释了这个论点的目的:

If this cipher (including its underlying feedback or padding scheme) requires any random bytes (e.g., for parameter generation), it will get them from random.

因此,在您的特定情况下,您可能根本没有使用此项目。您的 DES 使用中的任何内容都不需要随机数据(因为您似乎正在使用 ECB 模式)。如果您使用 CBC 模式,那么我假设 IV 将从 SecureRandom 对象中随机生成。

关于java - Java 中 Cipher 对象的 init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15406388/

相关文章:

java - 无法在Android代码中的Alarm OnReceive方法上执行select.php

凯撒密码简单程序

java - SecureRandom 是否会降低伪随机数据的熵?

java - 我如何翻译 printf ("%c",M);我的 DES 实现从 C 到 Java?

java - 如何在 Java 中生成双倍长度的 3-DES key

java - 如何用一些透明层覆盖SWT控件或控件?

java - 属性缺失 : Android namespace prefix

java - 在JavaFX中添加Spring依赖注入(inject)(JPA存储库,服务)

php - md5() .vs. 之间有什么不同?保存密码时的哈希值?

python - Erlang 和 Python 之间的 RSA 加密