2016-07-05 203 views
-1

我嘗試使用不同的文件名將文件加密並保存到外部存儲器中的相同位置。但我用過的方式似乎是錯誤的。請幫助別人。如何將文件寫入外部存儲?

 public static void encrypt(SecretKey secretKey, String filePath, IvParameterSpec iv){ 
    try { 

     String file = ""; 
     // Here you read the cleartext. 
     FileInputStream fis = new FileInputStream(filePath); 
     // This stream write the encrypted text. This stream will be wrapped by another stream. 
     //String filePath2 = filePath+"enc"; 

     file = filePath.substring(0,filePath.length()-5)+"enc.jpeg"; 

     FileOutputStream fos = new FileOutputStream(file); 
     Log.i(TAG, "Uri = "+file); 

     // Create cipher 
     Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); 
     cipher.init(Cipher.ENCRYPT_MODE, secretKey); 
     // Wrap the output stream 
     CipherOutputStream cos = new CipherOutputStream(fos, cipher); 

     // Write bytes 
     int b; 
     byte[] d = new byte[8]; 
     while ((b = fis.read(d)) != -1) { 
      cos.write(d, 0, b); 
     } 

     // Flush and close streams. 
     cos.flush(); 
     cos.close(); 
     fis.close(); 

    }catch(IOException e){ 
     e.printStackTrace(); 
    }catch (NoSuchAlgorithmException e){ 
     e.printStackTrace(); 
    }catch(NoSuchPaddingException e){ 
     e.printStackTrace(); 
    }catch(InvalidKeyException e){ 
     e.printStackTrace(); 
    }/*catch (InvalidAlgorithmParameterException e){ 
     e.printStackTrace(); 
    }*/ 
} 

清單文件包含讀取和寫入權限。

+0

你傳遞給這個方法的文件路徑是什麼? –

+1

'到外部存儲器中的相同位置'????? – greenapps

+0

您以與所有位置相同的方式寫入文件。那麼問題是什麼? – greenapps

回答

1

指定「AES/ECB/NoPadding」。

隨着歐洲央行沒有iv,因此不需要提供一個調用encrypt方法。 ECB模式不安全,請參閱ECB mode,向下滾動到企鵝。

AES是分組密碼,因此它一次加密塊大小的部分,因此輸入需要是塊大小的倍數。填充是透明地完成的,但是您指定了「NoPadding」,因此對於16字節的AES,輸入文件大小隻是塊大小的確切倍數。而是使用PKCS#7(有些稱爲PKCS#5)填充。

最簡單的解決方案是使用一個庫,將安全加密的所有元素放在一起,包括密碼派生,隨機iv,填充,加密驗證。考慮RNCryptor,它提供了所有這些加上版本控制。有關更多信息,請參閱RNCryptor READMERNCryptor-Spec

+0

感謝您的答案,但在這裏,不用擔心保存文件而不是填充 – Tharindu

+0

AES是分組密碼,輸入**必須**是ECB,CBC和其他模式的塊大小的倍數。所以要麼擔心填充或希望得到幸運,你的選擇。 – zaph

相關問題