package eu.friedcutlet.yokan.services.extensions.js import dev.whyoleg.cryptography.CryptographyProvider import dev.whyoleg.cryptography.DelicateCryptographyApi import dev.whyoleg.cryptography.algorithms.AES import dev.whyoleg.cryptography.operations.IvCipher // JDK provider on Android/desktop, CryptoKit + CommonCrypto on iOS. Invalid key sizes and // malformed ciphertext throw inside the provider; the JS bridge contract is null instead. private val provider = CryptographyProvider.Default private const val AES_BLOCK_SIZE = 16 @OptIn(DelicateCryptographyApi::class) actual fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? { if (iv.size != AES_BLOCK_SIZE) return null return runCatching { aesCbcCipher(key).encryptWithIvBlocking(iv, data) }.getOrNull() } @OptIn(DelicateCryptographyApi::class) actual fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? { if (iv.size != AES_BLOCK_SIZE) return null return runCatching { aesCbcCipher(key).decryptWithIvBlocking(iv, data) }.getOrNull() } @OptIn(DelicateCryptographyApi::class) actual fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? { if (block.size != AES_BLOCK_SIZE) return null return runCatching { provider.get(AES.ECB) .keyDecoder() .decodeFromByteArrayBlocking(AES.Key.Format.RAW, key) .cipher(padding = false) .encryptBlocking(block) }.getOrNull() } // PKCS#7 padding, matching the previous `AES/CBC/PKCS5Padding` and `kCCOptionPKCS7Padding` actuals. private fun aesCbcCipher(key: ByteArray): IvCipher = provider.get(AES.CBC) .keyDecoder() .decodeFromByteArrayBlocking(AES.Key.Format.RAW, key) .cipher(padding = true)