簡體   English   中英

如何在 JS 中 hash 使用 SHA256 的字符串?

[英]How can I hash a string with SHA256 in JS?

描述

我正在尋找 hash 在 Javascript 中使用 SHA256 的本地字符串。 我一直在環顧四周,認為會有某種官方圖書館或 function,但我發現的只是大量不同的項目,每個項目都有不同的腳本,我不太確定要信任的腳本(因為我不是專家,絕對沒有資格評估它們)或如何實施它們。 編輯:我需要文本中的 output,而不是十六進制,抱歉,如果我在發布原始問題時沒有解釋這一點。

代碼

這是我到目前為止所嘗試的:

async function sha256(message) {
  // encode as UTF-8
  const msgBuffer = new TextEncoder('utf-8').encode(message);

  // hash the message
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

  // convert ArrayBuffer to Array
  const hashArray = Array.from(new Uint8Array(hashBuffer));

  // convert bytes to hex string
  const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
  console.log(hashHex);
  return hashHex;
}
sha256(passwordInput); 

控制台 Output:

未捕獲(承諾中)類型錯誤:無法讀取未定義的屬性“摘要”

我是 javascript 的新手,我願意接受所有建議,所以是的。

更新

盡管您的大多數建議都有效,但對於那些希望使用 Web Crypto API 的人來說,答案在第 5 行。 我需要將crypto.subtle.digest更改為window.crypto.subtle.digest

你好:D 這是一個很好的功能。 如果你是學者,你想看看這篇文章: https : //www.movable-type.co.uk/scripts/sha256.html

純 javascript,不需要依賴:

var sha256 = function sha256(ascii) {
    function rightRotate(value, amount) {
        return (value>>>amount) | (value<<(32 - amount));
    };
    
    var mathPow = Math.pow;
    var maxWord = mathPow(2, 32);
    var lengthProperty = 'length'
    var i, j; // Used as a counter across the whole file
    var result = ''

    var words = [];
    var asciiBitLength = ascii[lengthProperty]*8;
    
    //* caching results is optional - remove/add slash from front of this line to toggle
    // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
    // (we actually calculate the first 64, but extra values are just ignored)
    var hash = sha256.h = sha256.h || [];
    // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
    var k = sha256.k = sha256.k || [];
    var primeCounter = k[lengthProperty];
    /*/
    var hash = [], k = [];
    var primeCounter = 0;
    //*/

    var isComposite = {};
    for (var candidate = 2; primeCounter < 64; candidate++) {
        if (!isComposite[candidate]) {
            for (i = 0; i < 313; i += candidate) {
                isComposite[i] = candidate;
            }
            hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
            k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
        }
    }
    
    ascii += '\x80' // Append Ƈ' bit (plus zero padding)
    while (ascii[lengthProperty]%64 - 56) ascii += '\x00' // More zero padding
    for (i = 0; i < ascii[lengthProperty]; i++) {
        j = ascii.charCodeAt(i);
        if (j>>8) return; // ASCII check: only accept characters in range 0-255
        words[i>>2] |= j << ((3 - i)%4)*8;
    }
    words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0);
    words[words[lengthProperty]] = (asciiBitLength)
    
    // process each chunk
    for (j = 0; j < words[lengthProperty];) {
        var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
        var oldHash = hash;
        // This is now the undefinedworking hash", often labelled as variables a...g
        // (we have to truncate as well, otherwise extra entries at the end accumulate
        hash = hash.slice(0, 8);
        
        for (i = 0; i < 64; i++) {
            var i2 = i + j;
            // Expand the message into 64 words
            // Used below if 
            var w15 = w[i - 15], w2 = w[i - 2];

            // Iterate
            var a = hash[0], e = hash[4];
            var temp1 = hash[7]
                + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
                + ((e&hash[5])^((~e)&hash[6])) // ch
                + k[i]
                // Expand the message schedule if needed
                + (w[i] = (i < 16) ? w[i] : (
                        w[i - 16]
                        + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0
                        + w[i - 7]
                        + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1
                    )|0
                );
            // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
            var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
                + ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj
            
            hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
            hash[4] = (hash[4] + temp1)|0;
        }
        
        for (i = 0; i < 8; i++) {
            hash[i] = (hash[i] + oldHash[i])|0;
        }
    }
    
    for (i = 0; i < 8; i++) {
        for (j = 3; j + 1; j--) {
            var b = (hash[i]>>(j*8))&255;
            result += ((b < 16) ? 0 : '') + b.toString(16);
        }
    }
    return result;
};

來源: https : //geraintluff.github.io/sha256/

簽出這個: https : //github.com/brix/crypto-js

您可以使用以下內容:

require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256)
{
    console.log(SHA256("Message")); 
});

或不需要:

