У меня есть приложение android, которое запрашивает зашифрованный файл с сервера и сохраняет его в каталоге файлов приложения, файлы PDF перечислены в приложении и открывает файл PDF после расшифровки файла PDF при нажатии. Я успешно могу зашифровать файл на сервере и расшифровать файл в приложении, так как строки выглядят одинаково. Но после преобразования расшифрованной строки в файл PDF приложение не может открыть файл, или система android не может открыть файлы, говорит поврежденный формат.
PHP функция для шифрования файла :
function encFile($data){
$iv = openssl_random_pseudo_bytes(16,$secure);
if (false === $iv) {
throw new \RuntimeException('iv generation failed');
}
$data = $iv . openssl_encrypt($data, 'AES-128-CBC', 'RfTjWnZr4u7x!A%D', OPENSSL_RAW_DATA, $iv);
$data=base64_encode($data);
//echo $data;
return $data;
}
После получения зашифрованной строки:
$encData=encFile($data);
$fullFileName="EncFiles/temp".time().".pdf";
file_put_contents($fullFileName, $encData);
Java функция, которая расшифровывает ее и создает файл PDF:
private void decFile(String fileLocation) throws IOException {
//File to String
File encFile=new File(fileLocation);
InputStream inputStream=null;
try {
inputStream = new FileInputStream(encFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
final StringBuilder stringBuilder = new StringBuilder();
boolean done = false;
while (!done) {
String line=null;
try {
line = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
done = (line == null);
if (line != null) {
stringBuilder.append(line);
}
}
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
inputStream.close();
String encString=stringBuilder.toString();
Log.i("encString",encString);
//Start Decryption
byte[] data64= android.util.Base64.decode(encString, android.util.Base64.DEFAULT);
if(data64.length < 17) {
Toast.makeText(this,"Something went Wrong",Toast.LENGTH_SHORT).show();
}
Log.i("decString",data64+"");
byte[] ivBytes = Arrays.copyOfRange(data64, 0, 16);
byte[] contentBytes = Arrays.copyOfRange(data64, 16, data64.length);
Log.i("decString",contentBytes+"");
try {
Cipher ciper = Cipher.getInstance("AES/CBC/PKCS5Padding");
String temp=getDecKey();
SecretKeySpec keySpec = new SecretKeySpec(temp.getBytes("UTF-8"),"AES");
IvParameterSpec iv = new IvParameterSpec(ivBytes,0, ciper.getBlockSize());
ciper.init(Cipher.DECRYPT_MODE, keySpec, iv);
byte[] decString=ciper.doFinal(contentBytes);
//Bytes to string
// String s= new String(decString);
// Log.i("decRYPTED STRING",s);
//Bytes to File;
long millis = System.currentTimeMillis();
long seconds = millis / 1000;
String path=this.getFilesDir().getAbsolutePath()+"/decFile_"+seconds+".pdf";
Log.i("PATH",path);
File decFile = new File(path);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decFile));
bos.write(decString);
bos.flush();
bos.close();
Log.i("DEC",decFile.getAbsoluteFile().toString());
Intent intent = new Intent(this,PDFWebViewActivity.class);
intent.putExtra("fromOffline",1);
intent.putExtra("filelocation",decFile.getAbsoluteFile().toString());
startActivity(intent);
} catch (
NoSuchAlgorithmException |
NoSuchPaddingException |
UnsupportedEncodingException |
InvalidAlgorithmParameterException |
InvalidKeyException |
IllegalBlockSizeException |
BadPaddingException ignored
) {
//ignored.printStackTrace();
ignored.printStackTrace();
}
}
Я использую PDF. js и веб-просмотр для просмотра PDF. Пожалуйста, помогите мне решить проблему.
Редактировать: Взял ссылку от https://gist.github.com/Haehnchen/3cb18c40fea2ab883ef1a7a8e25422dc