Skip to content

Instantly share code, notes, and snippets.

@tiqwab
Created January 11, 2019 03:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiqwab/33ddb4dd2d8fb6ac342094df2826ade8 to your computer and use it in GitHub Desktop.
Save tiqwab/33ddb4dd2d8fb6ac342094df2826ade8 to your computer and use it in GitHub Desktop.
MD5 and SHA-256 with Scala
package example
trait HashPerformance {
def hash(str: String): String
def doCheck(count: Int): Unit = {
val key = "something"
val hashed = hash(key)
println(hashed)
val start = System.currentTimeMillis()
1 to count foreach { _ =>
val h = hash(key)
if (h != hashed) {
throw new RuntimeException("hash should be same")
}
}
val end = System.currentTimeMillis()
println(s"finish: ${end - start} millis")
}
}
package example
// ref. https://github.com/apache/commons-codec/blob/trunk/src/main/java/org/apache/commons/codec/binary/Hex.java
object Hex {
private val toDigits: Array[Char] =
Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f')
def encodeHex(data: Array[Byte]): Array[Char] = {
val l = data.length
val out = Array.ofDim[Char](l << 1)
// two characters form the hex value
var j = 0
0 until l foreach { i =>
out(j) = toDigits((0xF0 & data(i)) >>> 4) // '>>>' means right shift with zero-padding
j += 1
out(j) = toDigits(0x0F & data(i))
j += 1
}
out
}
def encodeHexString(data: Array[Byte]): String = new String(encodeHex(data))
}
package example
import java.security.MessageDigest
import scala.util.Try
// ref. https://github.com/apache/commons-codec/blob/trunk/src/main/java/org/apache/commons/codec/digest/DigestUtils.java
object Md5Performance extends HashPerformance {
override def hash(str: String): String = {
val md5 = MessageDigest.getInstance("MD5")
Hex.encodeHexString(md5.digest(str.getBytes("UTF-8")))
}
def main(args: Array[String]): Unit = {
val count = Try(args(0).toInt).toOption.getOrElse {
println("illegal argument. assume count is 100.")
100
}
println(s"count is $count")
doCheck(count)
}
}
package example
import java.security.MessageDigest
import scala.util.Try
// ref. https://github.com/apache/commons-codec/blob/trunk/src/main/java/org/apache/commons/codec/digest/DigestUtils.java
object Sha256Performance extends HashPerformance {
override def hash(str: String): String = {
val sha256 = MessageDigest.getInstance("SHA-256")
Hex.encodeHexString(sha256.digest(str.getBytes("UTF-8")))
}
def main(args: Array[String]): Unit = {
val count = Try(args(0).toInt).toOption.getOrElse {
println("illegal argument. assume count is 100.")
100
}
println(s"count is $count")
doCheck(count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment