簡體   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