【发布时间】:2021-09-29 06:47:47
【问题描述】:
我需要重现一个 JS 函数,该函数在 r 中使用 SHA-256 对字符串进行哈希处理。
上述功能是:
function hashPhrase (phrase) {
const buf = new ArrayBuffer(phrase.length * 2)
const bufView = new Uint16Array(buf)
const strLen = phrase.length
for (let i = 0; i < strLen; i++) {
bufView[i] = phrase.charCodeAt(i)
}
return window.crypto.subtle.digest('SHA-256', buf)
.then(hashArrayBuffer => {
let binary = ''
const bytes = new Uint8Array(hashArrayBuffer)
const len = bytes.byteLength
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i])
}
return Promise.resolve(window.btoa(binary))
})
}
调用函数:
hashPhrase('test').then(x => { console.log(x) })
给我:
/lIGdrGh2T2rqyMZ7qA2dPNjLq7rFj0eiCRPXrHeEOs=
作为输出。
我加载 openssl 并尝试使用 sha256 作为函数来散列字符串。
library(openssl)
phrase = "test"
phraseraw = charToRaw(phrase)
base64_encode(sha256(phraseraw))
输出是:
[1] "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg="
不知道问题是否出在 uint16 上,因为在这两种情况下,我都猜想变量是作为原始参数传递的。
我将非常感谢任何帮助。
【问题讨论】: