[英]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
是有符號的,但可以使用Long
的xxxUnsigned()
方法將其視為無符號的。
由於您可能不關心有符號與無符號,除非打印值時,使用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.