Generate a Hash from string in Javascript

前端 未结 22 975
不知归路
不知归路 2020-11-22 03:34

I need to convert strings to some form of hash. Is this possible in JavaScript?

I\'m not utilizing a server-side language so I can\'t do it that way.

22条回答
  •  粉色の甜心
    2020-11-22 04:11

    I'm a bit surprised nobody has talked about the new SubtleCrypto API yet.

    To get an hash from a string, you can use the subtle.digest method :

    function getHash(str, algo = "SHA-256") {
      let strBuf = new TextEncoder('utf-8').encode(str);
      return crypto.subtle.digest(algo, strBuf)
        .then(hash => {
          window.hash = hash;
          // here hash is an arrayBuffer, 
          // so we'll connvert it to its hex version
          let result = '';
          const view = new DataView(hash);
          for (let i = 0; i < hash.byteLength; i += 4) {
            result += ('00000000' + view.getUint32(i).toString(16)).slice(-8);
          }
          return result;
        });
    }
    
    getHash('hello world')
      .then(hash => {
        console.log(hash);
      });

提交回复
热议问题