我正在開發一個項目來加密/解密文件。因爲這是我第一次,我想知道如果我做對了還是不對。到現在爲止,我對加密的想法是這樣的:Java加密文件數據並將其寫入同一文件
選擇一個文件- >閱讀它的所有字節,並把它添加到字節數組- >加密的字節數組- >寫入同一個文件的加密字節。
請注意,在此項目中輸出文件與輸入文件相同。所以我決定在寫入加密字節之前清除文件。
這可能是愚蠢的(而這就是爲什麼我要求幫助),所以這裏是我的方式
public class Encryptor {
File file;
SecretKeySpec secretKeySpec;
public void setFile(String filePath) throws Exception {
this.file = new File(filePath);
if(!file.isFile()){
throw new Exception("The file you choosed is not valid");
}
}
public void setKey(String keyword){
try {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(keyword.getBytes("UTF-8"));
byte[] key = sha.digest();
secretKeySpec = new SecretKeySpec(key, "AES");
} catch (UnsupportedEncodingException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public void encrypt(){
byte[] bFile = new byte[(int) file.length()];
try {
//adding portocol bytes to the file bytes
//String portcol = "encryptor portocol";
//byte[] decPortocol = portcol.getBytes();
//convert file into array of bytes
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
bufferedInputStream.read(bFile);
bufferedInputStream.close();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//outputStream.write(decPortocol);
outputStream.write(bFile);
byte[] cryptedFileBytes = outputStream.toByteArray();
//Cipher and encrypting
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(cryptedFileBytes);
//Write Encrypted File
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file,false));
bufferedOutputStream.write(encryptedBytes);
bufferedOutputStream.flush();
bufferedOutputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
主要問題
有其他的方式來讀取加密寫入同一時間在同一個文件上?就像逐字節讀取字節一樣,同時對該部分進行加密並用加密字節覆蓋它。
你能幫助我嗎?
還有關於如何使我的加密文件更安全的任何信息也可能會有所幫助。
和我的程序殺死RAM?!
(NOTE)由於某些原因,我在同一個文件上寫了加密數據。我對硬盤的工作原理並不熟悉。我的理由之一是防止以後恢復文件。有什麼我必須知道的嗎?我在做什麼防止未加密的文件以後恢復?
編輯 @erickson指出在他的回答一些重要的東西。我知道這種加密文件的方式並不安全。我正在考慮防止也,阻止文件後來被恢復。我的意思是加密文件並將其保存在硬盤中是沒有任何意義的,如果你曾經將它加密的話。根據我的經驗,每次我恢復一個文件,我都會對其進行最後編輯,並且我永遠無法獲得更改的歷史記錄。如果我在第一時間沒有錯,我認爲這一定是一樣的。我該如何幫助防止數據恢復呢?
處理您描述的操作的標準方法是創建一個新文件,將處理過的字節寫入它,然後刪除輸入文件。例如,參見'gzip'。在任何現代(日誌式)文件系統上,無論如何你都不會重寫數據;你根本無法控制。 – chrylis
@chrylis我知道這不是標準的方法。我可以處理在其他目錄中寫入輸出文件。正如我已經指出的那樣,我有一些理由以非標準的方式來做到這一點(我確實對它們有懷疑)。像防止文件恢復以後訪問普通(未加密)文件和其他... –
瞭解,但在原地覆蓋文件將無法完成,所以這是很多併發症,沒有任何好處。 – chrylis