Skip to content

Instantly share code, notes, and snippets.

@lovubuntu
Created November 24, 2017 15:58
Show Gist options
  • Save lovubuntu/164b6b9021f5ba54cefc67f60f7a1a25 to your computer and use it in GitHub Desktop.
Save lovubuntu/164b6b9021f5ba54cefc67f60f7a1a25 to your computer and use it in GitHub Desktop.
function to generate Sha-256 in Kotlin
Class Hasher {
fun hash(): String {
val bytes = this.toString().toByteArray()
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(bytes)
return digest.fold("", { str, it -> str + "%02x".format(it) })
}
}
@ChristianGarcia
Copy link

You can replace the fold with toHexString() (Mind you that this is, as of the time of writing this, marked as ExperimentalStdlibApi):

fun String.hashedWithSha256() =
    MessageDigest.getInstance("SHA-256")
        .digest(toByteArray())
        .toHexString()

val hashed = "12345".hashedWithSha256() // "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment