0

我正在尝试编写一个简单的应用程序,它接收上传的文件并在将它们存储到磁盘之前对其进行加密。

这是一个片段

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”但没有成功。我做错了什么?

4

1 回答 1

2

那是因为您需要初始化与您提供SecretKeyFactory的兼容的a 。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);

此调用生成的SecretKeyFactory可以从 的实例成功生成密钥,PBEKeySpecCipher使用正确的算法进行初始化。

于 2012-05-19T04:57:41.833 回答