I have this snippet of javascript code:
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();
And I am trying to write the same thing in kotlin.
I can get up to the digest
part and verify the byte arrays are the same:
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
)
The Java equivalent of "BigUInt64" is an unsigned long
. Java's long
is signed , but can be treated as unsigned using the xxxUnsigned()
methods of Long
.
Since you likely don't care about signed vs unsigned, except when printing the value, using long
is fine. If that's not good enough, then you'd need to use BigInteger
.
To read the value from the returned bytes from the digest, use a ByteBuffer
, which is similar to the Node.js Buffer
.
ByteBuffer.wrap(bytes).getLong()
If the JavaScript method name had ended with "LE", you would need to specify that.
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.
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:
crypto
.createHash('sha256')
.update(myString)
.digest()
.readBigUInt64BE();
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.