package eu.friedcutlet.yokan.services.extensions.js import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.experimental.xor import eu.friedcutlet.yokan.util.sha256 import eu.friedcutlet.yokan.util.sha1 /** * Common crypto helpers exposed to JS extensions. The `expect` functions below back AES and SHA; * encoding helpers stay in shared code. */ internal object CryptoBridge { @OptIn(ExperimentalEncodingApi::class) fun aes(payload: String): String { val args = payloadArray(payload).primitives() val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase() val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty()) val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty()) val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty()) val output = when (mode) { "encrypt" -> aesEncrypt(key, iv, data) "decrypt" -> aesDecrypt(key, iv, data) else -> null } ?: return "null" return buildJsonObject { put("hex", JsonPrimitive(output.toHexString())) put("base64", JsonPrimitive(Base64.encode(output))) put("utf8", JsonPrimitive(output.decodeToString())) }.toString() } @OptIn(ExperimentalEncodingApi::class) fun digest(payload: String): String { val args = payloadArray(payload).primitives() val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase() val data = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty()) val digest = when (algorithm) { "SHA-256", "SHA256" -> sha256(data) "SHA-1", "SHA1" -> sha1(data) "MD5" -> md5(data) else -> null } ?: return "null" return buildJsonObject { put("hex", JsonPrimitive(digest.toHexString())) put("base64", JsonPrimitive(Base64.encode(digest))) }.toString() } @OptIn(ExperimentalEncodingApi::class) fun base64(payload: String): String { val args = payloadArray(payload).primitives() val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase() val data = args.getOrNull(1)?.contentOrNull.orEmpty() return when (mode) { "encode" -> JsonPrimitive(Base64.encode(data.encodeToByteArray())).toString() "decode" -> runCatching { JsonPrimitive(Base64.decode(data).decodeToString()).toString() }.getOrDefault("null") else -> "null" } } @OptIn(ExperimentalEncodingApi::class) fun hmac(payload: String): String { val args = payloadArray(payload).primitives() val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase() val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty()) val message = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty()) val blockSize = 64 val hashFn: (ByteArray) -> ByteArray = when (algorithm) { "SHA-256", "SHA256" -> ::sha256 "SHA-1", "SHA1" -> ::sha1 "MD5" -> ::md5 else -> return "null" } val normalizedKey = if (key.size > blockSize) hashFn(key) else key val paddedKey = normalizedKey.copyOf(blockSize) val innerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x36).toByte() } val outerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x5c).toByte() } val inner = hashFn(innerPad + message) val digest = hashFn(outerPad + inner) return buildJsonObject { put("hex", JsonPrimitive(digest.toHexString())) put("base64", JsonPrimitive(Base64.encode(digest))) }.toString() } @OptIn(ExperimentalEncodingApi::class) fun tripleDes(payload: String): String { val args = payloadArray(payload).primitives() val keyRaw = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty()) val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty()) val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty()) if (iv.size != 8) return "null" // Normalize the key to 24 bytes: DESede accepts 16-byte keys as K1|K2|K1. val key = when (keyRaw.size) { 24 -> keyRaw 16 -> keyRaw + keyRaw.copyOfRange(0, 8) else -> return "null" } val output = runCatching { DesCipher.tripleDesCbcEncrypt(key, iv, data) }.getOrNull() ?: return "null" return buildJsonObject { put("hex", JsonPrimitive(output.toHexString())) put("base64", JsonPrimitive(Base64.encode(output))) }.toString() } @OptIn(ExperimentalEncodingApi::class) fun aesGcm(payload: String): String { val args = payloadArray(payload).primitives() val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase() val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty()) val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty()) val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty()) val additionalData = decodeHexOrBase64(args.getOrNull(4)?.contentOrNull.orEmpty()) val output = when (mode) { "encrypt" -> aesGcmEncrypt(key, iv, data, additionalData) "decrypt" -> aesGcmDecrypt(key, iv, data, additionalData) else -> null } ?: return "null" return buildJsonObject { put("hex", JsonPrimitive(output.toHexString())) put("base64", JsonPrimitive(Base64.encode(output))) put("utf8", JsonPrimitive(output.decodeToString())) }.toString() } // Non-primitive arguments become null in place so later argument indexes stay aligned. private fun JsonArray.primitives(): List = map { it as? JsonPrimitive } @OptIn(ExperimentalEncodingApi::class, ExperimentalStdlibApi::class) private fun decodeHexOrBase64(value: String): ByteArray { if (value.isBlank()) return ByteArray(0) if (value.length % 2 == 0 && value.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' }) { return runCatching { value.hexToByteArray() }.getOrElse { ByteArray(0) } } return runCatching { Base64.decode(value) }.getOrElse { value.encodeToByteArray() } } } /** * Pure-Kotlin MD5 (RFC 1321). MD5 is not exposed by every platform's crypto * provider, so it lives in shared code to keep extension behavior identical * across Android, desktop, and iOS. */ internal fun md5(message: ByteArray): ByteArray { val s = intArrayOf( 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ) val k = intArrayOf( -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983, 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329, -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848, 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734, -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640, 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651, -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799, 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551, ) val a0 = 0x67452301; val b0 = -0x10325477; val c0 = -0x67452302; val d0 = 0x10325476 val originalLenBits = message.size.toLong() * 8 val paddedLen = (((message.size + 8) / 64) + 1) * 64 val padded = message.copyOf(paddedLen) padded[message.size] = 0x80.toByte() for (i in 0 until 8) padded[paddedLen - 8 + i] = ((originalLenBits ushr (8 * i)) and 0xff).toByte() var a = a0; var b = b0; var c = c0; var d = d0 val m = IntArray(16) var chunk = 0 while (chunk < paddedLen) { for (i in 0 until 16) { val j = chunk + i * 4 m[i] = (padded[j].toInt() and 0xff) or ((padded[j + 1].toInt() and 0xff) shl 8) or ((padded[j + 2].toInt() and 0xff) shl 16) or ((padded[j + 3].toInt() and 0xff) shl 24) } var aa = a; var bb = b; var cc = c; var dd = d for (i in 0 until 64) { var f: Int; val g: Int when { i < 16 -> { f = (bb and cc) or (bb.inv() and dd); g = i } i < 32 -> { f = (dd and bb) or (dd.inv() and cc); g = (5 * i + 1) % 16 } i < 48 -> { f = bb xor cc xor dd; g = (3 * i + 5) % 16 } else -> { f = cc xor (bb or dd.inv()); g = (7 * i) % 16 } } f += aa + k[i] + m[g] aa = dd; dd = cc; cc = bb bb += (f shl s[i]) or (f ushr (32 - s[i])) } a += aa; b += bb; c += cc; d += dd chunk += 64 } val out = ByteArray(16) val words = intArrayOf(a, b, c, d) for (w in 0 until 4) for (i in 0 until 4) out[w * 4 + i] = ((words[w] ushr (8 * i)) and 0xff).toByte() return out } internal fun aesGcmEncrypt( key: ByteArray, iv: ByteArray, plaintext: ByteArray, additionalData: ByteArray = ByteArray(0), ): ByteArray? { if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE) return null val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null val initialCounter = iv + byteArrayOf(0, 0, 0, 1) val ciphertext = gcmCounterCrypt(key, initialCounter, plaintext) ?: return null val authentication = gcmHash(hashSubkey, additionalData, ciphertext) val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null val tag = ByteArray(GCM_TAG_SIZE) { encryptedCounter[it] xor authentication[it] } return ciphertext + tag } internal fun aesGcmDecrypt( key: ByteArray, iv: ByteArray, ciphertextAndTag: ByteArray, additionalData: ByteArray = ByteArray(0), ): ByteArray? { if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE || ciphertextAndTag.size < GCM_TAG_SIZE) { return null } val ciphertext = ciphertextAndTag.copyOfRange(0, ciphertextAndTag.size - GCM_TAG_SIZE) val suppliedTag = ciphertextAndTag.copyOfRange(ciphertext.size, ciphertextAndTag.size) val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null val initialCounter = iv + byteArrayOf(0, 0, 0, 1) val authentication = gcmHash(hashSubkey, additionalData, ciphertext) val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null var tagDifference = 0 for (index in suppliedTag.indices) { tagDifference = tagDifference or ( (suppliedTag[index].toInt() and 0xff) xor ((encryptedCounter[index] xor authentication[index]).toInt() and 0xff) ) } if (tagDifference != 0) return null return gcmCounterCrypt(key, initialCounter, ciphertext) } private fun gcmCounterCrypt(key: ByteArray, initialCounter: ByteArray, input: ByteArray): ByteArray? { val output = ByteArray(input.size) val counter = initialCounter.copyOf() var offset = 0 while (offset < input.size) { incrementCounter(counter) val keyStream = aesEncryptBlock(key, counter) ?: return null val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset) for (index in 0 until blockSize) { output[offset + index] = input[offset + index] xor keyStream[index] } offset += blockSize } return output } private fun incrementCounter(counter: ByteArray) { for (index in counter.lastIndex downTo counter.size - 4) { counter[index] = (counter[index] + 1).toByte() if (counter[index].toInt() != 0) return } } private fun gcmHash(hashSubkey: ByteArray, additionalData: ByteArray, ciphertext: ByteArray): ByteArray { var accumulator = ByteArray(GCM_BLOCK_SIZE) fun absorb(input: ByteArray) { var offset = 0 while (offset < input.size) { val block = ByteArray(GCM_BLOCK_SIZE) val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset) input.copyInto(block, endIndex = offset + blockSize, startIndex = offset) accumulator = gcmMultiply(accumulator.xor(block), hashSubkey) offset += blockSize } } absorb(additionalData) absorb(ciphertext) val lengthBlock = ByteArray(GCM_BLOCK_SIZE) val additionalDataBits = additionalData.size.toLong() * 8L val ciphertextBits = ciphertext.size.toLong() * 8L for (index in 0 until 8) { lengthBlock[7 - index] = (additionalDataBits ushr (index * 8)).toByte() lengthBlock[GCM_BLOCK_SIZE - 1 - index] = (ciphertextBits ushr (index * 8)).toByte() } return gcmMultiply(accumulator.xor(lengthBlock), hashSubkey) } private fun gcmMultiply(left: ByteArray, right: ByteArray): ByteArray { val product = ByteArray(GCM_BLOCK_SIZE) val factor = right.copyOf() for (bitIndex in 0 until GCM_BLOCK_SIZE * 8) { val byteIndex = bitIndex / 8 val bitMask = 1 shl (7 - bitIndex % 8) if ((left[byteIndex].toInt() and bitMask) != 0) { for (index in product.indices) product[index] = product[index] xor factor[index] } val leastSignificantBit = factor.last().toInt() and 1 var carry = 0 for (index in factor.indices) { val value = factor[index].toInt() and 0xff factor[index] = ((value ushr 1) or carry).toByte() carry = (value and 1) shl 7 } if (leastSignificantBit != 0) factor[0] = factor[0] xor 0xe1.toByte() } return product } private fun ByteArray.xor(other: ByteArray): ByteArray = ByteArray(size) { index -> this[index] xor other[index] } private const val GCM_BLOCK_SIZE = 16 private const val GCM_IV_SIZE = 12 private const val GCM_TAG_SIZE = 16 expect fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray? expect fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray? expect fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?