2013-12-15 41 views
0

我的RSA解密這部分代碼:BadPaddingException:執行會話密鑰的RSA加密時,數據必須以零

// Turn the encoded key into a real RSA private key. 
// Private keys are encoded in PKCS#8. 
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); 
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
PrivateKey privateKey = keyFactory.generatePrivate(keySpec); 

// Create a cipher using that key to initialize it 
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 

// Read in the encrypted bytes of the session key 
DataInputStream dis = new DataInputStream(new FileInputStream(fileInput)); 
byte[] encryptedKeyBytes = new byte[dis.readInt()]; 
dis.readFully(encryptedKeyBytes); 

// Decrypt the session key bytes. 
rsaCipher.init(Cipher.DECRYPT_MODE, privateKey); 
byte[] rijndaelKeyBytes = rsaCipher.doFinal(encryptedKeyBytes); 

// Transform the key bytes into an actual key. 
SecretKey rijndaelKey = new SecretKeySpec(rijndaelKeyBytes, "Rijndael"); 

當我選擇私鑰文件出現錯誤,我通過會話進行加密鍵做的主要文件的非對稱加密:

javax.crypto.BadPaddingException:數據必須以零

H啓動我能解決這個錯誤嗎?

+0

請在發佈之前使用拼寫檢查器並重新閱讀您的問題。確保使用使用良好的標籤。 [標籤:密碼]很難使用,請使用[標籤:加密]或[標籤:加密]代替 - 如果你不知道你的問題可能不會被注意到。 –

回答

0

你的問題表明,有一些誤解:

當我選擇私鑰文件,我通過會話密鑰進行加密,這樣做的主要文件的非對稱加密出現錯誤

因此,上述代碼使用RSA私鑰解密會話密鑰。然後會話密鑰可以用來解密數據。因此,您需要使用新的隨機會話密鑰加密數據,然後使用RSA公鑰加密會話密鑰

您應該一般不會加密任何其他實體的RSA私鑰。 RSA私鑰應該保密。您只能對它們進行加密,以便在密鑰存儲中進行備份或保護

+0

從我的答案user3077162中缺少任何東西? –