2014-02-24 105 views
1

我試圖加密某些內容,並將其解密。我解密失敗 - 我得到上面的例外。我嘗試改變ctLength和ptLength,但無濟於事。我究竟做錯了什麼?
我試圖加密:0 0 0 0 0 0 0 0javax.crypto.BadPaddingException:填充塊已損壞

private Cipher encrypt(byte[] input) 
{ 
    try 
    { 
     SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); 

     Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); 

     // encryption pass 
     cipher.init(Cipher.ENCRYPT_MODE, key); 
     byte[] cipherText = new byte[cipher.getOutputSize(input.length)]; 
     int ctLength = cipher.update(input, 0, input.length, cipherText, 0); 
     ctLength += cipher.doFinal(cipherText, ctLength); 
     FileOutputStream fs = new FileOutputStream(savedScoresFileName); 
     fs.write(cipherText); 

     return cipher; 
    } 
    catch (Exception e) 
    { 
     Log.e("encrtypt", "Exception", e); 
    } 

    return null; 
} 

private String decrypt() 
{ 
    try 
    { 
     Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); 

     SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); 
     byte[] cipherText = new byte[32]; 

     FileInputStream fl = new FileInputStream(savedScoresFileName); 
     fl.read(cipherText); 

     cipher.init(Cipher.DECRYPT_MODE, key); 
     byte[] plainText = new byte[cipher.getOutputSize(32)]; 
     int ptLength = cipher.update(cipherText, 0, 32, plainText, 0); 
     ptLength += cipher.doFinal(plainText, ptLength); 

     return new String(plainText).substring(0, ptLength); 
    } 
    catch (Exception e) 
    { 
     Log.e("decrypt", "Exception", e); 
    } 

    return null; 
} 

此代碼是從this,其中的工作拷貝。

回答

3

您的代碼有許多問題,但是您的問題是由您的文件讀取代碼和執行加密和解密的奇怪方法引起的。

請勿使用update()方法,只需使用doFinal()並更正您的文件寫入/讀取代碼。例如。你的解密方法應該是這樣的:

try { 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC"); 

    SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); 

    // Here you need to accurately and correctly read your file into a byte 
    // array. Either Google for a decent solution (there are many out there) 
    // or use an existing implementation, such as Apache Commons commons-io. 
    // Your existing effort is buggy and doesn't close its resources.  
    byte[] cipherText = FileUtils.readFileToByteArray(new File(savedScoresFileName)); 


    cipher.init(Cipher.DECRYPT_MODE, key); 

    // Just one call to doFinal 
    byte[] plainText = cipher.doFinal(cipherText); 

    // Note: don't do this. If you create a string from a byte array, 
    // PLEASE pass a charset otherwise your result is platform dependent. 
    return new String(plainText); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 
+0

謝謝!我不知道加密 - 我複製和粘貼過去爲我工作的代碼... – Ran

相關問題