Java AES 解密代码不起作用 - 无效异常1234444



我正在尝试编写简单的AES密码 加密部分工作正常,但解密部分抛出异常: 代码是这样的:

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class Next {
public static void main(String []ar) throws 
NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, 
IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException 
{
Security.addProvider(new BouncyCastleProvider());
KeyGenerator generator = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = new SecureRandom();
generator.init(256, secureRandom);
SecretKey key = generator.generateKey();
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText  = "abcdefghijklmnopqrstuvwxyz".getBytes("UTF-8");
byte[] cipherText = cipher.doFinal(plainText);
System.out.println(cipherText);
Cipher cipher2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher2.init(Cipher.DECRYPT_MODE, key);
byte[] text = cipher.doFinal(cipherText); // Exception is 
//throwing here
System.out.println(text);
}
}

例外情况是:

线程"main"中的异常 java.security.InvalidKeyException: 参数 missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:470(at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:313(at javax.crypto.Cipher.implInit(Cipher.java:801(at javax.crypto.Cipher.chooseProvider(Cipher.java:863(at javax.crypto.Cipher.init(Cipher.java:1248(at javax.crypto.Cipher.init(Cipher.java:1185(at securityInvade.Next.main(Next.java:41(





CBC(密码块链(需要iv(初始向量(进行加密和解密。

byte[] iv = new byte[16];
// set up iv...
IvParameterSpec spec = new IvParameterSpec(iv);

然后使用 iv 初始化密码:

cipher.init(Cipher.ENCRYPT_MODE, key, spec);

cipher2.init(Cipher.DECRYPT_MODE, key, spec);

要打印邮件,请将其转换为String

System.out.println(new String(text, "utf-8"));

相关内容

  • 没有找到相关文章

最新更新