当我尝试解密文件时,我正在Node.js客户端中加密文件并将其保存为文件,
Encryptor.encryptFile = function (inputPath, outputPath, key, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = Encryptor.combineOptions(options);
var keyBuf = new Buffer(key);
console.log(key)
var inputStream = fs.createReadStream(inputPath);
var outputStream = fs.createWriteStream(outputPath);
var cipher = crypto.createCipher(options.algorithm, keyBuf);
inputStream.on('data', function (data) {
console.log(data.length)
var buf = new Buffer(cipher.update(data));
outputStream.write(buf);
});
inputStream.on('end', function () {
try {
var buf = new Buffer(cipher.final('binary'), 'binary');
outputStream.write(buf);
outputStream.end();
outputStream.on('close', function () {
return callback();
});
} catch (e) {
fs.unlink(outputPath);
return callback(e);
}
});
};
上面是加密代码,在Android方面,我使用以下代码。 文件下载:
Ion.with(this).load(documentModel.filePath)
.progress { downloaded, total -> println("$downloaded / $total") }
.write(file)
.setCallback { e, result ->
if (result != null) {
// val keys = MedpayDatabaseHelper.getInstance(this@ViewMedicalRecordActivity)?.keyDao()?.getKeys()
val handler = EncryptionHandler()
val decrepted = handler.decryptFile(handler.getSymmetricKey(), result)
val outfile = File(dir, "output.pdf")
pdfView.fromBytes(decrepted).load()
} else {
Toast.makeText(this@ViewMedicalRecordActivity, "Failed to load file", Toast.LENGTH_LONG).show()
}
}
以下是解密代码。
fun decryptFile(symmetricKey: String, file: File): ByteArray {
encryptionAlgorithm = "AES"
encryptionMode = "/ECB"
paddingMode = "/NoPadding"
return decrypt(symmetricKey, file)
}
private fun decrypt(decryptionKey: String, file: File): ByteArray {
val inputStream = BufferedReader(InputStreamReader(FileInputStream(file), Charsets.UTF_16BE))
var x: String? = ""
var builder = StringBuilder()
while (x != null) {
x = inputStream.readLine()
if (x != null)
builder.append(x).append('\n')
}
val text = builder.toString()
val read = text.toByteArray().decrypt(decryptionKey)
val path = Environment.getExternalStorageDirectory().absolutePath + "/folder"
val dir = File(path)
if (!dir.exists())
dir.mkdirs()
val outfile = File(dir, "output.pdf")
val dos = OutputStreamWriter(FileOutputStream(outfile))
dos.write(read.toString(Charsets.UTF_16LE))
dos.flush()
dos.close()
return read
}
//extension function for decrypting the byte array
private fun ByteArray.decrypt(decryptionKey: String): ByteArray {
val secretKeySpec = SecretKeySpec(decryptionKey.toByteArray(), encryptionAlgorithm)
val cipher = Cipher.getInstance(encryptionAlgorithm + encryptionMode + paddingMode)
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec)
return cipher.doFinal(this)
}
由于我是密码学的新手,所以我不确定自己出了什么问题,但我认为这与文件格式和编码有关。 这些文件已解密,没有任何错误,但是当我尝试用代码或从文件资源管理器打开文件时,仍然会引发以下异常。
E/PDFView: load pdf error
java.io.IOException: cannot create document: File not in PDF format or corrupted.
at com.shockwave.pdfium.PdfiumCore.nativeOpenMemDocument(Native Method)