From 549ee790d3e52bc62565ddf92e6a556e98b5195e Mon Sep 17 00:00:00 2001 From: Harsh Shandilya Date: Fri, 15 Jul 2022 00:53:48 +0530 Subject: all: re-do package structure yet again --- .../app/passwordstore/crypto/GpgIdentifier.kt | 99 +++++++++++ .../kotlin/app/passwordstore/crypto/KeyUtils.kt | 37 ++++ .../main/kotlin/app/passwordstore/crypto/PGPKey.kt | 12 ++ .../app/passwordstore/crypto/PGPKeyManager.kt | 135 +++++++++++++++ .../crypto/PGPainlessCryptoHandler.kt | 110 ++++++++++++ .../dev/msfjarvis/aps/crypto/GpgIdentifier.kt | 99 ----------- .../kotlin/dev/msfjarvis/aps/crypto/KeyUtils.kt | 37 ---- .../main/kotlin/dev/msfjarvis/aps/crypto/PGPKey.kt | 12 -- .../dev/msfjarvis/aps/crypto/PGPKeyManager.kt | 135 --------------- .../aps/crypto/PGPainlessCryptoHandler.kt | 110 ------------ .../app/passwordstore/crypto/CryptoConstants.kt | 14 ++ .../app/passwordstore/crypto/GpgIdentifierTest.kt | 41 +++++ .../app/passwordstore/crypto/KeyUtilsTest.kt | 24 +++ .../app/passwordstore/crypto/PGPKeyManagerTest.kt | 189 +++++++++++++++++++++ .../crypto/PGPainlessCryptoHandlerTest.kt | 78 +++++++++ .../kotlin/app/passwordstore/crypto/TestUtils.kt | 16 ++ .../dev/msfjarvis/aps/crypto/CryptoConstants.kt | 14 -- .../dev/msfjarvis/aps/crypto/GpgIdentifierTest.kt | 41 ----- .../dev/msfjarvis/aps/crypto/KeyUtilsTest.kt | 24 --- .../dev/msfjarvis/aps/crypto/PGPKeyManagerTest.kt | 189 --------------------- .../aps/crypto/PGPainlessCryptoHandlerTest.kt | 78 --------- .../kotlin/dev/msfjarvis/aps/crypto/TestUtils.kt | 16 -- 22 files changed, 755 insertions(+), 755 deletions(-) create mode 100644 crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/GpgIdentifier.kt create mode 100644 crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/KeyUtils.kt create mode 100644 crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKey.kt create mode 100644 crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKeyManager.kt create mode 100644 crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandler.kt delete mode 100644 crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifier.kt delete mode 100644 crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/KeyUtils.kt delete mode 100644 crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKey.kt delete mode 100644 crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManager.kt delete mode 100644 crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandler.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/CryptoConstants.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/GpgIdentifierTest.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/KeyUtilsTest.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPKeyManagerTest.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandlerTest.kt create mode 100644 crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/TestUtils.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/CryptoConstants.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifierTest.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/KeyUtilsTest.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManagerTest.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandlerTest.kt delete mode 100644 crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/TestUtils.kt (limited to 'crypto-pgpainless/src') diff --git a/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/GpgIdentifier.kt b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/GpgIdentifier.kt new file mode 100644 index 00000000..4aa4a57a --- /dev/null +++ b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/GpgIdentifier.kt @@ -0,0 +1,99 @@ +/* + * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +import java.util.Locale +import java.util.regex.Pattern + +public sealed class GpgIdentifier { + public data class KeyId(val id: Long) : GpgIdentifier() { + override fun toString(): String { + return convertKeyIdToHex(id) + } + + /** Convert a [Long] key ID to a formatted string. */ + private fun convertKeyIdToHex(keyId: Long): String { + return convertKeyIdToHex32bit(keyId shr 32) + convertKeyIdToHex32bit(keyId) + } + + /** + * Converts [keyId] to an unsigned [Long] then uses [java.lang.Long.toHexString] to convert it + * to a lowercase hex ID. + */ + private fun convertKeyIdToHex32bit(keyId: Long): String { + var hexString = java.lang.Long.toHexString(keyId and 0xffffffffL).lowercase(Locale.ENGLISH) + while (hexString.length < 8) { + hexString = "0$hexString" + } + return hexString + } + } + public data class UserId(val email: String) : GpgIdentifier() { + override fun toString(): String { + return email + } + } + + public companion object { + public fun fromString(identifier: String): GpgIdentifier? { + if (identifier.isEmpty()) return null + // Match long key IDs: + // FF22334455667788 or 0xFF22334455667788 + val maybeLongKeyId = + identifier.removePrefix("0x").takeIf { it.matches("[a-fA-F\\d]{16}".toRegex()) } + if (maybeLongKeyId != null) { + val keyId = maybeLongKeyId.toULong(16) + return KeyId(keyId.toLong()) + } + + // Match fingerprints: + // FF223344556677889900112233445566778899 or 0xFF223344556677889900112233445566778899 + val maybeFingerprint = + identifier.removePrefix("0x").takeIf { it.matches("[a-fA-F\\d]{40}".toRegex()) } + if (maybeFingerprint != null) { + // Truncating to the long key ID is not a security issue since OpenKeychain only + // accepts + // non-ambiguous key IDs. + val keyId = maybeFingerprint.takeLast(16).toULong(16) + return KeyId(keyId.toLong()) + } + + return splitUserId(identifier)?.let { UserId(it) } + } + + private val USER_ID_PATTERN = Pattern.compile("^(.*?)(?: \\((.*)\\))?(?: <(.*)>)?$") + private val EMAIL_PATTERN = Pattern.compile("^\"]*@[^<>\"]*[.]?[^<>\"]*)\"?>?$") + + /** + * Takes a 'Name (Comment) ' user ID in any of its permutations and attempts to extract + * an email from it. + */ + private fun splitUserId(userId: String): String? { + if (userId.isNotEmpty()) { + val matcher = USER_ID_PATTERN.matcher(userId) + if (matcher.matches()) { + var name = if (matcher.group(1)?.isEmpty() == true) null else matcher.group(1) + var email = matcher.group(3) + if (email != null && name != null) { + val emailMatcher = EMAIL_PATTERN.matcher(name) + if (emailMatcher.matches() && email == emailMatcher.group(1)) { + email = emailMatcher.group(1) + name = null + } + } + if (email == null && name != null) { + val emailMatcher = EMAIL_PATTERN.matcher(name) + if (emailMatcher.matches()) { + email = emailMatcher.group(1) + } + } + return email + } + } + return null + } + } +} diff --git a/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/KeyUtils.kt b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/KeyUtils.kt new file mode 100644 index 00000000..39478751 --- /dev/null +++ b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/KeyUtils.kt @@ -0,0 +1,37 @@ +/* + * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +import app.passwordstore.crypto.GpgIdentifier.KeyId +import com.github.michaelbull.result.get +import com.github.michaelbull.result.runCatching +import org.bouncycastle.openpgp.PGPKeyRing +import org.pgpainless.PGPainless + +/** Utility methods to deal with [PGPKey]s. */ +public object KeyUtils { + /** + * Attempts to parse a [PGPKeyRing] from a given [key]. The key is first tried as a secret key and + * then as a public one before the method gives up and returns null. + */ + public fun tryParseKeyring(key: PGPKey): PGPKeyRing? { + val secKeyRing = runCatching { PGPainless.readKeyRing().secretKeyRing(key.contents) }.get() + if (secKeyRing != null) { + return secKeyRing + } + val pubKeyRing = runCatching { PGPainless.readKeyRing().publicKeyRing(key.contents) }.get() + if (pubKeyRing != null) { + return pubKeyRing + } + return null + } + + /** Parses a [PGPKeyRing] from the given [key] and calculates its long key ID */ + public fun tryGetId(key: PGPKey): KeyId? { + val keyRing = tryParseKeyring(key) ?: return null + return KeyId(keyRing.publicKey.keyID) + } +} diff --git a/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKey.kt b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKey.kt new file mode 100644 index 00000000..a33655d4 --- /dev/null +++ b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKey.kt @@ -0,0 +1,12 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +/** + * A simple value class wrapping over a [ByteArray] that can represent a PGP key. The implementation + * details of public/ private parts as well as identities are deferred to [PGPKeyManager]. + */ +@JvmInline public value class PGPKey(public val contents: ByteArray) diff --git a/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKeyManager.kt b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKeyManager.kt new file mode 100644 index 00000000..a80b5dcb --- /dev/null +++ b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPKeyManager.kt @@ -0,0 +1,135 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ +@file:Suppress("BlockingMethodInNonBlockingContext") + +package app.passwordstore.crypto + +import androidx.annotation.VisibleForTesting +import app.passwordstore.crypto.KeyUtils.tryGetId +import app.passwordstore.crypto.KeyUtils.tryParseKeyring +import app.passwordstore.crypto.errors.InvalidKeyException +import app.passwordstore.crypto.errors.KeyAlreadyExistsException +import app.passwordstore.crypto.errors.KeyDeletionFailedException +import app.passwordstore.crypto.errors.KeyDirectoryUnavailableException +import app.passwordstore.crypto.errors.KeyNotFoundException +import app.passwordstore.crypto.errors.NoKeysAvailableException +import app.passwordstore.util.coroutines.runSuspendCatching +import com.github.michaelbull.result.Result +import java.io.File +import javax.inject.Inject +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.withContext +import org.pgpainless.util.selection.userid.SelectUserId + +public class PGPKeyManager +@Inject +constructor( + filesDir: String, + private val dispatcher: CoroutineDispatcher, +) : KeyManager { + + private val keyDir = File(filesDir, KEY_DIR_NAME) + + override suspend fun addKey(key: PGPKey, replace: Boolean): Result = + withContext(dispatcher) { + runSuspendCatching { + if (!keyDirExists()) throw KeyDirectoryUnavailableException + if (tryParseKeyring(key) == null) throw InvalidKeyException + val keyFile = File(keyDir, "${tryGetId(key)}.$KEY_EXTENSION") + if (keyFile.exists()) { + // Check for replace flag first and if it is false, throw an error + if (!replace) + throw KeyAlreadyExistsException( + tryGetId(key)?.toString() ?: "Failed to retrieve key ID" + ) + if (!keyFile.delete()) throw KeyDeletionFailedException + } + + keyFile.writeBytes(key.contents) + + key + } + } + + override suspend fun removeKey(key: PGPKey): Result = + withContext(dispatcher) { + runSuspendCatching { + if (!keyDirExists()) throw KeyDirectoryUnavailableException + if (tryParseKeyring(key) == null) throw InvalidKeyException + val keyFile = File(keyDir, "${tryGetId(key)}.$KEY_EXTENSION") + if (keyFile.exists()) { + if (!keyFile.delete()) throw KeyDeletionFailedException + } + + key + } + } + + override suspend fun getKeyById(id: GpgIdentifier): Result = + withContext(dispatcher) { + runSuspendCatching { + if (!keyDirExists()) throw KeyDirectoryUnavailableException + val keyFiles = keyDir.listFiles() + if (keyFiles.isNullOrEmpty()) throw NoKeysAvailableException + val keys = keyFiles.map { file -> PGPKey(file.readBytes()) } + + val matchResult = + when (id) { + is GpgIdentifier.KeyId -> { + val keyIdMatch = + keys + .map { key -> key to tryGetId(key) } + .firstOrNull { (_, keyId) -> keyId?.id == id.id } + keyIdMatch?.first + } + is GpgIdentifier.UserId -> { + val selector = SelectUserId.byEmail(id.email) + val userIdMatch = + keys + .map { key -> key to tryParseKeyring(key) } + .firstOrNull { (_, keyRing) -> selector.firstMatch(keyRing) != null } + userIdMatch?.first + } + } + + if (matchResult != null) { + return@runSuspendCatching matchResult + } + + throw KeyNotFoundException("$id") + } + } + + override suspend fun getAllKeys(): Result, Throwable> = + withContext(dispatcher) { + runSuspendCatching { + if (!keyDirExists()) throw KeyDirectoryUnavailableException + val keyFiles = keyDir.listFiles() + if (keyFiles.isNullOrEmpty()) return@runSuspendCatching emptyList() + keyFiles.map { keyFile -> PGPKey(keyFile.readBytes()) }.toList() + } + } + + override suspend fun getKeyId(key: PGPKey): GpgIdentifier? = tryGetId(key) + + // TODO: This is a temp hack for now and in future it should check that the GPGKeyManager can + // decrypt the file. + override fun canHandle(fileName: String): Boolean { + return fileName.endsWith(KEY_EXTENSION) + } + + /** Checks if [keyDir] exists and attempts to create it if not. */ + private fun keyDirExists(): Boolean { + return keyDir.exists() || keyDir.mkdirs() + } + + public companion object { + + @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) + internal const val KEY_DIR_NAME: String = "keys" + @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) + internal const val KEY_EXTENSION: String = "key" + } +} diff --git a/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandler.kt b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandler.kt new file mode 100644 index 00000000..440b162e --- /dev/null +++ b/crypto-pgpainless/src/main/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandler.kt @@ -0,0 +1,110 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +import app.passwordstore.crypto.errors.CryptoHandlerException +import app.passwordstore.crypto.errors.IncorrectPassphraseException +import app.passwordstore.crypto.errors.NoKeysProvided +import app.passwordstore.crypto.errors.UnknownError +import com.github.michaelbull.result.Result +import com.github.michaelbull.result.mapError +import com.github.michaelbull.result.runCatching +import java.io.ByteArrayInputStream +import java.io.InputStream +import java.io.OutputStream +import javax.inject.Inject +import org.bouncycastle.openpgp.PGPPublicKeyRing +import org.bouncycastle.openpgp.PGPPublicKeyRingCollection +import org.bouncycastle.openpgp.PGPSecretKeyRingCollection +import org.pgpainless.PGPainless +import org.pgpainless.decryption_verification.ConsumerOptions +import org.pgpainless.encryption_signing.EncryptionOptions +import org.pgpainless.encryption_signing.ProducerOptions +import org.pgpainless.exception.WrongPassphraseException +import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector +import org.pgpainless.util.Passphrase + +public class PGPainlessCryptoHandler @Inject constructor() : CryptoHandler { + + public override fun decrypt( + privateKey: PGPKey, + passphrase: String, + ciphertextStream: InputStream, + outputStream: OutputStream, + ): Result = + runCatching { + val pgpSecretKeyRing = PGPainless.readKeyRing().secretKeyRing(privateKey.contents) + val keyringCollection = PGPSecretKeyRingCollection(listOf(pgpSecretKeyRing)) + val protector = + PasswordBasedSecretKeyRingProtector.forKey( + pgpSecretKeyRing, + Passphrase.fromPassword(passphrase) + ) + PGPainless.decryptAndOrVerify() + .onInputStream(ciphertextStream) + .withOptions( + ConsumerOptions() + .addDecryptionKeys(keyringCollection, protector) + .addDecryptionPassphrase(Passphrase.fromPassword(passphrase)) + ) + .use { decryptionStream -> decryptionStream.copyTo(outputStream) } + return@runCatching + } + .mapError { error -> + when (error) { + is WrongPassphraseException -> IncorrectPassphraseException(error) + else -> UnknownError(error) + } + } + + public override fun encrypt( + keys: List, + plaintextStream: InputStream, + outputStream: OutputStream, + ): Result = + runCatching { + if (keys.isEmpty()) throw NoKeysProvided("No keys provided for encryption") + val publicKeyRings = arrayListOf() + val armoredKeys = + keys.joinToString("\n") { key -> key.contents.decodeToString() }.toByteArray() + val secKeysStream = ByteArrayInputStream(armoredKeys) + val secretKeyRingCollection = + PGPainless.readKeyRing().secretKeyRingCollection(secKeysStream) + secretKeyRingCollection.forEach { secretKeyRing -> + publicKeyRings.add(PGPainless.extractCertificate(secretKeyRing)) + } + if (publicKeyRings.isEmpty()) { + val pubKeysStream = ByteArrayInputStream(armoredKeys) + val publicKeyRingCollection = + PGPainless.readKeyRing().publicKeyRingCollection(pubKeysStream) + publicKeyRings.addAll(publicKeyRingCollection) + } + require(publicKeyRings.isNotEmpty()) { "No public keys to encrypt message to" } + val publicKeyRingCollection = PGPPublicKeyRingCollection(publicKeyRings) + val encryptionOptions = EncryptionOptions().addRecipients(publicKeyRingCollection) + val producerOptions = ProducerOptions.encrypt(encryptionOptions).setAsciiArmor(false) + val encryptor = + PGPainless.encryptAndOrSign().onOutputStream(outputStream).withOptions(producerOptions) + plaintextStream.copyTo(encryptor) + encryptor.close() + val result = encryptor.result + publicKeyRingCollection.keyRings.forEach { keyRing -> + require(result.isEncryptedFor(keyRing)) { + "Stream should be encrypted for ${keyRing.publicKey.keyID} but wasn't" + } + } + } + .mapError { error -> + when (error) { + is CryptoHandlerException -> error + else -> UnknownError(error) + } + } + + public override fun canHandle(fileName: String): Boolean { + return fileName.split('.').lastOrNull() == "gpg" + } +} diff --git a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifier.kt b/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifier.kt deleted file mode 100644 index b7dcdd0d..00000000 --- a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifier.kt +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -import java.util.Locale -import java.util.regex.Pattern - -public sealed class GpgIdentifier { - public data class KeyId(val id: Long) : GpgIdentifier() { - override fun toString(): String { - return convertKeyIdToHex(id) - } - - /** Convert a [Long] key ID to a formatted string. */ - private fun convertKeyIdToHex(keyId: Long): String { - return convertKeyIdToHex32bit(keyId shr 32) + convertKeyIdToHex32bit(keyId) - } - - /** - * Converts [keyId] to an unsigned [Long] then uses [java.lang.Long.toHexString] to convert it - * to a lowercase hex ID. - */ - private fun convertKeyIdToHex32bit(keyId: Long): String { - var hexString = java.lang.Long.toHexString(keyId and 0xffffffffL).lowercase(Locale.ENGLISH) - while (hexString.length < 8) { - hexString = "0$hexString" - } - return hexString - } - } - public data class UserId(val email: String) : GpgIdentifier() { - override fun toString(): String { - return email - } - } - - public companion object { - public fun fromString(identifier: String): GpgIdentifier? { - if (identifier.isEmpty()) return null - // Match long key IDs: - // FF22334455667788 or 0xFF22334455667788 - val maybeLongKeyId = - identifier.removePrefix("0x").takeIf { it.matches("[a-fA-F\\d]{16}".toRegex()) } - if (maybeLongKeyId != null) { - val keyId = maybeLongKeyId.toULong(16) - return KeyId(keyId.toLong()) - } - - // Match fingerprints: - // FF223344556677889900112233445566778899 or 0xFF223344556677889900112233445566778899 - val maybeFingerprint = - identifier.removePrefix("0x").takeIf { it.matches("[a-fA-F\\d]{40}".toRegex()) } - if (maybeFingerprint != null) { - // Truncating to the long key ID is not a security issue since OpenKeychain only - // accepts - // non-ambiguous key IDs. - val keyId = maybeFingerprint.takeLast(16).toULong(16) - return KeyId(keyId.toLong()) - } - - return splitUserId(identifier)?.let { UserId(it) } - } - - private val USER_ID_PATTERN = Pattern.compile("^(.*?)(?: \\((.*)\\))?(?: <(.*)>)?$") - private val EMAIL_PATTERN = Pattern.compile("^\"]*@[^<>\"]*[.]?[^<>\"]*)\"?>?$") - - /** - * Takes a 'Name (Comment) ' user ID in any of its permutations and attempts to extract - * an email from it. - */ - private fun splitUserId(userId: String): String? { - if (userId.isNotEmpty()) { - val matcher = USER_ID_PATTERN.matcher(userId) - if (matcher.matches()) { - var name = if (matcher.group(1)?.isEmpty() == true) null else matcher.group(1) - var email = matcher.group(3) - if (email != null && name != null) { - val emailMatcher = EMAIL_PATTERN.matcher(name) - if (emailMatcher.matches() && email == emailMatcher.group(1)) { - email = emailMatcher.group(1) - name = null - } - } - if (email == null && name != null) { - val emailMatcher = EMAIL_PATTERN.matcher(name) - if (emailMatcher.matches()) { - email = emailMatcher.group(1) - } - } - return email - } - } - return null - } - } -} diff --git a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/KeyUtils.kt b/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/KeyUtils.kt deleted file mode 100644 index 1251463a..00000000 --- a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/KeyUtils.kt +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -import com.github.michaelbull.result.get -import com.github.michaelbull.result.runCatching -import dev.msfjarvis.aps.crypto.GpgIdentifier.KeyId -import org.bouncycastle.openpgp.PGPKeyRing -import org.pgpainless.PGPainless - -/** Utility methods to deal with [PGPKey]s. */ -public object KeyUtils { - /** - * Attempts to parse a [PGPKeyRing] from a given [key]. The key is first tried as a secret key and - * then as a public one before the method gives up and returns null. - */ - public fun tryParseKeyring(key: PGPKey): PGPKeyRing? { - val secKeyRing = runCatching { PGPainless.readKeyRing().secretKeyRing(key.contents) }.get() - if (secKeyRing != null) { - return secKeyRing - } - val pubKeyRing = runCatching { PGPainless.readKeyRing().publicKeyRing(key.contents) }.get() - if (pubKeyRing != null) { - return pubKeyRing - } - return null - } - - /** Parses a [PGPKeyRing] from the given [key] and calculates its long key ID */ - public fun tryGetId(key: PGPKey): KeyId? { - val keyRing = tryParseKeyring(key) ?: return null - return KeyId(keyRing.publicKey.keyID) - } -} diff --git a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKey.kt b/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKey.kt deleted file mode 100644 index 2e1311a1..00000000 --- a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKey.kt +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -/** - * A simple value class wrapping over a [ByteArray] that can represent a PGP key. The implementation - * details of public/ private parts as well as identities are deferred to [PGPKeyManager]. - */ -@JvmInline public value class PGPKey(public val contents: ByteArray) diff --git a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManager.kt b/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManager.kt deleted file mode 100644 index 137bd141..00000000 --- a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManager.kt +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ -@file:Suppress("BlockingMethodInNonBlockingContext") - -package dev.msfjarvis.aps.crypto - -import androidx.annotation.VisibleForTesting -import com.github.michaelbull.result.Result -import dev.msfjarvis.aps.crypto.KeyUtils.tryGetId -import dev.msfjarvis.aps.crypto.KeyUtils.tryParseKeyring -import dev.msfjarvis.aps.crypto.errors.InvalidKeyException -import dev.msfjarvis.aps.crypto.errors.KeyAlreadyExistsException -import dev.msfjarvis.aps.crypto.errors.KeyDeletionFailedException -import dev.msfjarvis.aps.crypto.errors.KeyDirectoryUnavailableException -import dev.msfjarvis.aps.crypto.errors.KeyNotFoundException -import dev.msfjarvis.aps.crypto.errors.NoKeysAvailableException -import dev.msfjarvis.aps.util.coroutines.runSuspendCatching -import java.io.File -import javax.inject.Inject -import kotlinx.coroutines.CoroutineDispatcher -import kotlinx.coroutines.withContext -import org.pgpainless.util.selection.userid.SelectUserId - -public class PGPKeyManager -@Inject -constructor( - filesDir: String, - private val dispatcher: CoroutineDispatcher, -) : KeyManager { - - private val keyDir = File(filesDir, KEY_DIR_NAME) - - override suspend fun addKey(key: PGPKey, replace: Boolean): Result = - withContext(dispatcher) { - runSuspendCatching { - if (!keyDirExists()) throw KeyDirectoryUnavailableException - if (tryParseKeyring(key) == null) throw InvalidKeyException - val keyFile = File(keyDir, "${tryGetId(key)}.$KEY_EXTENSION") - if (keyFile.exists()) { - // Check for replace flag first and if it is false, throw an error - if (!replace) - throw KeyAlreadyExistsException( - tryGetId(key)?.toString() ?: "Failed to retrieve key ID" - ) - if (!keyFile.delete()) throw KeyDeletionFailedException - } - - keyFile.writeBytes(key.contents) - - key - } - } - - override suspend fun removeKey(key: PGPKey): Result = - withContext(dispatcher) { - runSuspendCatching { - if (!keyDirExists()) throw KeyDirectoryUnavailableException - if (tryParseKeyring(key) == null) throw InvalidKeyException - val keyFile = File(keyDir, "${tryGetId(key)}.$KEY_EXTENSION") - if (keyFile.exists()) { - if (!keyFile.delete()) throw KeyDeletionFailedException - } - - key - } - } - - override suspend fun getKeyById(id: GpgIdentifier): Result = - withContext(dispatcher) { - runSuspendCatching { - if (!keyDirExists()) throw KeyDirectoryUnavailableException - val keyFiles = keyDir.listFiles() - if (keyFiles.isNullOrEmpty()) throw NoKeysAvailableException - val keys = keyFiles.map { file -> PGPKey(file.readBytes()) } - - val matchResult = - when (id) { - is GpgIdentifier.KeyId -> { - val keyIdMatch = - keys - .map { key -> key to tryGetId(key) } - .firstOrNull { (_, keyId) -> keyId?.id == id.id } - keyIdMatch?.first - } - is GpgIdentifier.UserId -> { - val selector = SelectUserId.byEmail(id.email) - val userIdMatch = - keys - .map { key -> key to tryParseKeyring(key) } - .firstOrNull { (_, keyRing) -> selector.firstMatch(keyRing) != null } - userIdMatch?.first - } - } - - if (matchResult != null) { - return@runSuspendCatching matchResult - } - - throw KeyNotFoundException("$id") - } - } - - override suspend fun getAllKeys(): Result, Throwable> = - withContext(dispatcher) { - runSuspendCatching { - if (!keyDirExists()) throw KeyDirectoryUnavailableException - val keyFiles = keyDir.listFiles() - if (keyFiles.isNullOrEmpty()) return@runSuspendCatching emptyList() - keyFiles.map { keyFile -> PGPKey(keyFile.readBytes()) }.toList() - } - } - - override suspend fun getKeyId(key: PGPKey): GpgIdentifier? = tryGetId(key) - - // TODO: This is a temp hack for now and in future it should check that the GPGKeyManager can - // decrypt the file. - override fun canHandle(fileName: String): Boolean { - return fileName.endsWith(KEY_EXTENSION) - } - - /** Checks if [keyDir] exists and attempts to create it if not. */ - private fun keyDirExists(): Boolean { - return keyDir.exists() || keyDir.mkdirs() - } - - public companion object { - - @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) - internal const val KEY_DIR_NAME: String = "keys" - @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) - internal const val KEY_EXTENSION: String = "key" - } -} diff --git a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandler.kt b/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandler.kt deleted file mode 100644 index 24b3e665..00000000 --- a/crypto-pgpainless/src/main/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandler.kt +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -import com.github.michaelbull.result.Result -import com.github.michaelbull.result.mapError -import com.github.michaelbull.result.runCatching -import dev.msfjarvis.aps.crypto.errors.CryptoHandlerException -import dev.msfjarvis.aps.crypto.errors.IncorrectPassphraseException -import dev.msfjarvis.aps.crypto.errors.NoKeysProvided -import dev.msfjarvis.aps.crypto.errors.UnknownError -import java.io.ByteArrayInputStream -import java.io.InputStream -import java.io.OutputStream -import javax.inject.Inject -import org.bouncycastle.openpgp.PGPPublicKeyRing -import org.bouncycastle.openpgp.PGPPublicKeyRingCollection -import org.bouncycastle.openpgp.PGPSecretKeyRingCollection -import org.pgpainless.PGPainless -import org.pgpainless.decryption_verification.ConsumerOptions -import org.pgpainless.encryption_signing.EncryptionOptions -import org.pgpainless.encryption_signing.ProducerOptions -import org.pgpainless.exception.WrongPassphraseException -import org.pgpainless.key.protection.PasswordBasedSecretKeyRingProtector -import org.pgpainless.util.Passphrase - -public class PGPainlessCryptoHandler @Inject constructor() : CryptoHandler { - - public override fun decrypt( - privateKey: PGPKey, - passphrase: String, - ciphertextStream: InputStream, - outputStream: OutputStream, - ): Result = - runCatching { - val pgpSecretKeyRing = PGPainless.readKeyRing().secretKeyRing(privateKey.contents) - val keyringCollection = PGPSecretKeyRingCollection(listOf(pgpSecretKeyRing)) - val protector = - PasswordBasedSecretKeyRingProtector.forKey( - pgpSecretKeyRing, - Passphrase.fromPassword(passphrase) - ) - PGPainless.decryptAndOrVerify() - .onInputStream(ciphertextStream) - .withOptions( - ConsumerOptions() - .addDecryptionKeys(keyringCollection, protector) - .addDecryptionPassphrase(Passphrase.fromPassword(passphrase)) - ) - .use { decryptionStream -> decryptionStream.copyTo(outputStream) } - return@runCatching - } - .mapError { error -> - when (error) { - is WrongPassphraseException -> IncorrectPassphraseException(error) - else -> UnknownError(error) - } - } - - public override fun encrypt( - keys: List, - plaintextStream: InputStream, - outputStream: OutputStream, - ): Result = - runCatching { - if (keys.isEmpty()) throw NoKeysProvided("No keys provided for encryption") - val publicKeyRings = arrayListOf() - val armoredKeys = - keys.joinToString("\n") { key -> key.contents.decodeToString() }.toByteArray() - val secKeysStream = ByteArrayInputStream(armoredKeys) - val secretKeyRingCollection = - PGPainless.readKeyRing().secretKeyRingCollection(secKeysStream) - secretKeyRingCollection.forEach { secretKeyRing -> - publicKeyRings.add(PGPainless.extractCertificate(secretKeyRing)) - } - if (publicKeyRings.isEmpty()) { - val pubKeysStream = ByteArrayInputStream(armoredKeys) - val publicKeyRingCollection = - PGPainless.readKeyRing().publicKeyRingCollection(pubKeysStream) - publicKeyRings.addAll(publicKeyRingCollection) - } - require(publicKeyRings.isNotEmpty()) { "No public keys to encrypt message to" } - val publicKeyRingCollection = PGPPublicKeyRingCollection(publicKeyRings) - val encryptionOptions = EncryptionOptions().addRecipients(publicKeyRingCollection) - val producerOptions = ProducerOptions.encrypt(encryptionOptions).setAsciiArmor(false) - val encryptor = - PGPainless.encryptAndOrSign().onOutputStream(outputStream).withOptions(producerOptions) - plaintextStream.copyTo(encryptor) - encryptor.close() - val result = encryptor.result - publicKeyRingCollection.keyRings.forEach { keyRing -> - require(result.isEncryptedFor(keyRing)) { - "Stream should be encrypted for ${keyRing.publicKey.keyID} but wasn't" - } - } - } - .mapError { error -> - when (error) { - is CryptoHandlerException -> error - else -> UnknownError(error) - } - } - - public override fun canHandle(fileName: String): Boolean { - return fileName.split('.').lastOrNull() == "gpg" - } -} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/CryptoConstants.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/CryptoConstants.kt new file mode 100644 index 00000000..d827e169 --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/CryptoConstants.kt @@ -0,0 +1,14 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +object CryptoConstants { + const val KEY_PASSPHRASE = "hunter2" + const val PLAIN_TEXT = "encryption worthy content" + const val KEY_NAME = "John Doe" + const val KEY_EMAIL = "john.doe@example.com" + const val KEY_ID = 0x08edf7567183ce27 +} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/GpgIdentifierTest.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/GpgIdentifierTest.kt new file mode 100644 index 00000000..009976a2 --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/GpgIdentifierTest.kt @@ -0,0 +1,41 @@ +/* + * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +class GpgIdentifierTest { + + @Test + fun parseHexKeyIdWithout0xPrefix() { + val identifier = GpgIdentifier.fromString("79E8208280490C77") + assertNotNull(identifier) + assertTrue { identifier is GpgIdentifier.KeyId } + } + + @Test + fun parseHexKeyId() { + val identifier = GpgIdentifier.fromString("0x79E8208280490C77") + assertNotNull(identifier) + assertTrue { identifier is GpgIdentifier.KeyId } + } + + @Test + fun parseValidEmail() { + val identifier = GpgIdentifier.fromString("john.doe@example.org") + assertNotNull(identifier) + assertTrue { identifier is GpgIdentifier.UserId } + } + + @Test + fun parseEmailWithoutTLD() { + val identifier = GpgIdentifier.fromString("john.doe@example") + assertNotNull(identifier) + assertTrue { identifier is GpgIdentifier.UserId } + } +} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/KeyUtilsTest.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/KeyUtilsTest.kt new file mode 100644 index 00000000..209865ea --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/KeyUtilsTest.kt @@ -0,0 +1,24 @@ +package app.passwordstore.crypto + +import app.passwordstore.crypto.KeyUtils.tryGetId +import app.passwordstore.crypto.KeyUtils.tryParseKeyring +import app.passwordstore.crypto.TestUtils.getArmoredPrivateKeyWithMultipleIdentities +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import org.bouncycastle.openpgp.PGPSecretKeyRing + +class KeyUtilsTest { + @Test + fun parseKeyWithMultipleIdentities() { + val key = PGPKey(getArmoredPrivateKeyWithMultipleIdentities()) + val keyring = tryParseKeyring(key) + assertNotNull(keyring) + assertIs(keyring) + val keyId = tryGetId(key) + assertNotNull(keyId) + assertIs(keyId) + assertEquals("b950ae2813841585", keyId.toString()) + } +} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPKeyManagerTest.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPKeyManagerTest.kt new file mode 100644 index 00000000..c446cee4 --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPKeyManagerTest.kt @@ -0,0 +1,189 @@ +package app.passwordstore.crypto + +import app.passwordstore.crypto.GpgIdentifier.KeyId +import app.passwordstore.crypto.GpgIdentifier.UserId +import app.passwordstore.crypto.TestUtils.getArmoredPrivateKeyWithMultipleIdentities +import app.passwordstore.crypto.errors.KeyAlreadyExistsException +import app.passwordstore.crypto.errors.KeyNotFoundException +import app.passwordstore.crypto.errors.NoKeysAvailableException +import com.github.michaelbull.result.unwrap +import com.github.michaelbull.result.unwrapError +import java.io.File +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.Rule +import org.junit.rules.TemporaryFolder + +@OptIn(ExperimentalCoroutinesApi::class) +class PGPKeyManagerTest { + + @get:Rule val temporaryFolder: TemporaryFolder = TemporaryFolder() + private val filesDir by unsafeLazy { temporaryFolder.root } + private val keysDir by unsafeLazy { File(filesDir, PGPKeyManager.KEY_DIR_NAME) } + private val dispatcher = StandardTestDispatcher() + private val scope = TestScope(dispatcher) + private val keyManager by unsafeLazy { PGPKeyManager(filesDir.absolutePath, dispatcher) } + private val key = PGPKey(TestUtils.getArmoredPrivateKey()) + + private fun unsafeLazy(initializer: () -> T) = + lazy(LazyThreadSafetyMode.NONE) { initializer.invoke() } + + @BeforeTest + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterTest + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun addKey() = + scope.runTest { + // Check if the key id returned is correct + val keyId = keyManager.getKeyId(keyManager.addKey(key).unwrap()) + assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) + + // Check if the keys directory have one file + assertEquals(1, filesDir.list()?.size) + + // Check if the file name is correct + val keyFile = keysDir.listFiles()?.first() + assertEquals(keyFile?.name, "$keyId.${PGPKeyManager.KEY_EXTENSION}") + } + + @Test + fun addKeyWithoutReplaceFlag() = + scope.runTest { + // Check adding the keys twice + keyManager.addKey(key, false).unwrap() + val error = keyManager.addKey(key, false).unwrapError() + + assertIs(error) + } + + @Test + fun addKeyWithReplaceFlag() = + scope.runTest { + // Check adding the keys twice + keyManager.addKey(key, true).unwrap() + val keyId = keyManager.getKeyId(keyManager.addKey(key, true).unwrap()) + + assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) + } + + @Test + fun removeKey() = + scope.runTest { + // Add key using KeyManager + keyManager.addKey(key).unwrap() + + // Check if the key id returned is correct + val keyId = keyManager.getKeyId(keyManager.removeKey(key).unwrap()) + assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) + + // Check if the keys directory have 0 files + val keysDir = File(filesDir, PGPKeyManager.KEY_DIR_NAME) + assertEquals(0, keysDir.list()?.size) + } + + @Test + fun getKeyById() = + scope.runTest { + // Add key using KeyManager + keyManager.addKey(key).unwrap() + + val keyId = keyManager.getKeyId(key) + assertNotNull(keyId) + assertEquals(KeyId(CryptoConstants.KEY_ID), keyManager.getKeyId(key)) + + // Check returned key id matches the expected id and the created key id + val returnedKey = keyManager.getKeyById(keyId).unwrap() + assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) + } + + @Test + fun getKeyByFullUserId() = + scope.runTest { + keyManager.addKey(key).unwrap() + + val keyId = "${CryptoConstants.KEY_NAME} <${CryptoConstants.KEY_EMAIL}>" + val returnedKey = keyManager.getKeyById(UserId(keyId)).unwrap() + assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) + } + + @Test + fun getKeyByEmailUserId() = + scope.runTest { + keyManager.addKey(key).unwrap() + + val keyId = CryptoConstants.KEY_EMAIL + val returnedKey = keyManager.getKeyById(UserId(keyId)).unwrap() + assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) + } + + @Test + fun getNonExistentKey() = + scope.runTest { + // Add key using KeyManager + keyManager.addKey(key).unwrap() + + val keyId = KeyId(0x08edf7567183ce44) + + // Check returned key + val error = keyManager.getKeyById(keyId).unwrapError() + assertIs(error) + assertEquals("No key found with id: $keyId", error.message) + } + + @Test + fun findNonExistentKey() = + scope.runTest { + // Check returned key + val error = keyManager.getKeyById(KeyId(0x08edf7567183ce44)).unwrapError() + assertIs(error) + assertEquals("No keys were found", error.message) + } + + @Test + fun getAllKeys() = + scope.runTest { + // Check if KeyManager returns no key + val noKeyList = keyManager.getAllKeys().unwrap() + assertEquals(0, noKeyList.size) + + // Add key using KeyManager + keyManager.addKey(key).unwrap() + keyManager.addKey(PGPKey(getArmoredPrivateKeyWithMultipleIdentities())).unwrap() + + // Check if KeyManager returns one key + val singleKeyList = keyManager.getAllKeys().unwrap() + assertEquals(2, singleKeyList.size) + } + + @Test + fun getMultipleIdentityKeyWithAllIdentities() { + scope.runTest { + val key = PGPKey(getArmoredPrivateKeyWithMultipleIdentities()) + keyManager.addKey(key).unwrap() + + val johnKey = keyManager.getKeyById(UserId("john@doe.org")).unwrap() + val janeKey = keyManager.getKeyById(UserId("jane@doe.org")).unwrap() + + assertContentEquals(johnKey.contents, janeKey.contents) + } + } +} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandlerTest.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandlerTest.kt new file mode 100644 index 00000000..60e8fb6e --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/PGPainlessCryptoHandlerTest.kt @@ -0,0 +1,78 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ + +package app.passwordstore.crypto + +import app.passwordstore.crypto.errors.IncorrectPassphraseException +import com.github.michaelbull.result.Err +import com.github.michaelbull.result.getError +import com.google.testing.junit.testparameterinjector.TestParameter +import com.google.testing.junit.testparameterinjector.TestParameterInjector +import java.io.ByteArrayOutputStream +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue +import org.junit.runner.RunWith + +@Suppress("Unused") // Test runner handles it internally +enum class EncryptionKey(val key: PGPKey) { + PUBLIC(PGPKey(TestUtils.getArmoredPublicKey())), + SECRET(PGPKey(TestUtils.getArmoredPrivateKey())), +} + +@RunWith(TestParameterInjector::class) +class PGPainlessCryptoHandlerTest { + + @TestParameter private lateinit var encryptionKey: EncryptionKey + private val cryptoHandler = PGPainlessCryptoHandler() + private val privateKey = PGPKey(TestUtils.getArmoredPrivateKey()) + + @Test + fun encryptAndDecrypt() { + val ciphertextStream = ByteArrayOutputStream() + cryptoHandler.encrypt( + listOf(encryptionKey.key), + CryptoConstants.PLAIN_TEXT.byteInputStream(Charsets.UTF_8), + ciphertextStream, + ) + val plaintextStream = ByteArrayOutputStream() + cryptoHandler.decrypt( + privateKey, + CryptoConstants.KEY_PASSPHRASE, + ciphertextStream.toByteArray().inputStream(), + plaintextStream, + ) + assertEquals(CryptoConstants.PLAIN_TEXT, plaintextStream.toString(Charsets.UTF_8)) + } + + @Test + fun decryptWithWrongPassphrase() { + val ciphertextStream = ByteArrayOutputStream() + cryptoHandler.encrypt( + listOf(encryptionKey.key), + CryptoConstants.PLAIN_TEXT.byteInputStream(Charsets.UTF_8), + ciphertextStream, + ) + val plaintextStream = ByteArrayOutputStream() + val result = + cryptoHandler.decrypt( + privateKey, + "very incorrect passphrase", + ciphertextStream.toByteArray().inputStream(), + plaintextStream, + ) + assertIs>(result) + assertIs(result.getError()) + } + + @Test + fun canHandleFiltersFormats() { + assertFalse { cryptoHandler.canHandle("example.com") } + assertTrue { cryptoHandler.canHandle("example.com.gpg") } + assertFalse { cryptoHandler.canHandle("example.com.asc") } + } +} diff --git a/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/TestUtils.kt b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/TestUtils.kt new file mode 100644 index 00000000..1e5aea8c --- /dev/null +++ b/crypto-pgpainless/src/test/kotlin/app/passwordstore/crypto/TestUtils.kt @@ -0,0 +1,16 @@ +/* + * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. + * SPDX-License-Identifier: GPL-3.0-only + */ +@file:Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") + +package app.passwordstore.crypto + +object TestUtils { + fun getArmoredPrivateKey() = this::class.java.classLoader.getResource("private_key").readBytes() + fun getArmoredPublicKey() = this::class.java.classLoader.getResource("public_key").readBytes() + fun getArmoredPrivateKeyWithMultipleIdentities() = + this::class.java.classLoader.getResource("private_key_multiple_identities").readBytes() + fun getArmoredPublicKeyWithMultipleIdentities() = + this::class.java.classLoader.getResource("public_key_multiple_identities").readBytes() +} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/CryptoConstants.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/CryptoConstants.kt deleted file mode 100644 index ede8f08d..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/CryptoConstants.kt +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -object CryptoConstants { - const val KEY_PASSPHRASE = "hunter2" - const val PLAIN_TEXT = "encryption worthy content" - const val KEY_NAME = "John Doe" - const val KEY_EMAIL = "john.doe@example.com" - const val KEY_ID = 0x08edf7567183ce27 -} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifierTest.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifierTest.kt deleted file mode 100644 index aaf20cd8..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/GpgIdentifierTest.kt +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright © 2014-2022 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -import kotlin.test.Test -import kotlin.test.assertNotNull -import kotlin.test.assertTrue - -class GpgIdentifierTest { - - @Test - fun parseHexKeyIdWithout0xPrefix() { - val identifier = GpgIdentifier.fromString("79E8208280490C77") - assertNotNull(identifier) - assertTrue { identifier is GpgIdentifier.KeyId } - } - - @Test - fun parseHexKeyId() { - val identifier = GpgIdentifier.fromString("0x79E8208280490C77") - assertNotNull(identifier) - assertTrue { identifier is GpgIdentifier.KeyId } - } - - @Test - fun parseValidEmail() { - val identifier = GpgIdentifier.fromString("john.doe@example.org") - assertNotNull(identifier) - assertTrue { identifier is GpgIdentifier.UserId } - } - - @Test - fun parseEmailWithoutTLD() { - val identifier = GpgIdentifier.fromString("john.doe@example") - assertNotNull(identifier) - assertTrue { identifier is GpgIdentifier.UserId } - } -} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/KeyUtilsTest.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/KeyUtilsTest.kt deleted file mode 100644 index 33597f9f..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/KeyUtilsTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package dev.msfjarvis.aps.crypto - -import dev.msfjarvis.aps.crypto.KeyUtils.tryGetId -import dev.msfjarvis.aps.crypto.KeyUtils.tryParseKeyring -import dev.msfjarvis.aps.crypto.TestUtils.getArmoredPrivateKeyWithMultipleIdentities -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import org.bouncycastle.openpgp.PGPSecretKeyRing - -class KeyUtilsTest { - @Test - fun parseKeyWithMultipleIdentities() { - val key = PGPKey(getArmoredPrivateKeyWithMultipleIdentities()) - val keyring = tryParseKeyring(key) - assertNotNull(keyring) - assertIs(keyring) - val keyId = tryGetId(key) - assertNotNull(keyId) - assertIs(keyId) - assertEquals("b950ae2813841585", keyId.toString()) - } -} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManagerTest.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManagerTest.kt deleted file mode 100644 index 60436d3b..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPKeyManagerTest.kt +++ /dev/null @@ -1,189 +0,0 @@ -package dev.msfjarvis.aps.crypto - -import com.github.michaelbull.result.unwrap -import com.github.michaelbull.result.unwrapError -import dev.msfjarvis.aps.crypto.GpgIdentifier.KeyId -import dev.msfjarvis.aps.crypto.GpgIdentifier.UserId -import dev.msfjarvis.aps.crypto.TestUtils.getArmoredPrivateKeyWithMultipleIdentities -import dev.msfjarvis.aps.crypto.errors.KeyAlreadyExistsException -import dev.msfjarvis.aps.crypto.errors.KeyNotFoundException -import dev.msfjarvis.aps.crypto.errors.NoKeysAvailableException -import java.io.File -import kotlin.test.AfterTest -import kotlin.test.BeforeTest -import kotlin.test.Test -import kotlin.test.assertContentEquals -import kotlin.test.assertEquals -import kotlin.test.assertIs -import kotlin.test.assertNotNull -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.ExperimentalCoroutinesApi -import kotlinx.coroutines.test.StandardTestDispatcher -import kotlinx.coroutines.test.TestScope -import kotlinx.coroutines.test.resetMain -import kotlinx.coroutines.test.runTest -import kotlinx.coroutines.test.setMain -import org.junit.Rule -import org.junit.rules.TemporaryFolder - -@OptIn(ExperimentalCoroutinesApi::class) -class PGPKeyManagerTest { - - @get:Rule val temporaryFolder: TemporaryFolder = TemporaryFolder() - private val filesDir by unsafeLazy { temporaryFolder.root } - private val keysDir by unsafeLazy { File(filesDir, PGPKeyManager.KEY_DIR_NAME) } - private val dispatcher = StandardTestDispatcher() - private val scope = TestScope(dispatcher) - private val keyManager by unsafeLazy { PGPKeyManager(filesDir.absolutePath, dispatcher) } - private val key = PGPKey(TestUtils.getArmoredPrivateKey()) - - private fun unsafeLazy(initializer: () -> T) = - lazy(LazyThreadSafetyMode.NONE) { initializer.invoke() } - - @BeforeTest - fun setUp() { - Dispatchers.setMain(dispatcher) - } - - @AfterTest - fun tearDown() { - Dispatchers.resetMain() - } - - @Test - fun addKey() = - scope.runTest { - // Check if the key id returned is correct - val keyId = keyManager.getKeyId(keyManager.addKey(key).unwrap()) - assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) - - // Check if the keys directory have one file - assertEquals(1, filesDir.list()?.size) - - // Check if the file name is correct - val keyFile = keysDir.listFiles()?.first() - assertEquals(keyFile?.name, "$keyId.${PGPKeyManager.KEY_EXTENSION}") - } - - @Test - fun addKeyWithoutReplaceFlag() = - scope.runTest { - // Check adding the keys twice - keyManager.addKey(key, false).unwrap() - val error = keyManager.addKey(key, false).unwrapError() - - assertIs(error) - } - - @Test - fun addKeyWithReplaceFlag() = - scope.runTest { - // Check adding the keys twice - keyManager.addKey(key, true).unwrap() - val keyId = keyManager.getKeyId(keyManager.addKey(key, true).unwrap()) - - assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) - } - - @Test - fun removeKey() = - scope.runTest { - // Add key using KeyManager - keyManager.addKey(key).unwrap() - - // Check if the key id returned is correct - val keyId = keyManager.getKeyId(keyManager.removeKey(key).unwrap()) - assertEquals(KeyId(CryptoConstants.KEY_ID), keyId) - - // Check if the keys directory have 0 files - val keysDir = File(filesDir, PGPKeyManager.KEY_DIR_NAME) - assertEquals(0, keysDir.list()?.size) - } - - @Test - fun getKeyById() = - scope.runTest { - // Add key using KeyManager - keyManager.addKey(key).unwrap() - - val keyId = keyManager.getKeyId(key) - assertNotNull(keyId) - assertEquals(KeyId(CryptoConstants.KEY_ID), keyManager.getKeyId(key)) - - // Check returned key id matches the expected id and the created key id - val returnedKey = keyManager.getKeyById(keyId).unwrap() - assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) - } - - @Test - fun getKeyByFullUserId() = - scope.runTest { - keyManager.addKey(key).unwrap() - - val keyId = "${CryptoConstants.KEY_NAME} <${CryptoConstants.KEY_EMAIL}>" - val returnedKey = keyManager.getKeyById(UserId(keyId)).unwrap() - assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) - } - - @Test - fun getKeyByEmailUserId() = - scope.runTest { - keyManager.addKey(key).unwrap() - - val keyId = CryptoConstants.KEY_EMAIL - val returnedKey = keyManager.getKeyById(UserId(keyId)).unwrap() - assertEquals(keyManager.getKeyId(key), keyManager.getKeyId(returnedKey)) - } - - @Test - fun getNonExistentKey() = - scope.runTest { - // Add key using KeyManager - keyManager.addKey(key).unwrap() - - val keyId = KeyId(0x08edf7567183ce44) - - // Check returned key - val error = keyManager.getKeyById(keyId).unwrapError() - assertIs(error) - assertEquals("No key found with id: $keyId", error.message) - } - - @Test - fun findNonExistentKey() = - scope.runTest { - // Check returned key - val error = keyManager.getKeyById(KeyId(0x08edf7567183ce44)).unwrapError() - assertIs(error) - assertEquals("No keys were found", error.message) - } - - @Test - fun getAllKeys() = - scope.runTest { - // Check if KeyManager returns no key - val noKeyList = keyManager.getAllKeys().unwrap() - assertEquals(0, noKeyList.size) - - // Add key using KeyManager - keyManager.addKey(key).unwrap() - keyManager.addKey(PGPKey(getArmoredPrivateKeyWithMultipleIdentities())).unwrap() - - // Check if KeyManager returns one key - val singleKeyList = keyManager.getAllKeys().unwrap() - assertEquals(2, singleKeyList.size) - } - - @Test - fun getMultipleIdentityKeyWithAllIdentities() { - scope.runTest { - val key = PGPKey(getArmoredPrivateKeyWithMultipleIdentities()) - keyManager.addKey(key).unwrap() - - val johnKey = keyManager.getKeyById(UserId("john@doe.org")).unwrap() - val janeKey = keyManager.getKeyById(UserId("jane@doe.org")).unwrap() - - assertContentEquals(johnKey.contents, janeKey.contents) - } - } -} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandlerTest.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandlerTest.kt deleted file mode 100644 index e39bc06e..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/PGPainlessCryptoHandlerTest.kt +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ - -package dev.msfjarvis.aps.crypto - -import com.github.michaelbull.result.Err -import com.github.michaelbull.result.getError -import com.google.testing.junit.testparameterinjector.TestParameter -import com.google.testing.junit.testparameterinjector.TestParameterInjector -import dev.msfjarvis.aps.crypto.errors.IncorrectPassphraseException -import java.io.ByteArrayOutputStream -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFalse -import kotlin.test.assertIs -import kotlin.test.assertTrue -import org.junit.runner.RunWith - -@Suppress("Unused") // Test runner handles it internally -enum class EncryptionKey(val key: PGPKey) { - PUBLIC(PGPKey(TestUtils.getArmoredPublicKey())), - SECRET(PGPKey(TestUtils.getArmoredPrivateKey())), -} - -@RunWith(TestParameterInjector::class) -class PGPainlessCryptoHandlerTest { - - @TestParameter private lateinit var encryptionKey: EncryptionKey - private val cryptoHandler = PGPainlessCryptoHandler() - private val privateKey = PGPKey(TestUtils.getArmoredPrivateKey()) - - @Test - fun encryptAndDecrypt() { - val ciphertextStream = ByteArrayOutputStream() - cryptoHandler.encrypt( - listOf(encryptionKey.key), - CryptoConstants.PLAIN_TEXT.byteInputStream(Charsets.UTF_8), - ciphertextStream, - ) - val plaintextStream = ByteArrayOutputStream() - cryptoHandler.decrypt( - privateKey, - CryptoConstants.KEY_PASSPHRASE, - ciphertextStream.toByteArray().inputStream(), - plaintextStream, - ) - assertEquals(CryptoConstants.PLAIN_TEXT, plaintextStream.toString(Charsets.UTF_8)) - } - - @Test - fun decryptWithWrongPassphrase() { - val ciphertextStream = ByteArrayOutputStream() - cryptoHandler.encrypt( - listOf(encryptionKey.key), - CryptoConstants.PLAIN_TEXT.byteInputStream(Charsets.UTF_8), - ciphertextStream, - ) - val plaintextStream = ByteArrayOutputStream() - val result = - cryptoHandler.decrypt( - privateKey, - "very incorrect passphrase", - ciphertextStream.toByteArray().inputStream(), - plaintextStream, - ) - assertIs>(result) - assertIs(result.getError()) - } - - @Test - fun canHandleFiltersFormats() { - assertFalse { cryptoHandler.canHandle("example.com") } - assertTrue { cryptoHandler.canHandle("example.com.gpg") } - assertFalse { cryptoHandler.canHandle("example.com.asc") } - } -} diff --git a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/TestUtils.kt b/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/TestUtils.kt deleted file mode 100644 index d002180d..00000000 --- a/crypto-pgpainless/src/test/kotlin/dev/msfjarvis/aps/crypto/TestUtils.kt +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright © 2014-2021 The Android Password Store Authors. All Rights Reserved. - * SPDX-License-Identifier: GPL-3.0-only - */ -@file:Suppress("RECEIVER_NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS") - -package dev.msfjarvis.aps.crypto - -object TestUtils { - fun getArmoredPrivateKey() = this::class.java.classLoader.getResource("private_key").readBytes() - fun getArmoredPublicKey() = this::class.java.classLoader.getResource("public_key").readBytes() - fun getArmoredPrivateKeyWithMultipleIdentities() = - this::class.java.classLoader.getResource("private_key_multiple_identities").readBytes() - fun getArmoredPublicKeyWithMultipleIdentities() = - this::class.java.classLoader.getResource("public_key_multiple_identities").readBytes() -} -- cgit v1.2.3