Created
November 24, 2017 15:58
-
-
Save lovubuntu/164b6b9021f5ba54cefc67f60f7a1a25 to your computer and use it in GitHub Desktop.
function to generate Sha-256 in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) }) | |
} | |
} |
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) })
}
class keyword has to be written in lowercase! @lovubuntu
Thank you that was really nice :)
Thank that help me
Thank you @reastland
This is going to have bad performance.
Better:
val hex = digest.fold(StringBuilder(), { sb, it -> sb.append("%02x".format(it)) }).toString()
Thanks to y'all
Your answers have saved my day
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
thank you very much!!! @lovubuntu
for performance issue, maybe everyone can check samclarke post here:
https://www.samclarke.com/kotlin-hash-strings/