2015-10-13 59 views
0

我似乎對JCE有問題。我使用加密JCE密碼創建了一個CipherInputStream,然後我使用另一個解密JCE密碼創建另一個CipherInputStream解密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); 

謝謝!

回答

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