Java加密设置因InvalidKeySpecException而失败

时间:2012-05-19 01:43:48

标签: java encryption

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

这是一个片段

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

1 个答案:

答案 0 :(得分: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);

此调用生成的SecretKeyFactory可以从PBEKeySpec的实例成功生成密钥,并使用正确的算法初始化Cipher