Created
August 11, 2020 05:07
-
-
Save downthecrop/10d0e8415a37dfddbe0f9d6be32dc3ba to your computer and use it in GitHub Desktop.
kotlin md5 to hex
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
private fun File.calcHash(algorithm: String = "MD5", bufferSize: Int = 1024): String { | |
this.inputStream().use { input -> | |
val buffer = ByteArray(bufferSize) | |
val digest = MessageDigest.getInstance(algorithm) | |
read@ while (true) { | |
when (val bytesRead = input.read(buffer)) { | |
-1 -> break@read | |
else -> digest.update(buffer, 0, bytesRead) | |
} | |
} | |
return digest.digest().toHexString() | |
} | |
} | |
private fun ByteArray.toHexString(): String { | |
return this.fold(StringBuilder()) { result, b -> result.append(String.format("%02X", b)) }.toString().toUpperCase() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment