Kotlin Hashing

Hashing is an important concept, it has numerous applications, and it’s at the core of many other computer science concepts.

HashUtils.kt is a very simple, yet very helpful snippet I’ve used in some of my applications when I need some basic hashing. It’s an extension function, one of Kotlin neat features.

package com.isscroberto.onebreath.utils
import java.security.MessageDigest
enum class Algorithm(val code: String) {
SHA1("SHA-1"), SHA256("SHA-256"), SHA512("SHA-512")
}
fun String.hash (algorithm: Algorithm): String {
val hexArray = "0123456789ABCDEF"
val bytes = MessageDigest.getInstance(algorithm.code).digest(this.toByteArray())
val hash = StringBuilder(bytes.size * 2)
bytes.forEach {
val i = it.toInt()
hash.append(hexArray[i shr 4 and 0x0f])
hash.append(hexArray[i and 0x0f])
}
return hash.toString()
}

view raw

HashUtils.kt

hosted with ❤ by GitHub

Usage:

val text = "hello"
val hashedText = text.hash(Algorithm.SHA256)

Reference:
https://www.samclarke.com/kotlin-hash-strings/

Leave a Reply