2016-10-01 32 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

謝謝你,這很簡單!從我的角度來看,這是一種愚蠢的分心。 –