Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

sha

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.

like image 627
An Illusion Avatar asked Sep 20 '17 19:09

An Illusion


2 Answers

Equivalent, but a bit more efficient:

MessageDigest.getInstance("SHA-256")
  .digest("some string".getBytes("UTF-8"))
  .map("%02x".format(_)).mkString
like image 131
Dima Avatar answered Nov 14 '22 01:11

Dima


java.security.MessageDigest#digest gives a byte array.

scala> import java.security.MessageDigest
scala> import java.math.BigInteger

scala> MessageDigest.getInstance("SHA-256").digest("some string".getBytes("UTF-8"))
res1: Array[Byte] = Array(97, -48, 52, 71, 49, 2, -41, -38, -61, 5, -112, 39, 112, 71, 31, -43, 15, 76, 91, 38, -10, -125, 26, 86, -35, -112, -75, 24, 75, 60, 48, -4)

To create the hex, use String.format,

scala> val hash = String.format("%032x", new BigInteger(1, MessageDigest.getInstance("SHA-256").digest("some string".getBytes("UTF-8"))))
hash: String = 61d034473102d7dac305902770471fd50f4c5b26f6831a56dd90b5184b3c30fc

You can verify hash with command line tool in linux, unix

$ echo -n "some string" | openssl dgst -sha256
61d034473102d7dac305902770471fd50f4c5b26f6831a56dd90b5184b3c30fc

NOTE:

In case java returns hash of length lesser than 64 chars you can left pad with 0. (eg. 39)

def hash64(data: String) = {
  val hash = String.format(
               "%032x", 
               new BigInteger(1, MessageDigest.getInstance("SHA-256").digest(data.getBytes("UTF-8")))
             )
  val hash64 = hash.reverse.padTo(64, "0").reverse.mkString 
  hash64      
}
like image 12
prayagupa Avatar answered Nov 14 '22 00:11

prayagupa