2010-12-01 248 views
5

我做的使用AES算法的充氣城堡加密和解密J2ME AES解密錯誤(org.bouncycastle.crypto.InvalidCipherTextException:墊塊損壞)

我的加密和解密工作正常,但它給我的錯誤,當我的平原文字大小越大

即使有時它給非解密的數據

public static boolean setEncryptionKey(String keyText) 
{ 
    byte[] keyBytes = keyText.getBytes(); 

    key = new KeyParameter(keyBytes); 
    engine = new AESFastEngine(); 
    cipher = new PaddedBufferedBlockCipher(engine); 

    return true; 
} 

加密:

public static String encryptString(String plainText) 
{ 

     byte[] plainArray = plainText.getBytes(); 

     cipher.init(true, key); 
     byte[] cipherBytes = new byte[cipher.getOutputSize(plainArray.length)]; 
     int cipherLength = cipher.processBytes(plainArray, 0, plainArray.length, cipherBytes, 0); 
     cipher.doFinal(cipherBytes, cipherLength); 
     String cipherString = new String(cipherBytes); 
     return cipherString; 
    } 

解密:

public static String decryptString(String encryptedText) 
{ 

     byte[] cipherBytes = encryptedText.getBytes(); 
     cipher.init(false, key); 
     byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; 
     int decryptedLength = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); 
     cipher.doFinal(decryptedBytes, decryptedLength); 
     String decryptedString = new String(decryptedBytes); 

     int index = decryptedString.indexOf("\u0000"); 
     if (index >= 0) 
     { 
      decryptedString = decryptedString.substring(0, index); 
     } 
     return decryptedString; 
    } 

此解密是給我下面的錯誤

org.bouncycastle.crypto.InvalidCipherTextException: pad block corrupted 
     at org.bouncycastle.crypto.paddings.PKCS7Padding.padCount(+30) 
     at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.doFinal(+190) 
     at com.NewCrypto.decryptString(NewCrypto.java:103) 
     at com.New_Midlet.startApp(New_Midlet.java:23) 
     at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:44) 
     at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:375) 
     at com.sun.midp.main.Main.runLocalClass(Main.java:477) 
     at com.sun.midp.main.Main.main(+80) 

可能是什麼問題呢?

回答

2

String cipherString = new String(cipherBytes); 

是一個錯誤。 cipherBytes是一個具有任意值的字節數組,不能使用任何Java字符串解碼器轉換爲字符串。您應該將密碼發送/保存爲字節數組。如果你必須把它作爲一個字符串,那麼你將不得不使用一個編碼器。經常使用Base64編碼器,Base16(十六進制)也是如此。您可以使用Apache Commons Codec或我的最愛,Harder Base64 codec

+0

任何仍然輸出字節而不是字符的base64編碼器在我看來有點愚蠢。有人試圖將其流式傳輸到UTF-16 XML文件時,我已經可以看到這種恐怖。此外,它似乎不支持任何其他形式的base64比默認的。嗯,也許我應該讓我的編碼器也可用。 – 2011-07-21 23:39:48