CryptoBridge.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/CryptoBridge.kt
1package eu.friedcutlet.yokan.services.extensions.js23import kotlinx.serialization.json.JsonArray4import kotlinx.serialization.json.JsonPrimitive5import kotlinx.serialization.json.buildJsonObject6import kotlinx.serialization.json.contentOrNull7import kotlin.io.encoding.Base648import kotlin.io.encoding.ExperimentalEncodingApi9import kotlin.experimental.xor10import eu.friedcutlet.yokan.util.sha25611import eu.friedcutlet.yokan.util.sha11213/**14 * Common crypto helpers exposed to JS extensions. The `expect` functions below back AES and SHA;15 * encoding helpers stay in shared code.16 */17internal object CryptoBridge {18 @OptIn(ExperimentalEncodingApi::class)19 fun aes(payload: String): String {20 val args = payloadArray(payload).primitives()21 val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()22 val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())23 val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())24 val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())25 val output = when (mode) {26 "encrypt" -> aesEncrypt(key, iv, data)27 "decrypt" -> aesDecrypt(key, iv, data)28 else -> null29 } ?: return "null"30 return buildJsonObject {31 put("hex", JsonPrimitive(output.toHexString()))32 put("base64", JsonPrimitive(Base64.encode(output)))33 put("utf8", JsonPrimitive(output.decodeToString()))34 }.toString()35 }3637 @OptIn(ExperimentalEncodingApi::class)38 fun digest(payload: String): String {39 val args = payloadArray(payload).primitives()40 val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase()41 val data = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())42 val digest = when (algorithm) {43 "SHA-256", "SHA256" -> sha256(data)44 "SHA-1", "SHA1" -> sha1(data)45 "MD5" -> md5(data)46 else -> null47 } ?: return "null"48 return buildJsonObject {49 put("hex", JsonPrimitive(digest.toHexString()))50 put("base64", JsonPrimitive(Base64.encode(digest)))51 }.toString()52 }5354 @OptIn(ExperimentalEncodingApi::class)55 fun base64(payload: String): String {56 val args = payloadArray(payload).primitives()57 val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()58 val data = args.getOrNull(1)?.contentOrNull.orEmpty()59 return when (mode) {60 "encode" -> JsonPrimitive(Base64.encode(data.encodeToByteArray())).toString()61 "decode" -> runCatching { JsonPrimitive(Base64.decode(data).decodeToString()).toString() }.getOrDefault("null")62 else -> "null"63 }64 }6566 @OptIn(ExperimentalEncodingApi::class)67 fun hmac(payload: String): String {68 val args = payloadArray(payload).primitives()69 val algorithm = args.getOrNull(0)?.contentOrNull.orEmpty().uppercase()70 val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())71 val message = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())72 val blockSize = 6473 val hashFn: (ByteArray) -> ByteArray = when (algorithm) {74 "SHA-256", "SHA256" -> ::sha25675 "SHA-1", "SHA1" -> ::sha176 "MD5" -> ::md577 else -> return "null"78 }79 val normalizedKey = if (key.size > blockSize) hashFn(key) else key80 val paddedKey = normalizedKey.copyOf(blockSize)81 val innerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x36).toByte() }82 val outerPad = ByteArray(blockSize) { (paddedKey[it].toInt() xor 0x5c).toByte() }83 val inner = hashFn(innerPad + message)84 val digest = hashFn(outerPad + inner)85 return buildJsonObject {86 put("hex", JsonPrimitive(digest.toHexString()))87 put("base64", JsonPrimitive(Base64.encode(digest)))88 }.toString()89 }9091 @OptIn(ExperimentalEncodingApi::class)92 fun tripleDes(payload: String): String {93 val args = payloadArray(payload).primitives()94 val keyRaw = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())95 val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())96 val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())97 if (iv.size != 8) return "null"98 // Normalize the key to 24 bytes: DESede accepts 16-byte keys as K1|K2|K1.99 val key = when (keyRaw.size) {100 24 -> keyRaw101 16 -> keyRaw + keyRaw.copyOfRange(0, 8)102 else -> return "null"103 }104 val output = runCatching { DesCipher.tripleDesCbcEncrypt(key, iv, data) }.getOrNull() ?: return "null"105 return buildJsonObject {106 put("hex", JsonPrimitive(output.toHexString()))107 put("base64", JsonPrimitive(Base64.encode(output)))108 }.toString()109 }110111 @OptIn(ExperimentalEncodingApi::class)112 fun aesGcm(payload: String): String {113 val args = payloadArray(payload).primitives()114 val mode = args.getOrNull(0)?.contentOrNull.orEmpty().lowercase()115 val key = decodeHexOrBase64(args.getOrNull(1)?.contentOrNull.orEmpty())116 val iv = decodeHexOrBase64(args.getOrNull(2)?.contentOrNull.orEmpty())117 val data = decodeHexOrBase64(args.getOrNull(3)?.contentOrNull.orEmpty())118 val additionalData = decodeHexOrBase64(args.getOrNull(4)?.contentOrNull.orEmpty())119 val output = when (mode) {120 "encrypt" -> aesGcmEncrypt(key, iv, data, additionalData)121 "decrypt" -> aesGcmDecrypt(key, iv, data, additionalData)122 else -> null123 } ?: return "null"124 return buildJsonObject {125 put("hex", JsonPrimitive(output.toHexString()))126 put("base64", JsonPrimitive(Base64.encode(output)))127 put("utf8", JsonPrimitive(output.decodeToString()))128 }.toString()129 }130131 // Non-primitive arguments become null in place so later argument indexes stay aligned.132 private fun JsonArray.primitives(): List<JsonPrimitive?> = map { it as? JsonPrimitive }133134 @OptIn(ExperimentalEncodingApi::class, ExperimentalStdlibApi::class)135 private fun decodeHexOrBase64(value: String): ByteArray {136 if (value.isBlank()) return ByteArray(0)137 if (value.length % 2 == 0 && value.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' }) {138 return runCatching { value.hexToByteArray() }.getOrElse { ByteArray(0) }139 }140 return runCatching { Base64.decode(value) }.getOrElse { value.encodeToByteArray() }141 }142}143144/**145 * Pure-Kotlin MD5 (RFC 1321). MD5 is not exposed by every platform's crypto146 * provider, so it lives in shared code to keep extension behavior identical147 * across Android, desktop, and iOS.148 */149internal fun md5(message: ByteArray): ByteArray {150 val s = intArrayOf(151 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,152 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,153 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,154 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,155 )156 val k = intArrayOf(157 -680876936, -389564586, 606105819, -1044525330, -176418897, 1200080426, -1473231341, -45705983,158 1770035416, -1958414417, -42063, -1990404162, 1804603682, -40341101, -1502002290, 1236535329,159 -165796510, -1069501632, 643717713, -373897302, -701558691, 38016083, -660478335, -405537848,160 568446438, -1019803690, -187363961, 1163531501, -1444681467, -51403784, 1735328473, -1926607734,161 -378558, -2022574463, 1839030562, -35309556, -1530992060, 1272893353, -155497632, -1094730640,162 681279174, -358537222, -722521979, 76029189, -640364487, -421815835, 530742520, -995338651,163 -198630844, 1126891415, -1416354905, -57434055, 1700485571, -1894986606, -1051523, -2054922799,164 1873313359, -30611744, -1560198380, 1309151649, -145523070, -1120210379, 718787259, -343485551,165 )166 val a0 = 0x67452301; val b0 = -0x10325477; val c0 = -0x67452302; val d0 = 0x10325476167 val originalLenBits = message.size.toLong() * 8168 val paddedLen = (((message.size + 8) / 64) + 1) * 64169 val padded = message.copyOf(paddedLen)170 padded[message.size] = 0x80.toByte()171 for (i in 0 until 8) padded[paddedLen - 8 + i] = ((originalLenBits ushr (8 * i)) and 0xff).toByte()172 var a = a0; var b = b0; var c = c0; var d = d0173 val m = IntArray(16)174 var chunk = 0175 while (chunk < paddedLen) {176 for (i in 0 until 16) {177 val j = chunk + i * 4178 m[i] = (padded[j].toInt() and 0xff) or179 ((padded[j + 1].toInt() and 0xff) shl 8) or180 ((padded[j + 2].toInt() and 0xff) shl 16) or181 ((padded[j + 3].toInt() and 0xff) shl 24)182 }183 var aa = a; var bb = b; var cc = c; var dd = d184 for (i in 0 until 64) {185 var f: Int; val g: Int186 when {187 i < 16 -> { f = (bb and cc) or (bb.inv() and dd); g = i }188 i < 32 -> { f = (dd and bb) or (dd.inv() and cc); g = (5 * i + 1) % 16 }189 i < 48 -> { f = bb xor cc xor dd; g = (3 * i + 5) % 16 }190 else -> { f = cc xor (bb or dd.inv()); g = (7 * i) % 16 }191 }192 f += aa + k[i] + m[g]193 aa = dd; dd = cc; cc = bb194 bb += (f shl s[i]) or (f ushr (32 - s[i]))195 }196 a += aa; b += bb; c += cc; d += dd197 chunk += 64198 }199 val out = ByteArray(16)200 val words = intArrayOf(a, b, c, d)201 for (w in 0 until 4) for (i in 0 until 4) out[w * 4 + i] = ((words[w] ushr (8 * i)) and 0xff).toByte()202 return out203}204205internal fun aesGcmEncrypt(206 key: ByteArray,207 iv: ByteArray,208 plaintext: ByteArray,209 additionalData: ByteArray = ByteArray(0),210): ByteArray? {211 if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE) return null212 val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null213 val initialCounter = iv + byteArrayOf(0, 0, 0, 1)214 val ciphertext = gcmCounterCrypt(key, initialCounter, plaintext) ?: return null215 val authentication = gcmHash(hashSubkey, additionalData, ciphertext)216 val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null217 val tag = ByteArray(GCM_TAG_SIZE) { encryptedCounter[it] xor authentication[it] }218 return ciphertext + tag219}220221internal fun aesGcmDecrypt(222 key: ByteArray,223 iv: ByteArray,224 ciphertextAndTag: ByteArray,225 additionalData: ByteArray = ByteArray(0),226): ByteArray? {227 if (key.size !in setOf(16, 24, 32) || iv.size != GCM_IV_SIZE || ciphertextAndTag.size < GCM_TAG_SIZE) {228 return null229 }230 val ciphertext = ciphertextAndTag.copyOfRange(0, ciphertextAndTag.size - GCM_TAG_SIZE)231 val suppliedTag = ciphertextAndTag.copyOfRange(ciphertext.size, ciphertextAndTag.size)232 val hashSubkey = aesEncryptBlock(key, ByteArray(GCM_BLOCK_SIZE)) ?: return null233 val initialCounter = iv + byteArrayOf(0, 0, 0, 1)234 val authentication = gcmHash(hashSubkey, additionalData, ciphertext)235 val encryptedCounter = aesEncryptBlock(key, initialCounter) ?: return null236 var tagDifference = 0237 for (index in suppliedTag.indices) {238 tagDifference = tagDifference or (239 (suppliedTag[index].toInt() and 0xff) xor240 ((encryptedCounter[index] xor authentication[index]).toInt() and 0xff)241 )242 }243 if (tagDifference != 0) return null244 return gcmCounterCrypt(key, initialCounter, ciphertext)245}246247private fun gcmCounterCrypt(key: ByteArray, initialCounter: ByteArray, input: ByteArray): ByteArray? {248 val output = ByteArray(input.size)249 val counter = initialCounter.copyOf()250 var offset = 0251 while (offset < input.size) {252 incrementCounter(counter)253 val keyStream = aesEncryptBlock(key, counter) ?: return null254 val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset)255 for (index in 0 until blockSize) {256 output[offset + index] = input[offset + index] xor keyStream[index]257 }258 offset += blockSize259 }260 return output261}262263private fun incrementCounter(counter: ByteArray) {264 for (index in counter.lastIndex downTo counter.size - 4) {265 counter[index] = (counter[index] + 1).toByte()266 if (counter[index].toInt() != 0) return267 }268}269270private fun gcmHash(hashSubkey: ByteArray, additionalData: ByteArray, ciphertext: ByteArray): ByteArray {271 var accumulator = ByteArray(GCM_BLOCK_SIZE)272 fun absorb(input: ByteArray) {273 var offset = 0274 while (offset < input.size) {275 val block = ByteArray(GCM_BLOCK_SIZE)276 val blockSize = minOf(GCM_BLOCK_SIZE, input.size - offset)277 input.copyInto(block, endIndex = offset + blockSize, startIndex = offset)278 accumulator = gcmMultiply(accumulator.xor(block), hashSubkey)279 offset += blockSize280 }281 }282 absorb(additionalData)283 absorb(ciphertext)284 val lengthBlock = ByteArray(GCM_BLOCK_SIZE)285 val additionalDataBits = additionalData.size.toLong() * 8L286 val ciphertextBits = ciphertext.size.toLong() * 8L287 for (index in 0 until 8) {288 lengthBlock[7 - index] = (additionalDataBits ushr (index * 8)).toByte()289 lengthBlock[GCM_BLOCK_SIZE - 1 - index] = (ciphertextBits ushr (index * 8)).toByte()290 }291 return gcmMultiply(accumulator.xor(lengthBlock), hashSubkey)292}293294private fun gcmMultiply(left: ByteArray, right: ByteArray): ByteArray {295 val product = ByteArray(GCM_BLOCK_SIZE)296 val factor = right.copyOf()297 for (bitIndex in 0 until GCM_BLOCK_SIZE * 8) {298 val byteIndex = bitIndex / 8299 val bitMask = 1 shl (7 - bitIndex % 8)300 if ((left[byteIndex].toInt() and bitMask) != 0) {301 for (index in product.indices) product[index] = product[index] xor factor[index]302 }303 val leastSignificantBit = factor.last().toInt() and 1304 var carry = 0305 for (index in factor.indices) {306 val value = factor[index].toInt() and 0xff307 factor[index] = ((value ushr 1) or carry).toByte()308 carry = (value and 1) shl 7309 }310 if (leastSignificantBit != 0) factor[0] = factor[0] xor 0xe1.toByte()311 }312 return product313}314315private fun ByteArray.xor(other: ByteArray): ByteArray =316 ByteArray(size) { index -> this[index] xor other[index] }317318private const val GCM_BLOCK_SIZE = 16319private const val GCM_IV_SIZE = 12320private const val GCM_TAG_SIZE = 16321322expect fun aesEncryptBlock(key: ByteArray, block: ByteArray): ByteArray?323324expect fun aesEncrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?325expect fun aesDecrypt(key: ByteArray, iv: ByteArray, data: ByteArray): ByteArray?326