Skip to content

Instantly share code, notes, and snippets.

@lovubuntu
Created November 24, 2017 15:58
Show Gist options
  • Star 38 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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) })
}
}
@mochadwi
Copy link

mochadwi commented Mar 12, 2019

thank you very much!!! @lovubuntu

for performance issue, maybe everyone can check samclarke post here:

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

@reastland
Copy link

reastland commented Dec 30, 2019

This is a nice little class. If you pass the algorithm ("SHA-256" in this example), it can be generalized to hash strings using different algorithms:

As an extension functions:

fun String.md5(): String {
    return hashString(this, "MD5")
}

fun String.sha256(): String {
    return hashString(this, "SHA-256")
}

private fun hashString(input: String, algorithm: String): String {
    return MessageDigest
        .getInstance(algorithm)
        .digest(input.toByteArray())
        .fold("", { str, it -> str + "%02x".format(it) })
}

@Fl0r3
Copy link

Fl0r3 commented Feb 12, 2020

class keyword has to be written in lowercase! @lovubuntu

@ImMohMol
Copy link

Thank you that was really nice :)

@Thomas-Bagnolati
Copy link

Thank that help me

@patiljignesh
Copy link

Thank you @reastland

@OndraZizka
Copy link

This is going to have bad performance.
Better:

val hex = digest.fold(StringBuilder(), { sb, it -> sb.append("%02x".format(it)) }).toString()

@stephmafole
Copy link

Thanks to y'all

Your answers have saved my day

@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