问题描述
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();
我正在尝试在 kotlin 中编写相同的内容。
我可以到达 digest
部分并验证字节数组是否相同:
val md = MessageDigest.getInstance("SHA-256")
val inputBytes = input.toByteArray()
val bytes = md.digest(inputBytes)
但我似乎无法在任何实用程序库(如 readBigUInt64BE
)中找到等效的 java.security.MessageDigest
解决方法
“BigUInt64”的 Java 等价物是 未签名 long
。 Java 的 long
是 signed,但可以使用 Long
的 xxxUnsigned()
方法将其视为 unsigned。
因为您可能不关心有符号和无符号,除非打印值,所以使用 long
很好。如果这还不够好,那么您需要使用 BigInteger
。
要从摘要返回的字节中读取值,请使用 ByteBuffer
,它类似于 Node.js Buffer
。
ByteBuffer.wrap(bytes).getLong()
如果 JavaScript 方法名称以“LE”结尾,则需要指定。
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getLong()
,
经过多次搜索,甚至尝试复制 readBigUInt64BE
的实现,这是我想出的解决方案,它给了我相同的结果。
科特林:
private fun getHashedValue(input: String): BigInteger {
val md = MessageDigest.getInstance("SHA-256")
val inputBytes = input.toByteArray()
val bytes = md.digest(inputBytes)
if (bytes.size < 8) { // Not sure if this case works,but I haven't hit it yet
return BigInteger(1,bytes)
}
return BigInteger(1,bytes.sliceArray(0..7))
}
NodeJS 等价物:
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();