Skip to content

Instantly share code, notes, and snippets.

@YuanLiou
Created August 25, 2018 03:11
Show Gist options
  • Save YuanLiou/6f9ecb9a9e59dde6fa41b27d0ef3ad03 to your computer and use it in GitHub Desktop.
Save YuanLiou/6f9ecb9a9e59dde6fa41b27d0ef3ad03 to your computer and use it in GitHub Desktop.
MD5 Extension Function
fun main(argv: Array<String>) {
val md5Result = "Hello World".saltMD5(null)
println("The Salted MD5 Hash is = $md5Result")
}
private fun String.saltMD5(salt: String?): String {
val saltedString = salt?.let { this + it } ?: this
val md5MessageDigest = MessageDigest.getInstance("MD5")
val digest = md5MessageDigest.digest(saltedString.toByteArray())
val stringBuilder = StringBuilder()
for (byte in digest) {
val value = byte.toInt() and 0xff
var hexString = Integer.toHexString(value)
if (hexString.length < 2) {
hexString = "0" + hexString
}
stringBuilder.append(hexString)
}
return stringBuilder.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment