2011-03-15 57 views
0

我做文件的加密解密在Android中,爲了這個目的,我使用下面的代碼Android的加密/ Decrytion問題

private void encryptFile() 
{ 
    try 
    { 
     File f = new File(Environment.getExternalStorageDirectory() + "/images.jpg"); 
     FileInputStream in = new FileInputStream(f); 
     byte[] buffer = new byte[100]; 
     int num = in.read(buffer, 0, 100); 
     Encryption mEncryption = new Encryption("test"); 
     File tempFile = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); 
     FileOutputStream os = new FileOutputStream(tempFile); 
     os.write(mEncryption.encrypt(buffer), 0, 100); 
     while(in.read(buffer) != -1) 
     { 
      os.write(buffer); 
     } 
     in.close(); 
     os.close(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

private void decryptFile() 
{ 
    try 
    { 
     File f = new File(Environment.getExternalStorageDirectory() + "/temp.jpg"); 
     FileInputStream in = new FileInputStream(f); 
     byte[] buffer = new byte[100]; 
     in.read(buffer, 0, 100); 
     Encryption mEncryption = new Encryption("test"); 
     File tempFile = new File(Environment.getExternalStorageDirectory() + "/images.jpg"); 
     FileOutputStream os = new FileOutputStream(tempFile); 
     os.write(mEncryption.decrypt(buffer), 0, 100); 
     while(in.read(buffer) != -1) 
     { 
      os.write(buffer); 
     } 
     in.close(); 
     os.close(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

但是當我解密文件,它給我IllegalBlockSizeException: last block incomplete in decryption任何想法,爲什麼它的發生?

編輯:我用這Encryption class

回答

0

沒有與此代碼中的許多潛在的問題。什麼是Encryption類?它不是標準Android SDK的一部分。你不打算加密整個文件嗎?此代碼僅加密前100個字節。這是重大錯誤所在。然後代碼假定輸入文件的前100個字節將包含加密數據,這是一個無效的假設。將加密數據開始標準化爲加密算法的塊大小的長度。

+0

嗨,感謝您的回覆,我試圖編碼/解碼僅前100字節的數據作爲加密整個文件將需要很多時間我已經發布鏈接到我的加密類以上 – ingsaurabh 2011-03-15 07:50:37

+0

好吧,然後看看所得到的緩衝區來自encryptFile方法中的mEncryption.encrypt(緩衝區)。您的decryptFile代碼假設這是100個字節,它不會。您需要將其存儲在某個地方,然後讀回正確數量的加密數據,然後傳遞給解密。 – 2011-03-15 07:55:55

+0

是啊,它的大於100字節,我認爲這是問題,但現在當我解密文件如何知道多少字節真正加密讀取和解密他們對此的任何想法我的意思是我怎麼只能加密前100字節文件,然後在以後解密它們 – ingsaurabh 2011-03-15 08:19:00

2

您正在使用的加密類在我的博客上發佈,就像您說的(http://blog.kotowicz.net/2010/09/story-of-android-cryptography-and.html),但是作爲您應該如何實現加密的示例!它有一些填充和關鍵擴展問題,都在博客文章中提到。

該類來源於此類,它來自Android Remote Notifier項目。如果你真的需要它,至少要使用更正後的版本http://code.google.com/p/android-notifier/source/browse/trunk/AndroidNotifier/src/org/damazio/notifier/util/Encryption.java - 我博客文章中的版本有一些嚴重問題。

正如Nic Strong所提到的,您遇到了填充 - 塊密碼對齊塊大小,您應該解釋它。

+0

感謝您的啓發,現在我已經創建了我自己的幫手類,並致力於 – ingsaurabh 2011-03-15 10:06:21