但不知道為什麼突然跑出 javax.crypto.BadPaddingException: Data must start with zero 的 Exception
找來找去都不知道問題出在哪.....後來查到 [1] 時發現好像有比較簡潔的寫法...。
直接記錄加解密的那一段程式碼如下:
byte[] buffer = new byte[1024];
int len = 0;
CipherOutputStream cos = null;
try {
// Initial the cipher.
Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
cipher.init(cipherMode, key);
// Cipher the input and write to output stream.
cos = new CipherOutputStream(output, cipher);
while((len = input.read(buffer)) != -1) {
cos.write(buffer, 0, len);
cos.flush();
}
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} finally {
try {
if(cos != null) cos.close();
} catch (IOException e) {}
}
其中 ENCRYPT_ALGORITHM 是加密或解密使用的演算法;cipherMode 是 Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
key 則是事先產生好的 Private Key 或 Public Key。
改用這個方法以後,似乎因為沒有自己呼叫 doFinal() 函式,所以也不會跑出 BadPaddingException 等的問題~程式碼也變短了
雖然仍然沒有真的發現原本到底是什麼問題.....。
參考資料:
1、Encrypting files with Public Key Encryption in Java
沒有留言:
張貼留言