Algorithm

This algorithm is a helper to convert check and anything for help in utils/Utils.kt file.

Luhn algorithm

The Luhn algorithm or Luhn formula is algorithm to validate card number in format.

fun cardIsValid(cardNumber: String): Boolean {
    var s1 = 0
    var s2 = 0
    val reverse = StringBuffer(cardNumber).reverse().toString()
    for (i in reverse.indices) {
        val digit = Character.digit(reverse[i], 10)
        when {
            i % 2 == 0 -> s1 += digit
            else -> {
                s2 += 2 * digit
                when {
                    digit >= 5 -> s2 -= 9
                }
            }
        }
    }
    return (s1 + s2) % 10 == 0
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Decimal to HEX string

fun decimalToHexString(payload: Byte): String {
    return when (payload.toUByte().toString(16).length) {
        1 -> "0${payload.toUByte().toString(16)}"
        else -> payload.toUByte().toString(16)
    }
}
1
2
3
4
5
6

HEX string to binary

fun hexToBinary(hex: Any): String? {
        var bin: String = BigInteger(hex.toString(), 16).toString(2)
        val inb = bin.toInt()
        bin = java.lang.String.format(Locale.getDefault(), "%08d", inb)
        return bin
}
1
2
3
4
5
6

HEX string to binary (Use when to change bitmap)

fun hexToBinary(hex: Any): String? {
     return BigInteger(hex.toString(), 16).toString(2).padStart(64,'0')
}
1
2
3

Decimal to Octal

fun convertDecimalToOctal(decimal: Int): Int {
    var decimal = decimal
    var octalNumber = 0
    var i = 1

    while (decimal != 0) {
        octalNumber += decimal % 8 * i
        decimal /= 8
        i *= 10
    }

    return octalNumber
}
1
2
3
4
5
6
7
8
9
10
11
12
13

HEX string to ASCII

fun hexToAscii(hexValue: String): String {
    try {
        if (hexValue.length % 2 != 0) {
            throw Exception("Invalid payload")
        }
        val builder = StringBuilder()

        run {
            var i = 0
            while (i < hexValue.length) {

                // Step-1 Split the hex string into two character group
                val s: String = hexValue.substring(i, i + 2)
                // Step-2 Convert the each character group into integer using valueOf method
                val n = Integer.valueOf(s, 16)
                // Step-3 Cast the integer value to char
                builder.append(n.toChar())
                i += 2
            }
        }

        return builder.toString()
    } catch (e: Exception) {
        Log.e("test", "hex to ascii exeption $e")
        throw  Exception(e.message)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

ASCII to HEX String

fun asciiToHex(asciiValue: String): String {
    return asciiValue.map { it.code.toString(16) }.joinToString("")
}
1
2
3

HEX list string to HEX string

fun hexToString(payload: List<Any>): String {
    val newPayload = StringBuilder()
    if (payload.isEmpty()) {
        return ""
    }
    for (i in payload) {
        newPayload.append(i)
    }
    return newPayload.toString()
}
1
2
3
4
5
6
7
8
9
10

Triple DES

Encrypt

private fun tdes(data: String): String {
    try {
        val key = ("31313131313131313131313131313131").hexStringToByteArray()
        val dataIn = (data).hexStringToByteArray()
        val mode = AlgMode.EM_alg_TDESENCRYPT or AlgMode.EM_alg_TDESTCBCMODE
        val encResult = BytesValue()
        val ret = algorithm.TDES(mode, key, dataIn, encResult)
        if (ret != AlgError.SUCCESS) {
            return "Error"
        }
        return encResult.toHexString()
    } catch (e: Exception) {
        throw Exception(e.message)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Decrypt

private fun tdesDecrypt(data: String): String {
    try {
        val key = ("31313131313131313131313131313131").hexStringToByteArray()
        val dataIn = (data).hexStringToByteArray()
        val mode = AlgMode.EM_alg_TDESDECRYPT or AlgMode.EM_alg_TDESTCBCMODE
        val decResult = BytesValue()
        val ret = algorithm.TDES(mode, key, dataIn, decResult)
        if (ret != AlgError.SUCCESS) {
            return "Error"
        }
        return decResult.toHexString()
    } catch (e: Exception) {
        throw Exception(e.message)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Calculate MAC

private fun calMAC(data: String): String? {
    try {
        val key = BytesUtil.hexString2Bytes("31313131313131313131313131313131")
        val dataIn =
            BytesUtil.hexString2Bytes(data)
        val mode = AlgMode.EM_alg_MACALGORITHM1 or AlgMode.EM_alg_MACPADMODE1
        val dataOut = BytesValue()
        val ret = algorithm.calcMAC(mode, key, dataIn, dataOut)

        return dataOut.toHexString()

    } catch (e: Exception) {
        throw Exception(e.message)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Helper

ISO8583 to JSON

This function use class ISO8583 in file utils/ISO8583.kt to extract to JSON

fun extractISO8583TOJSON(
    data: ArrayList<String>,
): JSONObject {
    val newData = JSONObject()
    ISO8583().getISO8583Extract(data).let {
        val json = JSONObject(it)
        val jsonArray = json.getJSONArray("data")
        for (i in 0 until jsonArray.length()) {
            val jsonObject = jsonArray.getJSONObject(i)
            newData.put(jsonObject.getString("key"), jsonObject.getString("transformData"))
        }
    }

    return newData
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Last Updated:
Contributors: Supavit Panyafang, Kittison Apaijit