Java加密设置失败,并显示InvalidKeySpecException [英] Java Encryption setup fails with InvalidKeySpecException

查看:109
本文介绍了Java加密设置失败,并显示InvalidKeySpecException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的应用程序,该应用程序将上载的文件接收并加密,然后再将其存储到磁盘上.

I am trying to write a simple application that takes in uploaded files and encrypt them before storing them to disk.

这是一个片段

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

I also tried "RSA/ECB/PKCS1Padding " without success. What did I do wrong?

推荐答案

这是因为您需要初始化与您提供的 KeySpec 兼容的 SecretKeyFactory .尝试以下示例:

That is because you need to initialize a SecretKeyFactory that is compatible with the KeySpec you are providing it. Try this for example:

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 用正确的算法初始化.

The SecretKeyFactory produced by this invocation can successfully generate a key from an instance of PBEKeySpec and the Cipher is initialized with the correct algorithm.

这篇关于Java加密设置失败,并显示InvalidKeySpecException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