解密使用Jetpack加密的文件时出错



解密无结果

我正在做的是简单的加密和解密。加密按预期进行,但从加密文件中获得-1字节。我搜索了很多,但没有文件解决方案。甚至没有得到任何与密钥、文件或其他东西相关的错误。

我已经做了什么

  1. 我将目录从应用程序特定更改为外部(相同)
  2. 我的路径不包含空格
  3. 在主线程和后台线程上运行没有运气。3天了,还是找不到问题。
  4. ">

try {
//ENCRYPT FILE
File fileToEncrypt = new File(fileModel.getFilePath());
if (fileToEncrypt.exists()){
File encryptedFile = new File(fileHelper.getAppPhotosDirectory(), fileToEncrypt.getName());
if (encryptedFile.exists()) encryptedFile.delete();
FileInputStream fileInputStream = new FileInputStream(fileToEncrypt);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int nextByte = fileInputStream.read();
while (nextByte != -1){
byteArrayOutputStream.write(nextByte);
nextByte = fileInputStream.read();
}
KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(
MasterKey.DEFAULT_MASTER_KEY_ALIAS,
KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256).build();
MasterKey masterKey = new MasterKey.Builder(requireContext().getApplicationContext(), MasterKey.DEFAULT_MASTER_KEY_ALIAS)
.setKeyGenParameterSpec(keyGenParameterSpec).build();
EncryptedFile encryptedFileStreamer = new EncryptedFile.Builder(
requireContext().getApplicationContext(),
encryptedFile,
masterKey,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB).build();
OutputStream outputStream = encryptedFileStreamer.openFileOutput();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
outputStream.close();
fileInputStream.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
if (encryptedFile.exists()){
FileModel encryptedFileModel = new FileModel(encryptedFile.getName(), encryptedFile.getPath());
Log.d("analyze", "File encrypted in: "+encryptedFileModel.getFilePath());
Log.d("analyze", "Now decrypting file again"+encryptedFileModel.getFilePath());
String pathToDecrypt = fileHelper.getAppTempDirectory();

InputStream inputStream = encryptedFileStreamer.openFileInput();
Log.d("analyze", "First byte from file: "+inputStream.read());

}else{
Log.d("analyze", "File not encrypted");
}
}
//DECRYPT FILE
} catch (GeneralSecurityException | IOException generalSecurityException){
generalSecurityException.printStackTrace();
}

您可以在jetpack EncryptedFile security中读取图像加密

你不应该使用inputStream.read()

使用字节数组缓冲区来读取:inputStream.read(buffer)

最新更新