How to correctly generate SHA-256 checksum for a string in scala?

An Illusion picture An Illusion · Sep 20, 2017 · Viewed 11.3k times · Source

I need to generate an SHA-256 checksum from a string that will be sent as a get param.

If found this link to generate the checksum.

Genrating the checksum like so:

  val digest = MessageDigest.getInstance("SHA-256");      
  private def getCheckSum() = {
    println(new String(digest.digest(("Some String").getBytes(StandardCharsets.UTF_8))))        
  }

prints checksum similar to this:

*║┼¼┬]9AòdJb:#↓o6↓T╞B5C♀¼O~╟╙àÿG

The API that we need to send this to says the checksum should look like this:

45e00158bc8454049b7208e76670466d49a5dfb2db4196

What am I doing wrong?

Please advise. Thanks.

Answer

Dima picture Dima · Sep 20, 2017

Equivalent, but a bit more efficient:

MessageDigest.getInstance("SHA-256")
  .digest("some string".getBytes("UTF-8"))
  .map("%02x".format(_)).mkString