在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/