Я пытаюсь зашифровать большие файлы в Android с помощью AES, но мне не удалось зашифровать нехватку памяти.
Вот код, который я использую:
import android.content.Context
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import timber.log.Timber
import java.io.IOException
import javax.crypto.Cipher
import javax.crypto.CipherOutputStream
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
suspend fun encryptFile(
context: Context,
file: DocumentFile,
secretByte: ByteArray,
iv: ByteArray
) {
try {
val bufferSize = 1024 * 1024
val secretKeySpec = SecretKeySpec(secretByte, "AES")
val encryptedFileUri = createEncryptedFileUri(file)
?: throw IOException("Failed to create URI for encrypted file")
context.contentResolver.openOutputStream(encryptedFileUri)?.use { outputStream ->
context.contentResolver.openInputStream(file.uri)?.use { inputStream ->
val buffer = ByteArray(bufferSize)
var bytesRead: Int
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val gcmSpec = GCMParameterSpec(128, iv)
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmSpec)
CipherOutputStream(outputStream, cipher).use { cipherOutputStream ->
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
cipherOutputStream.write(buffer, 0, bytesRead)
}
cipherOutputStream.flush()
}
} ?: throw IOException("Failed to open input stream for file: ${file.uri}")
} ?: throw IOException("Failed to open output stream for file: $encryptedFileUri")
if (!file.delete()) {
Timber.e("Failed to delete original file: ${file.uri}")
}
} catch (e: Exception) {
e.printStackTrace()
Timber.e("Error during file encryption: ${e.message}")
}
}
private fun createEncryptedFileUri(file: DocumentFile): Uri? {
val parentDirectory = file.parentFile ?: throw IllegalArgumentException("No parent directory")
return parentDirectory.createFile("*/*", file.name + ".aesEncr")?.uri
}
Я получаю сообщение об ошибке:
java.lang.OutOfMemoryError: Failed to allocate a 266338320 byte allocation with 25165824 free bytes and 121MB until OOM, target footprint 166187728, growth limit 268435456
at com.android.org.conscrypt.OpenSSLAeadCipher.expand(OpenSSLAeadCipher.java:127)
at com.android.org.conscrypt.OpenSSLAeadCipher.updateInternal(OpenSSLAeadCipher.java:300)
at com.android.org.conscrypt.OpenSSLCipher.engineUpdate(OpenSSLCipher.java:332)
at javax.crypto.Cipher.update(Cipher.java:1741)
at javax.crypto.CipherOutputStream.write(CipherOutputStream.java:158)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
Suppressed: java.lang.OutOfMemoryError: Failed to allocate a 132120608 byte allocation with 25165824 free bytes and 121MB until OOM, target footprint 166188144, growth limit 268435456
at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:359)
at javax.crypto.Cipher.doFinal(Cipher.java:1957)
Подробнее здесь: https://stackoverflow.com/questions/790 ... -of-memory
Ошибка шифрования/дешифрования больших файлов Android AES из-за нехватки памяти ⇐ Android
Форум для тех, кто программирует под Android
1727100372
Anonymous
Я пытаюсь зашифровать большие файлы в Android с помощью AES, но мне не удалось зашифровать нехватку памяти.
Вот код, который я использую:
import android.content.Context
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import timber.log.Timber
import java.io.IOException
import javax.crypto.Cipher
import javax.crypto.CipherOutputStream
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
suspend fun encryptFile(
context: Context,
file: DocumentFile,
secretByte: ByteArray,
iv: ByteArray
) {
try {
val bufferSize = 1024 * 1024
val secretKeySpec = SecretKeySpec(secretByte, "AES")
val encryptedFileUri = createEncryptedFileUri(file)
?: throw IOException("Failed to create URI for encrypted file")
context.contentResolver.openOutputStream(encryptedFileUri)?.use { outputStream ->
context.contentResolver.openInputStream(file.uri)?.use { inputStream ->
val buffer = ByteArray(bufferSize)
var bytesRead: Int
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val gcmSpec = GCMParameterSpec(128, iv)
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmSpec)
CipherOutputStream(outputStream, cipher).use { cipherOutputStream ->
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
cipherOutputStream.write(buffer, 0, bytesRead)
}
cipherOutputStream.flush()
}
} ?: throw IOException("Failed to open input stream for file: ${file.uri}")
} ?: throw IOException("Failed to open output stream for file: $encryptedFileUri")
if (!file.delete()) {
Timber.e("Failed to delete original file: ${file.uri}")
}
} catch (e: Exception) {
e.printStackTrace()
Timber.e("Error during file encryption: ${e.message}")
}
}
private fun createEncryptedFileUri(file: DocumentFile): Uri? {
val parentDirectory = file.parentFile ?: throw IllegalArgumentException("No parent directory")
return parentDirectory.createFile("*/*", file.name + ".aesEncr")?.uri
}
Я получаю сообщение об ошибке:
java.lang.OutOfMemoryError: Failed to allocate a 266338320 byte allocation with 25165824 free bytes and 121MB until OOM, target footprint 166187728, growth limit 268435456
at com.android.org.conscrypt.OpenSSLAeadCipher.expand(OpenSSLAeadCipher.java:127)
at com.android.org.conscrypt.OpenSSLAeadCipher.updateInternal(OpenSSLAeadCipher.java:300)
at com.android.org.conscrypt.OpenSSLCipher.engineUpdate(OpenSSLCipher.java:332)
at javax.crypto.Cipher.update(Cipher.java:1741)
at javax.crypto.CipherOutputStream.write(CipherOutputStream.java:158)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:108)
at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:115)
at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:103)
at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:584)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:793)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:697)
at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:684)
Suppressed: java.lang.OutOfMemoryError: Failed to allocate a 132120608 byte allocation with 25165824 free bytes and 121MB until OOM, target footprint 166188144, growth limit 268435456
at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:359)
at javax.crypto.Cipher.doFinal(Cipher.java:1957)
Подробнее здесь: [url]https://stackoverflow.com/questions/79013458/android-aes-large-file-encryption-decryption-failed-with-out-of-memory[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия