gpt4 book ai didi

java - 如何解决AES加密代码中的异常

转载 作者:行者123 更新时间:2023-12-01 09:26:18 24 4
gpt4 key购买 nike

我是密码学新手,我正在尝试创建一个简单的 AES 加密程序和 base64 编码。该程序似乎按应有的方式加密和解密了我的消息字符串,但由于某种原因,它在 decrypt 方法中向我显示了异常 java.lang.IllegalArgumentException: Illegal base64 character 20但也许它与加密有关..

查了好久也没找到原因。如果有人能指出我的代码中可能导致此错误的任何错误,我将不胜感激!

public class AES_encryption {
private static SecretKey skey;
public static Cipher cipher;

public static void main(String[] args) throws Exception{
String init_vector = "RndInitVecforCBC";
String message = "Encrypt this?!()";
String ciphertext = null;

//Generate Key
skey = generateKey();

//Create IV necessary for CBC
IvParameterSpec iv = new IvParameterSpec(init_vector.getBytes());

//Set cipher to AES/CBC/
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

try{
ciphertext = encrypt(skey, iv, message);
}
catch(Exception ex){
System.err.println("Exception caught at encrypt method!" + ex);
}
System.out.println("Original Message: " + message + "\nCipher Text: " + ciphertext);

try{
message = decrypt(skey, iv, message);
}
catch(Exception ex){
System.err.println("Exception caught at decrypt method! " + ex);
}

System.out.println("Original Decrypted Message: " + message);


}

private static SecretKey generateKey(){
try {
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128);
skey = keygen.generateKey();
}
catch(NoSuchAlgorithmException ex){
System.err.println(ex);
}
return skey;
}

private static String encrypt(SecretKey skey, IvParameterSpec iv, String plaintext) throws Exception{
//Encodes plaintext into a sequence of bytes using the given charset
byte[] ptbytes = plaintext.getBytes(StandardCharsets.UTF_8);

//Init cipher for AES/CBC encryption
cipher.init(Cipher.ENCRYPT_MODE, skey, iv);

//Encryption of plaintext and enconding to Base64 String so it can be printed out
byte[] ctbytes = cipher.doFinal(ptbytes);
Base64.Encoder encoder64 = Base64.getEncoder();
String ciphertext = new String(encoder64.encode(ctbytes), "UTF-8");

return ciphertext;
}

private static String decrypt(SecretKey skey, IvParameterSpec iv, String ciphertext) throws Exception{
//Decoding ciphertext from Base64 to bytes[]
Base64.Decoder decoder64 = Base64.getDecoder();
byte[] ctbytes = decoder64.decode(ciphertext);

//Init cipher for AES/CBC decryption
cipher.init(Cipher.DECRYPT_MODE, skey, iv);

//Decryption of ciphertext
byte[] ptbytes = cipher.doFinal(ctbytes);
String plaintext = new String(ptbytes);

return plaintext;
}

}

最佳答案

问题是因为您解密的是消息而不是加密的消息!

decrypt(skey, iv, message) 可能应该是 decrypt(skey, iv, ciphertext)

关于java - 如何解决AES加密代码中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com