[英]What is the equivalent of readBigUInt64BE in java/kotlin?
I have this snippet of javascript code:我有这段 javascript 代码:
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();
And I am trying to write the same thing in kotlin.我正试图在 kotlin 中写同样的东西。
I can get up to the digest
part and verify the byte arrays are the same:我可以到达
digest
部分并验证字节 arrays 是否相同:
val md = MessageDigest.getInstance("SHA-256")
val inputBytes = input.toByteArray()
val bytes = md.digest(inputBytes)
But I cannot seem to find an equivalent of readBigUInt64BE
in any utility library (like java.security.MessageDigest
)但我似乎无法在任何实用程序库中找到
readBigUInt64BE
的等价物(如java.security.MessageDigest
)
The Java equivalent of "BigUInt64" is an unsigned long
. Java 相当于“BigUInt64”是一个unsigned
long
。 Java's long
is signed , but can be treated as unsigned using the xxxUnsigned()
methods of Long
. Java 的
long
是有符号的,但可以使用Long
的xxxUnsigned()
方法将其视为无符号的。
Since you likely don't care about signed vs unsigned, except when printing the value, using long
is fine.由于您可能不关心有符号与无符号,除非打印值时,使用
long
就可以了。 If that's not good enough, then you'd need to use BigInteger
.如果这还不够好,那么您需要使用
BigInteger
。
To read the value from the returned bytes from the digest, use a ByteBuffer
, which is similar to the Node.js Buffer
.要从摘要返回的字节中读取值,请使用
ByteBuffer
,它类似于 Node.js Buffer
。
ByteBuffer.wrap(bytes).getLong()
If the JavaScript method name had ended with "LE", you would need to specify that.如果 JavaScript 方法名称以“LE”结尾,您需要指定它。
ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getLong()
After much searching, and even trying to copy the implementation of readBigUInt64BE
, here is the solution I came up with which gives me the same result.经过大量搜索,甚至尝试复制
readBigUInt64BE
的实现,这是我想出的解决方案,它给了我相同的结果。
Kotlin: Kotlin:
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 Equivalent:等效于 NodeJS:
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.