gpt4 book ai didi

java - 在java中解密时出错

转载 作者:IT王子 更新时间:2023-10-29 06:22:31 25 4
gpt4 key购买 nike

我正在尝试用 Java 加密/解密字符串。加密没有问题,然后存储在 sqlite 表中。但我总是在尝试解密时遇到同样的错误:

“java.security.InvalidKeyException:没有按预期设置 IV”

这是我的代码 fragment :

public String encrypt(String password){
try
{
String key = "mysecretpassword";
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return new String(cipher.doFinal(password.getBytes()));
}
catch (Exception e)
{
return null;
}
}

public String decrypt(String password){
try
{
String key = "mysecretpassword";
SecretKeySpec keySpec = null;
keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE,keySpec);
return new String(cipher.doFinal(password.getBytes()));
}
catch (Exception e)
{
System.out.println(e);
return null;
}
}

我做错了什么?

最佳答案

您需要在 cipher.init() 方法中指定一个初始化 vector :

IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec, ivSpec);

参见:http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/IvParameterSpec.html

初始化 vector 应该是一个随机字节数组,讨论见:

http://en.wikipedia.org/wiki/Initialization_vector

关于java - 在java中解密时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13253783/

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