gpt4 book ai didi

Java 加密设置失败并出现 InvalidKeySpecException

转载 作者:行者123 更新时间:2023-12-02 07:47:15 24 4
gpt4 key购买 nike

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

这是一个片段

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

最佳答案

这是因为您需要初始化一个与您提供的 KeySpec 兼容的 SecretKeyFactory 。例如尝试这个:

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 实例成功生成 key ,并且使用正确的算法初始化 Cipher

关于Java 加密设置失败并出现 InvalidKeySpecException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10661644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com