<script type="text/javascript" src="path-to/bower_components/crypto-js/crypto-js.js"></script>
<script type="text/javascript">
    var encrypted = CryptoJS.AES(...);
    var encrypted = CryptoJS.SHA256(...);
</script>

正如您在問題中提到的,您不需要自定義 Crypto 實現來執行此操作。

當前所有瀏覽器都支持 WebCrypto 使用window.crypto.subtle.digest生成 SHA 256 哈希。

const digest = await window.crypto.subtle.digest('SHA-256', data);

如果你想要一些異步的東西,例如sha.js每月有 1280 萬次下載,並且正在積極維護。

const digest = shajs('sha256').update(data).digest('hex')

Cannot read property 'digest' of undefined打電話時crypto.subtle.digest意味着subtle不內可用的crypto ; 因此, digest不可能存在,因為它的包含模塊不存在。
從邏輯上講, crypto.subtle不能在這個范圍內使用,事實上,在安全上下文之外的任何地方的瀏覽器中都是如此

什么時候上下文被認為是安全的? developer.mozilla.org

當上下文安全地(或本地)交付時,並且當它不能用於向不安全的上下文提供對安全 API 的訪問時,上下文將被認為是安全的。 實際上,這意味着要使頁面具有安全上下文,它及其父鏈和開啟器鏈上的所有頁面必須已安全傳送。

例如,通過 TLS 安全交付的頁面如果其父文檔或祖先文檔未安全交付,則不被視為安全上下文; 否則,頁面將能夠通過postMessage消息將敏感 API 公開給非安全交付的祖先。 類似地,如果一個 TLS 傳遞的文檔被一個不安全的上下文在一個新窗口中打開,而沒有指定noopener ,那么打開的窗口不被認為是一個安全的上下文(因為 opener 和打開的窗口可以通過 postMessage 進行通信)。

本地交付的文件(例如 http://localhost* 和file://路徑)被視為已安全交付。

| | | | |上下文不在本地,必須通過https://WSS://和其中使用的協議不應被視為過時。

在安全的上下文中,您的代碼完美運行 😄


1:安全上下文 - 網絡安全 | MDN
2:什么時候上下文被認為是安全的? - 安全上下文 - 網絡安全 | MDN
3: Window.postMessage() - Web APIs | MDN
4:窗口功能特性 - Window.open() - Web APIs | MDN

代碼沒問題。 最后一行應該是這樣的:

var vDigest = await sha256(passwordInput);

上面來自 ofundefined 的答案有一堆缺少的分號和錯誤。 我已經清理了代碼,以便您可以將其作為函數調用。 我不確定這是否適用於 unicode 字符。 可能必須將 unicode 轉換為正常的 ascii 才能工作。 但是,正如鏈接文章所說......這不應該在生產環境中使用。 此外,此代碼的原始版本似乎確實支持 unicode,因此使用它可能比使用此功能更好。

上面的文章(似乎支持 unicode)顯示了這個功能,它與下面發布的功能不同......

https://www.movable-type.co.uk/scripts/sha256.html

如何使用

console.log(sha256('Perry Computer Services'));

輸出

89bae4aeb761e42cb71ba6b62305e0980154cf21992c9ab2ab6fc40966ab5bf3

用 PHP 哈希測試 - 輸出

89bae4aeb761e42cb71ba6b62305e0980154cf21992c9ab2ab6fc40966ab5bf3

這不是上面另一個鏈接頁面上顯示的完整功能。 正如您從上面的示例中看到的那樣,它確實可以“按原樣”使用非 unicode 字符。

function sha256(ascii) {
    function rightRotate(value, amount) {
        return (value >>> amount) | (value << (32 - amount));
    }
    ;

    var mathPow = Math.pow;
    var maxWord = mathPow(2, 32);
    var lengthProperty = 'length';
    var i, j; // Used as a counter across the whole file
    var result = '';

    var words = [];
    var asciiBitLength = ascii[lengthProperty] * 8;

    //* caching results is optional - remove/add slash from front of this line to toggle
    // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
    // (we actually calculate the first 64, but extra values are just ignored)
    var hash = sha256.h = sha256.h || [];
    // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
    var k = sha256.k = sha256.k || [];
    var primeCounter = k[lengthProperty];
    /*/
     var hash = [], k = [];
     var primeCounter = 0;
     //*/

    var isComposite = {};
    for (var candidate = 2; primeCounter < 64; candidate++) {
        if (!isComposite[candidate]) {
            for (i = 0; i < 313; i += candidate) {
                isComposite[i] = candidate;
            }
            hash[primeCounter] = (mathPow(candidate, .5) * maxWord) | 0;
            k[primeCounter++] = (mathPow(candidate, 1 / 3) * maxWord) | 0;
        }
    }

    ascii += '\x80'; // Append Ƈ' bit (plus zero padding)
    while (ascii[lengthProperty] % 64 - 56)
        ascii += '\x00'; // More zero padding

    for (i = 0; i < ascii[lengthProperty]; i++) {
        j = ascii.charCodeAt(i);
        if (j >> 8)
            return; // ASCII check: only accept characters in range 0-255
        words[i >> 2] |= j << ((3 - i) % 4) * 8;
    }
    words[words[lengthProperty]] = ((asciiBitLength / maxWord) | 0);
    words[words[lengthProperty]] = (asciiBitLength);

    // process each chunk
    for (j = 0; j < words[lengthProperty]; ) {
        var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
        var oldHash = hash;
        // This is now the undefinedworking hash", often labelled as variables a...g
        // (we have to truncate as well, otherwise extra entries at the end accumulate
        hash = hash.slice(0, 8);

        for (i = 0; i < 64; i++) {
            var i2 = i + j;
            // Expand the message into 64 words
            // Used below if 
            var w15 = w[i - 15], w2 = w[i - 2];

            // Iterate
            var a = hash[0], e = hash[4];
            var temp1 = hash[7]
                    + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
                    + ((e & hash[5]) ^ ((~e) & hash[6])) // ch
                    + k[i]
                    // Expand the message schedule if needed
                    + (w[i] = (i < 16) ? w[i] : (
                            w[i - 16]
                            + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15 >>> 3)) // s0
                            + w[i - 7]
                            + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2 >>> 10)) // s1
                            ) | 0
                            );
            // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
            var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
                    + ((a & hash[1]) ^ (a & hash[2]) ^ (hash[1] & hash[2])); // maj

            hash = [(temp1 + temp2) | 0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
            hash[4] = (hash[4] + temp1) | 0;
        }

        for (i = 0; i < 8; i++) {
            hash[i] = (hash[i] + oldHash[i]) | 0;
        }
    }

    for (i = 0; i < 8; i++) {
        for (j = 3; j + 1; j--) {
            var b = (hash[i] >> (j * 8)) & 255;
            result += ((b < 16) ? 0 : '') + b.toString(16);
        }
    }
    return result;
};

