2016-10-01 31 views
0

我是密码学新手,我试图创建一个简单的AES加密程序和base64代码。该程序似乎加密和解密我的消息字符串,因为它应该但由于某种原因,它显示我异常java.lang.IllegalArgumentException:非法base64字符20解密方法,但它可能与加密有关..如何解决AES加密代码中的例外问题

经过一段时间我找不到原因。如果有人能指出我的代码中可能导致此错误的任何错误,我将不胜感激!

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; 
} 

}

+0

如果你没有提供的测试数据不期待一个答案。需要[mcve],请注意“完整”。在十六进制中提供密钥和“ctbytes”。 – zaph

+0

如果你做了最少的调试(在调试器或打印语句中查看值),你会发现解密时的ctbytes不是它应该是的。 – zaph

回答

1

的问题是,因为你解密消息未加密的消息!

decrypt(skey, iv, message)大概应该是decrypt(skey, iv, ciphertext)

+0

谢谢你,这很简单!从我的角度来看,这是一种愚蠢的分心。 –