简体   繁体   中英

SHA1 hexadecimal encoding in scala

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM