Yokan / rebuild
Course 1 8624561

CryptoBridge.nonWeb.kt

composeApp/src/nonWebMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridge.nonWeb.kt

implementation42 lines
1package eu.friedcutlet.yokan.services.extensions.js23import dev.whyoleg.cryptography.CryptographyProvider4import dev.whyoleg.cryptography.DelicateCryptographyApi5import dev.whyoleg.cryptography.algorithms.AES6import dev.whyoleg.cryptography.operations.IvCipher78// JDK provider on Android/desktop, CryptoKit + CommonCrypto on iOS. Invalid key sizes and9// malformed ciphertext throw inside the provider; the JS bridge contract is null instead.10private val provider = CryptographyProvider.Default1112private const val AES_BLOCK_SIZE = 161314@OptIn(DelicateCryptographyApi::class)15actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {16    if (iv.size != AES_BLOCK_SIZE) return null17    return runCatching { aesCbcCipher(key).encryptWithIvBlocking(iv, data) }.getOrNull()18}1920@OptIn(DelicateCryptographyApi::class)21actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? {22    if (iv.size != AES_BLOCK_SIZE) return null23    return runCatching { aesCbcCipher(key).decryptWithIvBlocking(iv, data) }.getOrNull()24}2526@OptIn(DelicateCryptographyApi::class)27actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? {28    if (block.size != AES_BLOCK_SIZE) return null29    return runCatching {30        provider.get(AES.ECB)31            .keyDecoder()32            .decodeFromByteArrayBlocking(AES.Key.Format.RAW, key)33            .cipher(padding = false)34            .encryptBlocking(block)35    }.getOrNull()36}3738// PKCS#7 padding, matching the previous `AES/CBC/PKCS5Padding` and `kCCOptionPKCS7Padding` actuals.39private fun aesCbcCipher(key: ByteArray): IvCipher = provider.get(AES.CBC)40    .keyDecoder()41    .decodeFromByteArrayBlocking(AES.Key.Format.RAW, key)42    .cipher(padding = true)43

Search chapters, reference and source filenames.