1

I need to convert string to SHA1 hexadecimal hash below is the code I am using:

val md = java.security.MessageDigest.getInstance("SHA-1")
val ha = new sun.misc.HexDumpEncoder().encode(md.digest("Foo".getBytes))
print(ha)

but i donot get hexadecimal value, I can achive this in python using below piece of code:

int(hashlib.sha1("Foo".encode(encoding='UTF-8', errors='strict')).hexdigest(), 16)

what is the relevent hexdigest() of python in scala

toofrellik
  • 1,277
  • 4
  • 15
  • 39

1 Answers1

3

Basically any java way to convert byte array to string will do the job.

Here is a thread discussing different options to convert byte array to hex string.

You can try this way.

import javax.xml.bind.DatatypeConverter
val md = java.security.MessageDigest.getInstance("SHA-1")
val ha = DatatypeConverter.printHexBinary(md.digest("Foo".getBytes))
print(ha)

In order to create integer from the string you will have to use BigInteger, because Int and Long will overflow.

val i = new BigInteger(ha, 16)
// this will overflow for this input
val i2 = Integer.parseInt(ha, 16)
import java.lang.{ Long => JLong }
val l = JLong.parseLong(ha, 16)
vbuhlev
  • 509
  • 2
  • 10