8

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

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

这是我的代码片段:

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;
    }
}

我究竟做错了什么?

4

2 回答 2

10

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

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

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

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

于 2012-11-06T15:19:50.500 回答
1

您需要适当的 AES 密钥,请尝试:

 String key = "mysecretpassword";
 KeySpec spec = new PBEKeySpec(key.toCharArray(), Salt, 12345678,256);
 SecretKey encriptionKey = factory.generateSecret(spec);
 Key encriptionKey = new SecretKeySpec(encriptionKey.getEncoded(), "AES");
于 2012-11-06T15:14:38.020 回答