嗨,我正在使用 jetpack 安全加密库来加密文件。我已经用下面的代码生成了万能钥匙。
MasterKey masterKey = null;
try {
masterKey = new
MasterKey.Builder(context, MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
.build();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
我已加密我的文本文件 Sample.txt 并将加密文件写入设备外部存储。代码如下。
InputStream inputStream = new BufferedInputStream(appCtx.getAssets().open("Sample.txt"));
byte[] fileBytes=new byte[inputStream.available()];
inputStream.read(fileBytes);
File file = new File(Environment.getExternalStorageDirectory(), "Sample.txt");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
EncryptedFile encryptedFile = new EncryptedFile.Builder(
appCtx,
file,
masterKey,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
OutputStream outputStream = encryptedFile.openFileOutput();
outputStream.write(fileBytes);
outputStream.flush();
outputStream.close();
我将加密文件放在资产文件夹中,现在尝试解密,但根据文档 EncryptedFile.Builder 始终将文件对象作为参数,目前我在从资产读取文件后有 Inputstream。因此,为了获取文件对象,我将此 Inutstream 作为 Temp.txt 写入外部存储,并将此文件传递给解密。但我收到异常java.io.IOException: No matching key found for the ciphertext in the stream。
解密代码如下:
InputStream myInputstream = new BufferedInputStream(appCtx.getAssets().open("Sample.txt"));
File enfile = createFileFromInputStream(myInputstream,appCtx);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
EncryptedFile encryptedFile = new EncryptedFile.Builder(
appCtx,
enfile,
masterKey,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
InputStream inputStream1 = encryptedFile.openFileInput();
BufferedOutputStream os1 = new BufferedOutputStream( new FileOutputStream(new File(dstPath)));
int length = 0;
byte[] buffer = new byte[1024];
while ((length = inputStream1.read(buffer)) != -1) {
os1.write(buffer, 0, length);
}
os1.close();
}
private static File createFileFromInputStream(InputStream stream, Context context) {
File f = new File(Environment.getExternalStorageDirectory(), "Temp.txt");
BufferedOutputStream os1 = null;
try {
os1 = new BufferedOutputStream( new FileOutputStream(f));
int length = 0;
byte[] buffer = new byte[1024];
while ((length = stream.read(buffer)) != -1) {
os1.write(buffer, 0, length);
}
os1.close();
stream.close();
return f;
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
//Logging exception
}
return null;
}
主要场景: 如果将加密文件写入外部存储并直接从外部存储读取解密,那么一切都是工作文件。但是,如果我将加密文件粘贴到资产文件夹中并将从资产文件夹获取的 Inputstream 写入某个临时文件,然后尝试解密它会给出错误 java.io.IOException: No matching key found for the ciphertext in the stream。
请任何人帮助我解决这个问题。谢谢