Slackbot
10/02/2019, 2:45 PMMatteo Mirk
10/03/2019, 1:14 PMjavax.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?Vincent Chen
10/04/2019, 7:46 AMprivate 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
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN0
they are different
but if +/- one char
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN01
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJpc3MiOiJOZXh0IEN
they are the same