简体   繁体   English

如何计算浏览器 JavaScript 中字符串的 SHA hash

[英]How to calculate SHA hash of a string in browser JavaScript

Very new to JavaScript I am.我是 JavaScript 的新手。

What I think I know我认为我知道的

  • There's the CryptoJS module for the frontend.前端有CryptoJS模块。
  • There's a Closure Library by Google.谷歌有一个Closure Library

I tried我试过了

  • Using the CryptoJS module.使用CryptoJS模块。 But I didn't get the hexadecimal hash.但我没有得到十六进制的 hash。
  • Using the closure library according to this doc , this example and from this cdn .根据本文档本示例本 CDN使用闭包库。

But my question is但我的问题是

  • Is there a native crypto library on browser?浏览器上有本地加密库吗?

There is a native browser crypto.有一个本机浏览器加密。

A code example for what you want is:您想要的代码示例是:

const text = 'An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.';

async function digestMessage(message) {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  const hash = await crypto.subtle.digest('SHA-256', data);
  return hash;
}

digestMessage(text)
  .then(digestBuffer => console.log(digestBuffer.byteLength));

The above example is found here which is a good start for in-browser cryptography.上面的例子可以在这里找到,这是浏览器内加密的一个好的开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM