SubtleCrypto: generateKey() 方法

Baseline 广泛可用 *

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

* 此特性的某些部分可能存在不同级别的支持。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

注意:此功能在 Web Workers 中可用。

SubtleCrypto 接口的 generateKey() 方法用于生成一个新的密钥(用于对称算法)或密钥对(用于公钥算法)。

语法

js
generateKey(algorithm, extractable, keyUsages)

参数

algorithm

一个定义要生成的密钥类型并提供额外的算法特定参数的对象。

extractable

一个布尔值,指示是否可以使用 SubtleCrypto.exportKey()SubtleCrypto.wrapKey() 导出密钥。

keyUsages

一个 Array,其中包含指示新生成的密钥可以执行的操作的字符串。数组元素的可能值为

encrypt

密钥可用于 加密消息。

decrypt

密钥可用于 解密消息。

符号

密钥可用于 签名消息。

verify

密钥可用于 验证签名。

deriveKey

密钥可用于 派生新密钥

deriveBits

密钥可用于 派生位

wrapKey

密钥可用于 包装密钥

unwrapKey

密钥可用于 解包装密钥

返回值

一个 Promise,它将以 CryptoKey(用于对称算法)或 CryptoKeyPair(用于公钥算法)进行解析。

异常

当遇到以下异常时,Promise 将被拒绝

SyntaxError DOMException

当结果是类型为 secretprivateCryptoKey,但 keyUsages 为空或对于算法类型无效时,将抛出此异常。

SyntaxError DOMException

当结果是 CryptoKeyPair 且其 privateKey.usages 属性为空或对于算法类型无效时,将抛出此异常。

示例

注意:您可以在 GitHub 上 尝试工作示例

RSA 密钥对生成

此代码生成一个 RSA-OAEP 加密密钥对。 在 GitHub 上查看完整代码。

js
let keyPair = await window.crypto.subtle.generateKey(
  {
    name: "RSA-OAEP",
    modulusLength: 4096,
    publicExponent: new Uint8Array([1, 0, 1]),
    hash: "SHA-256",
  },
  true,
  ["encrypt", "decrypt"],
);

椭圆曲线密钥对生成

此代码生成一个 ECDSA 签名密钥对。 在 GitHub 上查看完整代码。

js
let keyPair = await window.crypto.subtle.generateKey(
  {
    name: "ECDSA",
    namedCurve: "P-384",
  },
  true,
  ["sign", "verify"],
);

HMAC 密钥生成

此代码生成一个 HMAC 签名密钥。 在 GitHub 上查看完整代码。

js
let key = await window.crypto.subtle.generateKey(
  {
    name: "HMAC",
    hash: { name: "SHA-512" },
  },
  true,
  ["sign", "verify"],
);

AES 密钥生成

此代码生成一个 AES-GCM 加密密钥。 在 GitHub 上查看完整代码。

js
let key = await window.crypto.subtle.generateKey(
  {
    name: "AES-GCM",
    length: 256,
  },
  true,
  ["encrypt", "decrypt"],
);

Ed25519 密钥生成

此代码生成一个 Ed25519 签名密钥对。它源自 GitHub 上的此源代码,您可以在 此处实时运行

JavaScript

下面显示了使用 Ed25519 算法生成密钥对并记录每个密钥信息的代码。请注意,代码运行在 try..catch 块中,因为并非所有浏览器都支持此算法。

JavaScript 首先获取 #sign-button#message <input> 元素,然后为按钮的 click 事件添加一个监听器。事件处理程序会清除日志并执行其他操作,传递 <input> 元素的内容。

js
const button = document.querySelector("#run-button");
const input = document.querySelector("#log");

button.addEventListener("click", () => {
  // Clear log
  logElement.innerText = "";
  logElement.scrollTop = logElement.scrollHeight;
  // Run test
  test();
});

async function test() {
  try {
    // Create a key pair and use destructuring assignment to assign to variables
    const { publicKey, privateKey } = await crypto.subtle.generateKey(
      {
        name: "Ed25519",
      },
      true,
      ["sign", "verify"],
    );

    // Log the properties of the keys
    log(`publicKey: ${publicKey}`);
    log(` type: ${publicKey.type}`);
    log(` extractable: ${publicKey.extractable}`);
    log(` algorithm: ${JSON.stringify(publicKey.algorithm)}`);
    log(` usages: ${publicKey.usages}`);
    log(`privateKey: ${privateKey}`);
    log(` type: ${privateKey.type}`);
    log(` extractable: ${privateKey.extractable}`);
    log(` algorithm: ${JSON.stringify(privateKey.algorithm)}`);
    log(` usages: ${privateKey.usages}`);
  } catch (error) {
    log(error);
  }
}

结果

有关创建的密钥的信息将记录在下方(如果浏览器不允许创建密钥,则显示错误字符串)。

X25519 密钥生成

此代码生成一个 X25519 公钥和私钥对,可用于 SubtleCrypto.deriveKey() 创建共享密钥,或用于 SubtleCrypto.deriveBits() 创建共享密钥。

JavaScript

下面显示了使用 X25519 算法生成密钥对并记录每个密钥信息的代码。请注意,代码运行在 try..catch 块中,因为并非所有浏览器都支持此算法。

JavaScript 首先获取 #run-button#log <input> 元素,然后为按钮的 click 事件添加一个监听器。事件处理程序会清除日志,生成一个 X25519 密钥对,并记录其一些属性。

js
const button = document.querySelector("#run-button");
const input = document.querySelector("#log");

button.addEventListener("click", () => {
  // Clear log
  logElement.innerText = "";
  logElement.scrollTop = logElement.scrollHeight;
  // Run test
  test();
});

async function test() {
  try {
    // Create a key pair and use destructuring assignment to assign to variables
    const { publicKey, privateKey } = await crypto.subtle.generateKey(
      {
        name: "X25519",
      },
      true,
      ["deriveKey", "deriveBits"],
    );

    // Log the properties of the keys
    log(`publicKey: ${publicKey}`);
    log(` type: ${publicKey.type}`);
    log(` extractable: ${publicKey.extractable}`);
    log(` algorithm: ${JSON.stringify(publicKey.algorithm)}`);
    log(` usages: ${publicKey.usages}`);
    log(`privateKey: ${privateKey}`);
    log(` type: ${privateKey.type}`);
    log(` extractable: ${privateKey.extractable}`);
    log(` algorithm: ${JSON.stringify(privateKey.algorithm)}`);
    log(` usages: ${privateKey.usages}`);
  } catch (error) {
    log(error);
  }
}

结果

有关创建的密钥的信息将记录在下方(如果浏览器不允许创建密钥,则显示错误字符串)。

规范

规范
Web 加密级别 2
# SubtleCrypto-method-generateKey

浏览器兼容性

另见