繁体   English   中英

java/kotlin 中 readBigUInt64BE 的等价物是什么?

[英]What is the equivalent of readBigUInt64BE in java/kotlin?

我有这段 javascript 代码:

crypto
    .createHash('sha256')
    .update(myString)
    .digest()
    .readBigUInt64BE();

我正试图在 kotlin 中写同样的东西。

我可以到达digest部分并验证字节 arrays 是否相同:

val md = MessageDigest.getInstance("SHA-256")
val inputBytes = input.toByteArray()
val bytes = md.digest(inputBytes)

但我似乎无法在任何实用程序库中找到readBigUInt64BE的等价物(如java.security.MessageDigest

Java 相当于“BigUInt64”是一个unsigned long Java 的long是有符号的,但可以使用LongxxxUnsigned()方法将其视为无符号的。

由于您可能不关心有符号与无符号,除非打印值时,使用long就可以了。 如果这还不够好,那么您需要使用BigInteger

要从摘要返回的字节中读取值,请使用ByteBuffer ,它类似于 Node.js Buffer

ByteBuffer.wrap(bytes).getLong()

如果 JavaScript 方法名称以“LE”结尾,您需要指定它。

ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getLong()

经过大量搜索,甚至尝试复制readBigUInt64BE的实现,这是我想出的解决方案,它给了我相同的结果。

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:

crypto
    .createHash('sha256')
    .update(myString)
    .digest()
    .readBigUInt64BE();

暂无
暂无

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

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