aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/dev/msfjarvis/aps/data
diff options
context:
space:
mode:
authorHarsh Shandilya <me@msfjarvis.dev>2022-01-09 17:04:16 +0530
committerGitHub <noreply@github.com>2022-01-09 17:04:16 +0530
commit1738879fb3ba1b2c2d0ca7933c861bf99ae32535 (patch)
tree42b339b07e3c45922310afd01e8ce357f99beeb6 /app/src/main/java/dev/msfjarvis/aps/data
parent799f1393e49955d05f68b81af26d6cfaf9beadfd (diff)
downloadHardenedPass-1738879fb3ba1b2c2d0ca7933c861bf99ae32535.tar.gz
HardenedPass-1738879fb3ba1b2c2d0ca7933c861bf99ae32535.zip
Integrate PGPainless backend into the UI properly (#1647)
Diffstat (limited to 'app/src/main/java/dev/msfjarvis/aps/data')
-rw-r--r--app/src/main/java/dev/msfjarvis/aps/data/crypto/CryptoRepository.kt58
1 files changed, 58 insertions, 0 deletions
diff --git a/app/src/main/java/dev/msfjarvis/aps/data/crypto/CryptoRepository.kt b/app/src/main/java/dev/msfjarvis/aps/data/crypto/CryptoRepository.kt
new file mode 100644
index 00000000..b0cde380
--- /dev/null
+++ b/app/src/main/java/dev/msfjarvis/aps/data/crypto/CryptoRepository.kt
@@ -0,0 +1,58 @@
+/*
+ * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved.
+ * SPDX-License-Identifier: GPL-3.0-only
+ */
+
+package dev.msfjarvis.aps.data.crypto
+
+import com.github.michaelbull.result.runCatching
+import com.github.michaelbull.result.unwrap
+import dev.msfjarvis.aps.crypto.PGPKeyManager
+import dev.msfjarvis.aps.crypto.PGPainlessCryptoHandler
+import dev.msfjarvis.aps.util.extensions.isOk
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import javax.inject.Inject
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+class CryptoRepository
+@Inject
+constructor(
+ private val pgpKeyManager: PGPKeyManager,
+ private val pgpCryptoHandler: PGPainlessCryptoHandler,
+) {
+
+ suspend fun decrypt(
+ password: String,
+ message: ByteArrayInputStream,
+ out: ByteArrayOutputStream,
+ ) {
+ withContext(Dispatchers.IO) { decryptPgp(password, message, out) }
+ }
+
+ suspend fun encrypt(content: ByteArrayInputStream, out: ByteArrayOutputStream) {
+ withContext(Dispatchers.IO) { encryptPgp(content, out) }
+ }
+
+ private suspend fun decryptPgp(
+ password: String,
+ message: ByteArrayInputStream,
+ out: ByteArrayOutputStream,
+ ) {
+ val keys = pgpKeyManager.getAllKeys().unwrap()
+ // Iterates through the keys until the first successful decryption, then returns.
+ keys.first { key ->
+ runCatching { pgpCryptoHandler.decrypt(key, password, message, out) }.isOk()
+ }
+ }
+
+ private suspend fun encryptPgp(content: ByteArrayInputStream, out: ByteArrayOutputStream) {
+ val keys = pgpKeyManager.getAllKeys().unwrap()
+ pgpCryptoHandler.encrypt(
+ keys,
+ content,
+ out,
+ )
+ }
+}