2012-05-19 78 views
0

我正在嘗試編寫一個簡單的應用程序,它將上載的文件加密並在將它們存儲到磁盤之前進行加密。Java加密設置失敗,出現InvalidKeySpecException

這裏是一個片段

InputStream is = item.openStream(); // item is obtained from file upload iterator 
try{ 
    PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength); 
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); 
    SecretKey key = keyFactory.generateSecret(keySpec); // Throws Exception 
    CipherInputStream cis; 
    Cipher cipher = Cipher.getInstance("RSA"); 
    cis = new CipherInputStream(is, cipher); 
    cipher.init(Cipher.ENCRYPT_MODE, key); 
} catch (Exception ex){ 
    // catches the following exceptopn 
    java.security.spec.InvalidKeySpecException: Inappropriate key specification 
    at com.sun.crypto.provider.DESedeKeyFactory.engineGenerateSecret(DashoA13*..) 
    // 
} 

我也試過 「RSA/ECB/PKCS1Padding」 沒有成功。 我做錯了什麼?

回答

2

那是因爲您需要初始化一個SecretKeyFactory,它與您提供的KeySpec兼容。嘗試此例如:

PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength); 
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES"); 
SecretKey key = keyFactory.generateSecret(keySpec); 
Cipher cipher = Cipher.getInstance(key.getAlgorithm()); 
CipherInputStream cis = new CipherInputStream(is, cipher); 
cipher.init(Cipher.ENCRYPT_MODE, key); 

通過這個調用產生可以成功地生成從PBEKeySpec實例的密鑰SecretKeyFactoryCipher與正確的算法初始化。

+0

謝謝@laz。我試過這個,現在看來我有供應商問題。現在調用_Cipher.getInstance(key.getAlgorithm()); _ throws「java.security.NoSuchAlgorithmException:找不到任何支持PBKDF2WithHmacSHA1的提供程序」。 – adaj21

+0

@ adaj21:您將不得不告訴我們您正在使用哪個Java平臺以及哪個版本。 –

+1

哎呀,我把錯誤的算法。我用正確的答案修改了答案。 – laz