2014-01-08 39 views
0

我解密一個文件,但它沒有顯示解密的字符串。它也扔了javax.crypto.IllegalBlockSizeException爲什麼解密的字符串不能顯示?

這是我的代碼:當輸入數據不是塊大小(在AES的情況下16個字節)的倍數發生

File f=new File("C:/Users/User/Desktop/Test.txt"); 
int ch; 

StringBuffer strContent = new StringBuffer(""); 
FileInputStream fin = null; 
try { 
    fin = new FileInputStream(f); 
    while ((ch = fin.read()) != -1) 
     strContent.append((char) ch); 
    fin.close(); 
} 
catch (Exception e) { 
    System.out.println(e); 
} 

KeyGenerator kgen = KeyGenerator.getInstance("AES"); 
kgen.init(128); 

SecretKey skey = kgen.generateKey(); 
byte[] raw = skey.getEncoded(); 

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); 

Cipher cipher = Cipher.getInstance("AES"); 

cipher.init(Cipher.DECRYPT_MODE, skeySpec); 
byte[] original =cipher.doFinal(strContent.toString().getBytes()); 

String originalString = new String(original); 
JOptionPane.showMessageDialog(null,originalString.toString()); 
+2

你可以顯示錯誤嗎?沒有它,我們無法幫助。 – skiwi

+0

當您在'String originalString = ...'行上設置斷點時,'original'包含了什麼? –

+0

線程「main」中的異常javax.crypto.IllegalBlockSizeException – newlearner

回答

0

IllegalBlockSizeException

此問題是由讀取解密數據的方法引起的。正如Jesper和JB Nizet在評論中所解釋的那樣,加密數據作爲文本是不可讀的。試圖將它作爲字符串讀取(不管字符集)是不行的。

所以...確保您將文件作爲字節流寫入磁盤並以相同方式讀取。這應該確保你有正確的數據(這將是正確的長度)。

我推薦一些類似Apache commons-lang FileUtils.writeByteArrayToFileFileUtils.readFileToByteArray,或者自己寫Java IO庫。

+0

任何人都可以修復我的代碼。 – newlearner

+0

@newlearner這不是什麼這個網站是關於。你需要修復你自己的代碼。我在答覆中給了你足夠的信息讓你開始。 –

相關問題