在java中解密时出错

Mad*_*ore 8 java sqlite encryption android

我正在尝试用Java加密/解密String.没有关于加密的问题然后存储在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Udo*_*ski 10

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

IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE,keySpec, ivSpec);
Run Code Online (Sandbox Code Playgroud)

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

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

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