2015-03-19 51 views
1

我正在嘗試編寫加密或解密字符串(主要是數字)的方法。它工作正常的一些文本(EG- '1010000011', '1010000012', '1010000013'),但給出以下爲別人的錯誤(EG- '1010000014', '1010000018'):AES加密/解密:鑑於最後的塊沒有正確填充

javax.crypto.BadPaddingException :鑑於最終塊無法正常 填充

這裏去我的代碼:

public static SecretKey secKey; 
private static IvParameterSpec ivspec; 
static { 
    try { 
     SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
     KeySpec spec = new PBEKeySpec("i15646dont6321wanna".toCharArray(), 
       "ahhalkdjfslk3205jlk3m4ljdfa85l".getBytes("UTF-8"), 65536, 256); 
     SecretKey tmp = factory.generateSecret(spec); 
     secKey = new SecretKeySpec(tmp.getEncoded(), "AES"); 
     byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; 
     ivspec = new IvParameterSpec(iv); 
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } 
} 

public static String encryptData(String textToEncrypt) { 

    byte[] encryptedBytes = null; 
    String encryptedText = ""; 
    try { 
     byte[] byteToEncrypt = textToEncrypt.getBytes(Charset.defaultCharset()); 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.ENCRYPT_MODE, secKey, ivspec); 
     encryptedBytes = cipher.doFinal(byteToEncrypt); 
     encryptedText = new String(encryptedBytes); 
    } catch (NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException 
      | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) { 
     e.printStackTrace(); 
    } 
    return encryptedText; 
} 

public static String decryptData(String textToDecrypt) { 

    byte[] decryptedBytes = null; 
    String decryptedText = ""; 
    try { 
     byte[] byteToDecrypt = textToDecrypt.getBytes(Charset.defaultCharset()); 
     Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
     cipher.init(Cipher.DECRYPT_MODE, secKey, ivspec); 
     decryptedBytes = cipher.doFinal(byteToDecrypt); 
     decryptedText = new String(decryptedBytes); 
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException 
      | IllegalBlockSizeException | BadPaddingException 
      | InvalidAlgorithmParameterException e) { 
     e.printStackTrace(); 
    } 
    return decryptedText; 
} 

要加密從文件中讀取和寫入加密後的一些其他文件中的字符串。這個加密的文本將不得不稍後解密。我按照以下方式調用這些方法:

String[] lineArray = line.split(" | "); //line is read from a file. 
String encryptedText = AESEncryption.encryptData(lineArray[0]); 
String decryptedText = AESEncryption.decryptData(encryptedText); 
System.out.println("Original Text: " + lineArray[0] + " | Encrypted text: " 
       + encryptedText + " | Decrypted again: " + decryptedText); 
+0

當在轉換字符串字節數組,如果我用UTF-8或UTF-16,它拋出異常而解密: javax.crypto.IllegalBlockSizeException:帶襯墊的密碼解密時輸入長度必須爲16的倍數 – Amarjeet 2015-03-19 12:41:33

回答

2

您試圖將加密數據作爲字符串傳遞。這是致命的。加密的數據是字節,而不是字符串。使用Base64轉換實用程序將加密的字節轉換爲Base64字符串。

加密:明文 - >加密字節 - > Base64文本。

解密:Base64文本 - >加密字節 - >解密文本。

相關問題