JNCryptor - RNCryptor Шифрование / дешифрование файлов изображений
Я пытаюсь заставить шифрование / дешифрование изображений работать с использованием AES256 реализации библиотеки RNCryptor.
Это мой код до сих пор:
//Encrypt file
/**
*
var encryptedData = RNCryptor.encrypt(data: data as Data, withPassword: hashKey.description)
try encryptedData.write(to: fileURL)
* */
fun encryptFile( inputFile : File ) : File {
val size = inputFile.length().toInt()
val fileBytes = ByteArray(size)
val aeS256JNCryptor = AES256JNCryptor()
val file = File(Environment.getExternalStorageDirectory().toString() + "/Encrypted_" + inputFile.name)
try {
val buf = BufferedInputStream(FileInputStream(inputFile))
buf.read(fileBytes, 0, fileBytes.size)
val encryptedFileBytes = aeS256JNCryptor.encryptData(fileBytes, "master".toCharArray())
val bufOut = BufferedOutputStream(FileOutputStream(file))
bufOut.write(encryptedFileBytes)
buf.close()
bufOut.close()
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return file
}
//Decrypt file
/**
*
let encryptedData = fileManager.contents(atPath: filePathNormal)
let decryptedData = try RNCryptor.decrypt(data: encryptedData!, withPassword: hashKey.description)
let selected_image = UIImage.sd_image(with: decryptedData)
* */
fun decryptFile( inputFile : File ) : File {
val size = inputFile.length().toInt()
val fileBytes = ByteArray(size)
val aeS256JNCryptor = AES256JNCryptor()
val file = File(Environment.getExternalStorageDirectory().toString() + "/Decrypted_" + inputFile.name)
try {
val buf = BufferedInputStream(FileInputStream(inputFile))
buf.read(fileBytes, 0, fileBytes.size)
val decryptedFileBytes = aeS256JNCryptor.decryptData(fileBytes, "master".toCharArray())
val bufOut = BufferedOutputStream(file.outputStream())
bufOut.write(decryptedFileBytes)
buf.close()
bufOut.close()
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return file
}
После расшифровки я не могу загрузить / просмотреть изображение. Я разместил соответствующий код iOS, используемый в комментариях. Пожалуйста, дайте мне знать, если я где-то не так.
Вот кое-что, что я уже пытался безуспешно:
fun decryptFile( inputFile : File ) : File {
val size = inputFile.length().toInt()
val fileBytes = ByteArray(size)
val aeS256JNCryptor = AES256JNCryptor()
val file = File(Environment.getExternalStorageDirectory().toString() + "/Decrypted_" + inputFile.name)
try {
val buf = BufferedInputStream(FileInputStream(inputFile))
buf.read(fileBytes, 0, fileBytes.size)
val decryptedFileBytes = aeS256JNCryptor.decryptData(fileBytes, "master".toCharArray())
if( file.exists() ) file.delete()
//val bufOut = BufferedOutputStream(file.outputStream())
//bufOut.write(decryptedFileBytes)
val fileOutputStream = FileOutputStream( file.absolutePath )
fileOutputStream.write(decryptedFileBytes)
buf.close()
fileOutputStream.close()
//bufOut.close()
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return file
}
Альтернативный способ сохранить растровое изображение:
val fileOutputStream = FileOutputStream( file.absolutePath )
//fileOutputStream.write(decryptedFileBytes)
val bitmap = BitmapFactory.decodeByteArray(decryptedFileBytes, 0, decryptedFileBytes.size)
if( bitmap != null )
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
buf.close()
fileOutputStream.close()
Я могу видеть расшифрованный файл, размер совпадает с размером исходного файла, пробовал отладку преобразования байтового массива, чтобы убедиться, что байты совпадают с оригиналом.
Я не могу открыть файл ни в приложении Галерея, ни в приложении при загрузке его в режиме просмотра изображений.
1 ответ
Это было решено путем изменения способа шифрования и использования пароля.
Вот что сработало:
//Encrypt file
/**
*
var encryptedData = RNCryptor.encrypt(data: data as Data, withPassword: hashKey.description)
try encryptedData.write(to: fileURL)
fileBytes - 3,1,-54,106
encrypted - 3,1,71,68
* */
fun encryptFile( inputFile : File, privateKey : CharArray ) : File {
val size = inputFile.length().toInt()
val fileBytes = ByteArray(size)
val aeS256JNCryptor = AES256JNCryptor()
val file = File(Environment.getExternalStorageDirectory().toString() + "/Encrypted_" + inputFile.name)
try {
val buf = BufferedInputStream(FileInputStream(inputFile))
buf.read(fileBytes, 0, fileBytes.size)
val encryptedFileBytes = aeS256JNCryptor.encryptData(fileBytes, privateKey)
val bufOut = BufferedOutputStream(FileOutputStream(file))
bufOut.write(encryptedFileBytes)
buf.close()
bufOut.close()
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return file
}
//Decrypt file
/**
*
let encryptedData = fileManager.contents(atPath: filePathNormal)
let decryptedData = try RNCryptor.decrypt(data: encryptedData!, withPassword: hashKey.description)
let selected_image = UIImage.sd_image(with: decryptedData)
encrypted - 3,1,71,68
decrypted Bytes - 3,1,-54,106
* */
fun decryptFile( inputFile : File, privateKey: CharArray ) : File {
val size = inputFile.length().toInt()
val fileBytes = ByteArray(size)
val aeS256JNCryptor = AES256JNCryptor()
val file = File(Environment.getExternalStorageDirectory().toString() + "/Decrypted_" + inputFile.name)
try {
val buf = BufferedInputStream(FileInputStream(inputFile))
buf.read(fileBytes, 0, fileBytes.size)
val decryptedFileBytes = aeS256JNCryptor.decryptData(fileBytes, privateKey)
if( file.exists() ) file.delete()
val fileOutputStream = FileOutputStream( file.absolutePath )
fileOutputStream.write(decryptedFileBytes)
buf.close()
fileOutputStream.close()
} catch (e: FileNotFoundException) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return file
}
privateKey - это произвольная буквенно-цифровая строка длиной 16. После создания ее необходимо повторно использовать при шифровании и дешифровании файла.