Window:crypto 属性

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Window 接口的 crypto 只读属性返回当前窗口的作用域的 Crypto 对象。此对象允许网页访问某些加密相关的服务。

虽然该属性自身是只读的,但它的所有方法(以及其子对象 SubtleCrypto 的方法)不仅是只读的,因此容易受到 polyfill 的攻击。

虽然 crypto 在所有窗口上均可用,但其返回的 Crypto 对象在不安全的上下文中仅有一个可用的特性:getRandomValues() 方法。通常,你应该仅在安全上下文中使用此 API。

Crypto 接口的实例,提供对通用的密码学功能和强随机数生成器的访问。

示例

使用 crypto 属性来访问 getRandomValues() 方法。

JavaScript

js
globalThis.genRandomNumbers = () => {
  const array = new Uint32Array(10);
  globalThis.crypto.getRandomValues(array);

  const randText = document.getElementById("myRandText");
  randText.textContent = `随机数为:${array.join(" ")}`;
};

HTML

html
<p id="myRandText">随机数为:</p>
<button type="button" onClick="genRandomNumbers()">生成 10 个随机数</button>

结果

规范

Specification
Web Cryptography API
# dom-windoworworkerglobalscope-crypto

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
crypto
Available in workers

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Uses a non-standard name.
Has more compatibility info.

参见