解密CipherInputStream会导致空流

时间:2015-10-13 10:48:15

标签: java encryption cryptography jce

我似乎遇到了JCE的问题。我使用加密JCE密码创建CipherInputStream,然后使用不同的解密JCE密码创建另一个CipherInputStream

当我尝试读取第二个流时,我得到的只是空数据。我发现没有文件禁止上述行为。有谁知道问题是什么?

这是我正在运行的代码,最后plainText为空(无论我使用什么SecurityProvider,同样的问题仍然存在)。

InputStream payload = new ByteArrayInputStream(payloadArray);
Cipher encryptCipher = Cipher.getInstance("AES", "SunJCE");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, IV);
InputStream encryptStream = new CipherInputStream(payload, encryptCipher);

Cipher decryptCipher = Cipher.getInstance("AES", "SunJCE");
decryptCipher.init(Cipher.DECRYPT_MODE, key, IV);
InputStream decryptStream = new CipherInputStream(encryptStream, decryptCipher);

byte[] plainText = IOUtisl.toByteArray(decryptStream);

谢谢!

1 个答案:

答案 0 :(得分:0)

当您省略键的部分时,IV参数会根据您提供的代码找到一个小片段。

// add proper exception handling, left out only for the example
public static void main(String[] args) throws Exception {
    String transformation = "AES/CBC/PKCS5PADDING";
    String provider = "SunJCE";
    String algorithm = "AES";
    byte[] payloadArray = "secret text".getBytes();

    KeyGenerator keyGen = KeyGenerator.getInstance(algorithm, provider);
    keyGen.init(128);
    Key key = keyGen.generateKey();

    byte[] ivBytes = new byte[16];
    SecureRandom prng = new SecureRandom();
    prng.nextBytes(ivBytes);
    IvParameterSpec IV = new IvParameterSpec(ivBytes);

    Cipher encryptCipher = Cipher.getInstance(transformation, provider);
    encryptCipher.init(Cipher.ENCRYPT_MODE, key, IV);

    InputStream payload = new ByteArrayInputStream(payloadArray);
    InputStream encryptStream = new CipherInputStream(payload, encryptCipher);

    Cipher decryptCipher = Cipher.getInstance(transformation, provider);
    decryptCipher.init(Cipher.DECRYPT_MODE, key, IV);
    InputStream decryptStream = new CipherInputStream(encryptStream, decryptCipher);

    for (int i = decryptStream.read(); i >= 0; i = decryptStream.read()) {
        System.out.print((char) i);
    }
}

<强>输出

secret text