SubtleCrypto.generateKey() - Web APIs 编辑

Secure context

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Use the generateKey() method of the SubtleCrypto interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).

Syntax

const result = crypto.subtle.generateKey(algorithm, extractable, keyUsages);

Parameters

Return value

Exceptions

The promise is rejected when the following exception is encountered:

SyntaxError
Raised when the result is a CryptoKey of type secret or private but keyUsages is empty.
SyntaxError
Raised when the result is a CryptoKeyPair and its privateKey.usages attribute is empty.

Examples

Note: You can try the working examples on GitHub.

RSA key pair generation

This code generates an RSA-OAEP encryption key pair. See the complete code on GitHub.

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

Elliptic curve key pair generation

This code generates an ECDSA signing key pair. See the complete code on GitHub.

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

HMAC key generation

This code generates an HMAC signing key. See the complete code on GitHub.

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

AES key generation

This code generates an AES-GCM encryption key. See the complete code on GitHub.

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

Specifications

SpecificationStatusComment
Web Cryptography API
The definition of 'SubtleCrypto.generateKey()' in that specification.
RecommendationInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:92 次

字数:8995

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文