純javascript,不需要依賴

您可以使用SubtleCrypto.digest()來幫助您。

它需要一個Uint8Array

如果您的數據是 Blob

const blob = new Blob([file])
const arrayBuffer = await blob.arrayBuffer()
const uint8Array = new Uint8Array(arrayBuffer)
SubtleCrypto.digest("SHA-256", uint8Array)

如果數據是字符串,使用TextEncoder.encode()轉換為 Uint8Array

const uint8Array = new TextEncoder().encode(data)
SubtleCrypto.digest("SHA-256", uint8Array)

下面是一個可運行的示例供您參考。

 <input type="file" multiple/> <input placeholder="Press `Enter` when done."/> <script> /** * @param {"SHA-1"|"SHA-256"|"SHA-384"|"SHA-512"} algorithm https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest * @param {string|Blob} data */ async function getHash(algorithm, data) { const main = async (msgUint8) => { // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest#converting_a_digest_to_a_hex_string const hashBuffer = await crypto.subtle.digest(algorithm, msgUint8) const hashArray = Array.from(new Uint8Array(hashBuffer)) return hashArray.map(b => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string } if (data instanceof Blob) { const arrayBuffer = await data.arrayBuffer() const msgUint8 = new Uint8Array(arrayBuffer) return await main(msgUint8) } const encoder = new TextEncoder() const msgUint8 = encoder.encode(data) return await main(msgUint8) } const inputFile = document.querySelector(`input[type="file"]`) const inputText = document.querySelector(`input[placeholder^="Press"]`) inputFile.onchange = async (event) => { for (const file of event.target.files) { console.log(file.name, file.type, file.size + "bytes") const hashHex = await getHash("SHA-256", new Blob([file])) console.log(hashHex) } } inputText.onkeyup = async (keyboardEvent) => { if (keyboardEvent.key === "Enter") { const hashHex = await getHash("SHA-256", keyboardEvent.target.value) console.log(hashHex) } } </script>

另請參閱如何在瀏覽器 JavaScript 中計算字符串的 SHA hash

您可以使用 CDN 庫。

https://cdnjs.com/libraries/crypto-js

請在您的 html 中引用以下腳本標簽:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js" integrity="sha512-E8QSvWZ0eCLGk4km3hxSsNmGWbLtSCSUcewDQPQWZF6pEU8GlT8a5fF32wOl1i8ftdMhssTrF/OhyGWwonTcXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

關於如何使用庫中的方法,請參考以下網站:

https://cryptojs.gitbook.io/docs/

以下頁面顯示了我的建議來自的示例:

https://codepen.io/omararcus/pen/QWwBdmo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM