PasswordBackupEnvelope.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/backup/PasswordBackupEnvelope.kt
1package eu.friedcutlet.yokan.services.backup23import dev.whyoleg.cryptography.CryptographyProvider4import dev.whyoleg.cryptography.CryptographyProviderApi5import dev.whyoleg.cryptography.DelicateCryptographyApi6import dev.whyoleg.cryptography.algorithms.AES7import dev.whyoleg.cryptography.algorithms.PBKDF28import dev.whyoleg.cryptography.algorithms.SHA2569import dev.whyoleg.cryptography.random.CryptographyRandom10import eu.friedcutlet.yokan.services.catchingNonCancellation11import kotlinx.coroutines.ensureActive12import kotlin.coroutines.coroutineContext1314internal sealed interface PasswordBackupEnvelopeResult {15 data class Success(val bytes: ByteArray) : PasswordBackupEnvelopeResult16 data class Failure(val error: PasswordBackupEnvelopeError) : PasswordBackupEnvelopeResult17}1819internal sealed interface PasswordBackupEnvelopeError {20 data object InvalidInput : PasswordBackupEnvelopeError21 data object Malformed : PasswordBackupEnvelopeError22 data object Unsupported : PasswordBackupEnvelopeError23 data object AuthenticationFailed : PasswordBackupEnvelopeError24 data object CryptoFailure : PasswordBackupEnvelopeError25}2627// Passwords are encoded as exact UTF-8 bytes and capped before KDF work.28internal const val MAX_BACKUP_PASSWORD_BYTES = 10242930/** Whether [password] is accepted by [PasswordBackupEnvelope]: 1 to [MAX_BACKUP_PASSWORD_BYTES] UTF-8 bytes. */31internal fun isValidBackupPassword(password: String): Boolean =32 password.encodeToByteArray().size in 1..MAX_BACKUP_PASSWORD_BYTES3334@OptIn(CryptographyProviderApi::class, DelicateCryptographyApi::class)35internal object PasswordBackupEnvelope {36 private const val VERSION = 137 private const val KDF_PBKDF2_SHA256 = 138 private const val AEAD_AES_256_GCM = 139 private const val PAYLOAD_RAW_YOKAN_JSON = 140 private const val ITERATIONS = 600_00041 private const val MAX_ITERATIONS = 2_000_00042 private const val KEY_SIZE_BYTES = 3243 private const val SALT_SIZE = 1644 private const val NONCE_SIZE = 1245 private const val TAG_SIZE = 1646 private const val HEADER_SIZE = 8 + 1 + 1 + 1 + 1 + 4 + SALT_SIZE + NONCE_SIZE47 private const val MAX_PAYLOAD_SIZE = 64 * 1024 * 102448 private const val MAX_ENVELOPE_SIZE = HEADER_SIZE + MAX_PAYLOAD_SIZE + TAG_SIZE49 private val MAGIC = "YOKANENC".encodeToByteArray()50 private val provider = CryptographyProvider.Default5152 suspend fun encode(payload: ByteArray, password: String): PasswordBackupEnvelopeResult =53 encodeWithEntropy(payload, password) { size -> CryptographyRandom.Default.nextBytes(size) }5455 suspend fun decode(envelope: ByteArray, password: String): PasswordBackupEnvelopeResult {56 coroutineContext.ensureActive()57 val passwordBytes = passwordBytes(password)58 ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)59 if (envelope.size < HEADER_SIZE + TAG_SIZE || envelope.size > MAX_ENVELOPE_SIZE) {60 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)61 }6263 val header = envelope.copyOfRange(0, HEADER_SIZE)64 if (!header.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) {65 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)66 }67 if (header[8].unsigned() != VERSION ||68 header[9].unsigned() != KDF_PBKDF2_SHA256 ||69 header[10].unsigned() != AEAD_AES_256_GCM ||70 header[11].unsigned() != PAYLOAD_RAW_YOKAN_JSON71 ) {72 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Unsupported)73 }7475 val iterations = readInt(header, 12)76 if (iterations !in ITERATIONS..MAX_ITERATIONS) {77 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)78 }7980 val ciphertext = envelope.copyOfRange(HEADER_SIZE, envelope.size)81 if (ciphertext.size < TAG_SIZE || ciphertext.size - TAG_SIZE > MAX_PAYLOAD_SIZE) {82 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)83 }8485 val key = catchingNonCancellation {86 deriveKey(passwordBytes, header.copyOfRange(16, 16 + SALT_SIZE), iterations)87 }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }88 val aesKey = catchingNonCancellation {89 provider.get(AES.GCM).keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key)90 }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }91 val cipher = catchingNonCancellation { aesKey.cipher(AES.Key.Size.B128) }92 .getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }93 val plaintext = catchingNonCancellation {94 cipher.decryptWithIv(95 header.copyOfRange(16 + SALT_SIZE, HEADER_SIZE),96 ciphertext,97 header,98 )99 }.getOrElse { return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.AuthenticationFailed) }100 return if (plaintext.size > MAX_PAYLOAD_SIZE) {101 PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.Malformed)102 } else {103 PasswordBackupEnvelopeResult.Success(plaintext)104 }105 }106107 internal suspend fun encodeForTesting(108 payload: ByteArray,109 password: String,110 salt: ByteArray,111 nonce: ByteArray,112 ): PasswordBackupEnvelopeResult {113 coroutineContext.ensureActive()114 if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) {115 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)116 }117 return encodeWithEntropy(payload, password) { size ->118 when (size) {119 SALT_SIZE -> salt.copyOf()120 NONCE_SIZE -> nonce.copyOf()121 else -> error("Unexpected envelope entropy request")122 }123 }124 }125126 private suspend fun encodeWithEntropy(127 payload: ByteArray,128 password: String,129 entropy: (Int) -> ByteArray,130 ): PasswordBackupEnvelopeResult {131 coroutineContext.ensureActive()132 val passwordBytes = passwordBytes(password)133 ?: return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)134 if (payload.size > MAX_PAYLOAD_SIZE) {135 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.InvalidInput)136 }137138 return catchingNonCancellation {139 val salt = entropy(SALT_SIZE)140 val nonce = entropy(NONCE_SIZE)141 if (salt.size != SALT_SIZE || nonce.size != NONCE_SIZE) {142 return PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure)143 }144 val header = ByteArray(HEADER_SIZE).also {145 MAGIC.copyInto(it)146 it[8] = VERSION.toByte()147 it[9] = KDF_PBKDF2_SHA256.toByte()148 it[10] = AEAD_AES_256_GCM.toByte()149 it[11] = PAYLOAD_RAW_YOKAN_JSON.toByte()150 writeInt(it, 12, ITERATIONS)151 salt.copyInto(it, 16)152 nonce.copyInto(it, 16 + SALT_SIZE)153 }154 val key = deriveKey(passwordBytes, salt, ITERATIONS)155 val aes = provider.get(AES.GCM)156 val aesKey = aes.keyDecoder().decodeFromByteArray(AES.Key.Format.RAW, key)157 val ciphertext = aesKey.cipher(AES.Key.Size.B128).encryptWithIv(nonce, payload, header)158 PasswordBackupEnvelopeResult.Success(header + ciphertext)159 }.getOrElse { PasswordBackupEnvelopeResult.Failure(PasswordBackupEnvelopeError.CryptoFailure) }160 }161162 private suspend fun deriveKey(password: ByteArray, salt: ByteArray, iterations: Int): ByteArray {163 val pbkdf2 = provider.get(PBKDF2)164 return pbkdf2.secretDerivation(SHA256, iterations, AES.Key.Size.B256, salt)165 .deriveSecretToByteArray(password)166 }167168 private fun passwordBytes(password: String): ByteArray? = password.takeIf(::isValidBackupPassword)?.encodeToByteArray()169170 private fun readInt(bytes: ByteArray, offset: Int): Int =171 (bytes[offset].unsigned() shl 24) or172 (bytes[offset + 1].unsigned() shl 16) or173 (bytes[offset + 2].unsigned() shl 8) or174 bytes[offset + 3].unsigned()175176 private fun writeInt(bytes: ByteArray, offset: Int, value: Int) {177 bytes[offset] = (value ushr 24).toByte()178 bytes[offset + 1] = (value ushr 16).toByte()179 bytes[offset + 2] = (value ushr 8).toByte()180 bytes[offset + 3] = value.toByte()181 }182183 private fun Byte.unsigned(): Int = toInt() and 0xff184}185