Tem*_*Dev 7 encryption android file
使用Android的EncryptedFile(androidx.security:security-crypto:1.1.0-alpha01),我可以使用以下代码成功写入文件
File file = new File(context.getFilesDir() + File.separator + filename);
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
EncryptedFile encryptedFile = null;
try {
String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
encryptedFile = new EncryptedFile.Builder(
file,
context,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
} catch (Exception exception) {
// log error
}
// write file
try {
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(encryptedFile.openFileOutput()));
bufferedWriter.write(string);
bufferedWriter.close();
} catch (Exception exception) {
// log error
}
Run Code Online (Sandbox Code Playgroud)
但是,当试图覆盖同一个文件时,写操作失败并抛出以下内容
java.io.IOException: output file already exists, please use a new file
Run Code Online (Sandbox Code Playgroud)
我发现这是对 EncryptedFile 的显式检查 openFileOutput()
if (mFile.exists()) {
throw new IOException("output file already exists, please use a new file: "
+ mFile.getName());
}
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题,我能够通过在使用它构建 EncryptedFile 之前删除文件(如果它存在)来成功覆盖
File file = new File(context.getFilesDir() + File.separator + filename);
if (file.exists()) { file.delete(); }
... remaining code from top snippet above
Run Code Online (Sandbox Code Playgroud)
这似乎是一种黑客行为,但我也不明白为mFile.exists()in抛出异常的选择openFileOutput()。有没有正确/更好的方法来覆盖EncryptedFile?
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |