简体   繁体   English

Scala中的SHA1十六进制编码

[英]SHA1 hexadecimal encoding in scala

I need to convert string to SHA1 hexadecimal hash below is the code I am using: 我需要将字符串转换为SHA1十六进制哈希,下面是我正在使用的代码:

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: 但是我没有得到十六进制值,我可以使用下面的代码在python中实现:

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

what is the relevent hexdigest() of python in scala Scala中python的relevent hexdigest()是什么

Basically any java way to convert byte array to string will do the job. 基本上,任何将字节数组转换为字符串的java方法都可以完成这项工作。

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. 为了从字符串创建整数,您将必须使用BigInteger,因为Int和Long将溢出。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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