我正在遵循有关数据加密的文档-https://developer.android.com/topic/security/data
读取EncryptedFile时出现错误,即-java.io.FileNotFoundException: androidx.security.crypto.EncryptedFile@742ce5e (No such file or directory)
这是我的代码-
public class ReadWriteChat {
private KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
private String masterKeyAlias;
{
try {
masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Context context;
public ReadWriteChat(Context context){
this.context = context;
}
public boolean write(){
String fileToWrite = "my_sensitive_data.txt";
try {
EncryptedFile encryptedFile = new EncryptedFile.Builder(
new File(context.getFilesDir(), fileToWrite),
context,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
// Write to a file.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
encryptedFile.openFileOutput()));
writer.write("MY SUPER-SECRET INFORMATION");
} catch (GeneralSecurityException gse) {
Log.d("GeneralSecurityExcepn 2",gse.toString());
gse.printStackTrace();
return false;
} catch (IOException ex) {
Log.d("IOException write",ex.toString());
ex.printStackTrace();
return false;
}
return true;
}
public String read(){
String fileToRead = "my_sensitive_data.txt";
EncryptedFile encryptedFile = null;
StringBuffer stringBuffer = new StringBuffer();
try {
encryptedFile = new EncryptedFile.Builder(
new File(context.getFilesDir(), fileToRead),
context,
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("Read Write", e.toString());
e.printStackTrace();
}
try (BufferedReader reader =
new BufferedReader(new FileReader(String.valueOf(encryptedFile)))) { //Getting error in this line.
String line = reader.readLine();
while (line != null) {
stringBuffer.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
Log.d("IOException read",e.toString()); //this line is printing the error.
e.printStackTrace();
return "";
} finally {
String contents = stringBuffer.toString();
return contents;
}
}
}
我得到encryptedFile
,但在尝试读取它时抛出错误。
请告诉我缺少了什么?