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.

We’d love to hear your thoughts on the next set of proposals for the JavaScript language. You can find a description of the proposals here.
Please take two minutes to fill out our short survey.

cryptoWindow インターフェイスの読み取り専用プロパティで、グローバルオブジェクトに関連付けられた Crypto オブジェクトを返します。このオブジェクトは、ウェブページが暗号に関連したサービスにアクセスできるようにします。

このプロパティ自体は読み取り専用ですが、そのメソッドすべて(加えて子オブジェクトのメソッドと SubtleCrypto)は読み取り専用ではありません。そのためポリフィルによる攻撃には脆弱です。

crypto はすべてのウィンドウで使用できますが、返される Crypto オブジェクトは保護されていないコンテキストで使用できる機能は 1 つしかありません。 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

ブラウザーの互換性

関連情報