在java中解密时出错

时间:2012-11-06 15:05:26

标签: java android sqlite encryption

我正在尝试用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;
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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");