This message was deleted.
# announcements
s
This message was deleted.
m
In the above Java code I assume you’re using
javax.crypto
, right? If you’re getting a different output it could depend on how you setup the generator. Could you post your Kotlin code that’s not properly working?
v
Copy code
private const val BLOCK_SIZE_64 = 64
    
    fun sha256(key: String, message: String) = hmac(key.encodeToByteArray(), message.encodeToByteArray(), BLOCK_SIZE_64, SHA2::sha256)
    fun sha256(key: ByteArray, message: ByteArray) = hmacRaw(key, message, BLOCK_SIZE_64, SHA2::sha256)
    
    private fun hmacRaw(key: ByteArray, message: ByteArray, blockSize: Int, hashFunction: (m: ByteArray) -> ByteArray): ByteArray {

        var preprocessedKey = key
        if (preprocessedKey.size > blockSize) {
            preprocessedKey = hashFunction(preprocessedKey)
        }

        if (preprocessedKey.size < blockSize) {
            preprocessedKey = preprocessedKey.copyOf(blockSize)
        }

        val outerPaddedKey = xorByteArray(preprocessedKey, ByteArray(blockSize) { 0x5c })
        val innerPaddedKey = xorByteArray(preprocessedKey, ByteArray(blockSize) { 0x36 })

        val ipk = hashFunction(appendBytes(innerPaddedKey, message))
        return hashFunction(appendBytes(outerPaddedKey, ipk))
    }

    private fun hmac(key: ByteArray, message: ByteArray, blockSize: Int, hashFunction: (m: ByteArray) -> ByteArray): String {
        return Hex.encode(hmacRaw(key, message, blockSize, hashFunction))
    }

    private fun xorByteArray(a: ByteArray, b: ByteArray): ByteArray {
        val result = ByteArray(a.size)
        for (i in b.indices) {
            result[i] = (a[i].toInt() xor b[i].toInt()).toByte()
        }
        return result
    }

    private fun appendBytes(origin: ByteArray, bytesToAppend: ByteArray): ByteArray {
        val result = origin.copyOf(origin.size + bytesToAppend.size)
        for (i in bytesToAppend.indices) {
            result[i + origin.size] = bytesToAppend[i]
        }
        return result
    }
My Kotlin Code is Above
HMACSHA256
I Can’t got the same result as javax
if my data =
Copy code
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN0
they are different but if +/- one char
Copy code
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN01
Copy code
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN
they are the same