package eu.friedcutlet.yokan.services.backup import dev.whyoleg.cryptography.CryptographyProvider import dev.whyoleg.cryptography.CryptographyProviderApi import dev.whyoleg.cryptography.DelicateCryptographyApi import dev.whyoleg.cryptography.algorithms.AES import dev.whyoleg.cryptography.algorithms.PBKDF2 import dev.whyoleg.cryptography.algorithms.SHA256 import dev.whyoleg.cryptography.random.CryptographyRandom import eu.friedcutlet.yokan.services.catchingNonCancellation import kotlinx.coroutines.ensureActive import kotlin.coroutines.coroutineContext internal sealed interface PasswordBackupEnvelopeResult { data class Success(val bytes: ByteArray) : PasswordBackupEnvelopeResult data class Failure(val error: PasswordBackupEnvelopeError) : PasswordBackupEnvelopeResult } internal sealed interface PasswordBackupEnvelopeError { data object InvalidInput : PasswordBackupEnvelopeError data object Malformed : PasswordBackupEnvelopeError data object Unsupported : PasswordBackupEnvelopeError data object AuthenticationFailed : PasswordBackupEnvelopeError data object CryptoFailure : PasswordBackupEnvelopeError } // Passwords are encoded as exact UTF-8 bytes and capped before KDF work. internal const val MAX_BACKUP_PASSWORD_BYTES = 1024 /** Whether [password] is accepted by [PasswordBackupEnvelope]: 1 to [MAX_BACKUP_PASSWORD_BYTES] UTF-8 bytes. */ internal fun isValidBackupPassword(password: String): Boolean = password.encodeToByteArray().size in 1..MAX_BACKUP_PASSWORD_BYTES @OptIn(CryptographyProviderApi::class, DelicateCryptographyApi::class) internal object PasswordBackupEnvelope { private const val VERSION = 1 private const val KDF_PBKDF2_SHA256 = 1 private const val AEAD_AES_256_GCM = 1 private const val PAYLOAD_RAW_YOKAN_JSON = 1 private const val ITERATIONS = 600_000 private const val MAX_ITERATIONS = 2_000_000 private const val KEY_SIZE_BYTES = 32 private const val SALT_SIZE = 16 private const val NONCE_SIZE = 12 private const val TAG_SIZE = 16 private const val HEADER_SIZE = 8 + 1 + 1 + 1 + 1 + 4 + SALT_SIZE + NONCE_SIZE private const val MAX_PAYLOAD_SIZE = 64 * 1024 * 1024 private const val MAX_ENVELOPE_SIZE = HEADER_SIZE + MAX_PAYLOAD_SIZE + TAG_SIZE private val MAGIC = "YOKANENC".encodeToByteArray() private val provider = CryptographyProvider.Default suspend fun encode(payload: ByteArray, password: String): PasswordBackupEnvelopeResult = encodeWithEntropy(payload, password) { size -> CryptographyRandom.Default.nextBytes(size) } suspend fun decode(envelope: ByteArray, password: String): PasswordBackupEnvelopeResult { coroutineContext.ensureActive() val passwordBytes = passwordBytes(password) ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput) if (envelope.size < HEADER_SIZE + TAG_SIZE || envelope.size > MAX_ENVELOPE_SIZE) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed) } val header = envelope.copyOfRange(0, HEADER_SIZE) if (!header.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed) } if (header[8].unsigned() != VERSION || header[9].unsigned() != KDF_PBKDF2_SHA256 || header[10].unsigned() != AEAD_AES_256_GCM || header[11].unsigned() != PAYLOAD_RAW_YOKAN_JSON ) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Unsupported) } val iterations = readInt(header, 12) if (iterations !in ITERATIONS..MAX_ITERATIONS) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed) } val ciphertext = envelope.copyOfRange(HEADER_SIZE, envelope.size) if (ciphertext.size < TAG_SIZE || ciphertext.size - TAG_SIZE > MAX_PAYLOAD_SIZE) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed) } val key = catchingNonCancellation { deriveKey(passwordBytes, header.copyOfRange(16, 16 + SALT_SIZE), iterations) }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) } val aesKey = catchingNonCancellation { provider.get(AES.GCM).keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key) }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) } val cipher = catchingNonCancellation { aesKey.cipher(AES.Key.Size.B128) } .getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) } val plaintext = catchingNonCancellation { cipher.decryptWithIv( header.copyOfRange(16 + SALT_SIZE, HEADER_SIZE), ciphertext, header, ) }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.AuthenticationFailed) } return if (plaintext.size > MAX_PAYLOAD_SIZE) { PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed) } else { PasswordBackupEnvelopeResult.Success(plaintext) } } internal suspend fun encodeForTesting( payload: ByteArray, password: String, salt: ByteArray, nonce: ByteArray, ): PasswordBackupEnvelopeResult { coroutineContext.ensureActive() if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput) } return encodeWithEntropy(payload, password) { size -> when (size) { SALT_SIZE -> salt.copyOf() NONCE_SIZE -> nonce.copyOf() else -> error("Unexpected envelope entropy request") } } } private suspend fun encodeWithEntropy( payload: ByteArray, password: String, entropy: (Int) -> ByteArray, ): PasswordBackupEnvelopeResult { coroutineContext.ensureActive() val passwordBytes = passwordBytes(password) ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput) if (payload.size > MAX_PAYLOAD_SIZE) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput) } return catchingNonCancellation { val salt = entropy(SALT_SIZE) val nonce = entropy(NONCE_SIZE) if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) } val header = ByteArray(HEADER_SIZE).also { MAGIC.copyInto(it) it[8] = VERSION.toByte() it[9] = KDF_PBKDF2_SHA256.toByte() it[10] = AEAD_AES_256_GCM.toByte() it[11] = PAYLOAD_RAW_YOKAN_JSON.toByte() writeInt(it, 12, ITERATIONS) salt.copyInto(it, 16) nonce.copyInto(it, 16 + SALT_SIZE) } val key = deriveKey(passwordBytes, salt, ITERATIONS) val aes = provider.get(AES.GCM) val aesKey = aes.keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key) val ciphertext = aesKey.cipher(AES.Key.Size.B128).encryptWithIv(nonce, payload, header) PasswordBackupEnvelopeResult.Success(header + ciphertext) }.getOrElse { PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) } } private suspend fun deriveKey(password: ByteArray, salt: ByteArray, iterations: Int): ByteArray { val pbkdf2 = provider.get(PBKDF2) return pbkdf2.secretDerivation(SHA256, iterations, AES.Key.Size.B256, salt) .deriveSecretToByteArray(password) } private fun passwordBytes(password: String): ByteArray? = password.takeIf(::isValidBackupPassword)?.encodeToByteArray() private fun readInt(bytes: ByteArray, offset: Int): Int = (bytes[offset].unsigned() shl 24) or (bytes[offset + 1].unsigned() shl 16) or (bytes[offset + 2].unsigned() shl 8) or bytes[offset + 3].unsigned() private fun writeInt(bytes: ByteArray, offset: Int, value: Int) { bytes[offset] = (value ushr 24).toByte() bytes[offset + 1] = (value ushr 16).toByte() bytes[offset + 2] = (value ushr 8).toByte() bytes[offset + 3] = value.toByte() } private fun Byte.unsigned(): Int = toInt() and 0xff }