如何在 JavaScript 中從字串建立雜湊值?


在開始之前,讓我們瞭解一下 JavaScript 中的雜湊值。雜湊值也是一個字串,但它是使用特定演算法加密的。通常,我們將雜湊值用於安全目的。

例如,Google 將使用者的電子郵件和密碼儲存在其資料庫中。現在,Google 的員工可以出於開發目的訪問其資料庫。但是他們可以從資料庫中獲取使用者的電子郵件和密碼嗎?不,因為密碼以雜湊形式儲存,並且要解密密碼,員工需要在從密碼字串建立雜湊值時使用的金鑰。

因此,我們可以透過這種方式將資料轉換為雜湊格式。每當我們需要將原始資料與新資料進行比較時,我們可以使用相同的演算法將新資料轉換為雜湊值,並將其與原始資料的雜湊值進行比較。我們將學習如何在 JavaScript 中從字串建立雜湊值。

建立將字串轉換為雜湊值的演算法

在這種方法中,我們將建立一個自定義函式來從字串生成雜湊值。我們將使用每個字串字元的 ASCII 值,執行一些操作,例如乘法、加法、減法、OR 等,並從中生成雜湊值。

語法

使用者可以按照以下語法從字串生成雜湊值。

for (let character of str) {
   let charCode = character.charCodeAt(0);
   hashString = hashString << 5 – hashString + charCode;
   hashString |= hashString;
}

在上述語法中,hashstring 包含 str 字串的最終雜湊值。

演算法

  • 步驟 1 - 將 hashString 變數初始化為零。

  • 步驟 2 - 使用 for-of 迴圈遍歷字串。

  • 步驟 3 - 在 for-of 迴圈內,獲取每個字元的 ASCII 值。

  • 步驟 4 - 之後,將 hashString 左移 5 位以將其乘以 31,然後從中減去 hashString。

  • 步驟 5 - 將字串字元的 ASCII 值新增到 hashString 變數。

  • 步驟 6 - 對 hashString 變數值執行 OR 操作。

  • 步驟 7 - for 迴圈的所有迭代完成後,我們可以獲得最終的 32 位整數雜湊值。

示例 1

在下面的示例中,我們使用了不同的字串來生成它們的雜湊值。我們建立了 convertToHash() 函式,它以字串作為引數,並實現上述演算法將其轉換為雜湊值。

使用者可以在輸出中觀察表示雜湊值的 32 位整數值。此外,我們可以觀察到它將始終為相同的字串生成相同的雜湊值。

<html>
<body>
   <h2>Creating the <i> custom hash function </i> to convert string to hash</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function convertToHash(str) {
         if (str == "") return 0;
         let hashString = 0;
         for (let character of str) {
            let charCode = character.charCodeAt(0);
            hashString = hashString << 5 - hashString;
            hashString += charCode;
            hashString |= hashString;
         }
         output.innerHTML += "The original string is " + str + "<br/>";
         output.innerHTML += "The hash string related to original string is " + hashString + "<br/>";
         return hashString;
      }
      convertToHash("Hello Users");
      convertToHash("TutorialsPoint");
   </script>
</body>
</html>

示例 2

在下面的示例中,我們實現了上述演算法將字串轉換為雜湊值,但我們使用了 reduce 方法而不是 for 迴圈。我們使用了 split() 方法將字串轉換為字元陣列。

之後,我們使用了 reduce() 方法並將回撥函式作為第一個引數,並將 0 作為第二個引數,表示雜湊變數的初始值。在回撥函式中,我們使用每個字元的 ASCII 值生成雜湊值。

<html>
<body>
   <h2>Using the <i> reduce() method </i> to convert string to hash</h2>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById('output');
      function hashUsingReduce(string) {
         if (string == "") return 0;
         let charArray = string.split('');
         let hash = charArray.reduce((hash, char) => ((hash << 5 - hash) + char.charCodeAt(0)) | hash, 0);
         output.innerHTML += "The original string is " + string + "<br/>";
         output.innerHTML += "The hash string related to original string is " + hash + "<br/>";
         return hash;
      }
      hashUsingReduce("JavaScript");
      hashUsingReduce("TypeScript");
   </script>
</body>
</html>

使用 crypto-js NPM 包

Crpyo-js 是一個 Npm 包,其中包含各種從字串生成雜湊值的方法。它還包含一些解密訊息的演算法。

使用者需要使用以下命令將 crypto-js npm 包安裝到節點專案中。

npm i crypto-js

語法

使用者可以按照以下語法匯入和使用 crypto-js 包進行加密和解密。

var ciphertext = CryptoJS.AES.encrypt('string', 'secret key').toString();

在上述語法中,我們使用了 cryptoJS 包的 AES 模組的 encrypt() 方法。

引數

  • 字串 - 它是要生成雜湊值的字串格式的訊息或資料。

  • 金鑰是一個秘密金鑰,演算法在生成雜湊值時將使用它。金鑰越複雜,生成的加密文字越安全。

示例 3

在下面的示例中,我們在 NodeJs 檔案中匯入了 crypto-js 包。之後,我們訪問了 CryptoJs 的 AES 模組,並使用 encrypt() 方法從字串生成雜湊值。

使用者可以在輸出中觀察使用 AES 演算法生成的雜湊值。

var CryptoJS = require("crypto-js");
// Encrypt
var encryptedText = CryptoJS.AES.encrypt('Your Welcome!', 'This is my Secret').toString();
console.log("The hash string is " + encryptedText);

輸出

"The hash string is U2FsdGVkX19br0LjrHteC9+dlP2PS9dVT03IrTc9zwQ="

本教程向我們介紹了兩種從字串或資料生成雜湊值的方法。第一種方法很簡單,可以在沒有任何金鑰的情況下加密文字。因此,我們不能在實際開發中使用它。

CryptoJs 包包含各種用於各種演算法的模組。我們可以使用任何演算法的加密方法,它也使用加密金鑰。因此,即使任何知道演算法但不知道金鑰的人也無法解密密文。

更新於:2023年2月16日

7K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.