Skip to content

Instantly share code, notes, and snippets.

@downthecrop
Created August 11, 2020 05:07
Show Gist options
  • Save downthecrop/10d0e8415a37dfddbe0f9d6be32dc3ba to your computer and use it in GitHub Desktop.
Save downthecrop/10d0e8415a37dfddbe0f9d6be32dc3ba to your computer and use it in GitHub Desktop.
kotlin md5 to hex
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