我在java中有以下代码用于加密
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class AES
{
public byte[] encrypted;
public byte[] original;
public String originalString,ske;
Cipher cipher;
SecretKeySpec skeySpec;
static IvParameterSpec spec;
byte [] iv;
/*public static String asHex (byte buf[])
{
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}*/
public AES()
{
try
{
String key ="chetan";
skeySpec = new SecretKeySpec(getMD5(key),"AES");
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
}
catch(Exception ex)
{ex.printStackTrace();}
}
private static byte[] getMD5(String input){
try{
byte[] bytesOfMessage = input.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
return md.digest(bytesOfMessage);
} catch (Exception e){
return null;
}
}
public String AESencryptalgo(byte[] text)
{
String newtext="";
try
{
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
AlgorithmParameters param = cipher.getParameters();
IvParameterSpec ivspec=param.getParameterSpec(IvParameterSpec.class);
iv=ivspec.getIV();
spec=new IvParameterSpec(iv);
//AlgorithmParameters params = cipher.getParameters();
//iv = params.getParameterSpec(IvParameterSpec.class).getIV();
encrypted = cipher.doFinal(text);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
newtext=new String(encrypted);
//System.out.println("ENCRYPTED "+newtext);
return newtext;
}
}
public String AESdecryptalgo(byte[] text)
{
try
{
cipher.init(Cipher.DECRYPT_MODE, skeySpec ,spec);
original = cipher.doFinal(text); //Exception occurs here
originalString = new String(original);
return originalString;
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
return originalString;
}
}
现在的问题是,当我想在不同的程序中加密时使用spec变量时,它会成功加密,但是当我在另一个程序中使用此规范解密相同的数据时,它会产生以下错误和堆栈跟踪:
java.security.InvalidAlgorithmParameterException: Parameters missing
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineInit(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.a(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at AES.AESdecryptalgo(AES.java:81)
at DatabaseClass.InstRecord(DatabaseCLass.java:230)
请告诉我出错了什么?
答案 0 :(得分:1)
是完全相同的机器吗?您确定要使用完全相同的JVM吗?你有没有安装正确的JCE?你能在工作程序中设置一个断点,并确保你的JCE提供者是com.sun.crypto提供者吗?如果所有其他方法都失败,也许您可以尝试使用BouncyCastle提供程序
import org.bouncycastle.jce.provider.BouncyCastleProvider;
...
static {
Security.addProvider(new BouncyCastleProvider());
}
http://www.bouncycastle.org/wiki/display/JA1/Provider+Installation