安全上下文
此特征只可用于 安全上下文 (HTTPS),在某些或所有 支持浏览器 .

deriveBits() 方法在 SubtleCrypto interface can be used to derive an array of bits from a base key.

It takes as its arguments the base key, the derivation algorithm to use, and the length of the bit string to derive. It returns a Promise which will be fulfilled with an ArrayBuffer containing the derived bits.

This method is very similar to SubtleCrypto.deriveKey() ,除了 deriveKey() 返回 CryptoKey object rather than an ArrayBuffer . Essentially deriveKey() is composed of deriveBits() followed by importKey() .

This function supports the same derivation algorithms as deriveKey() : ECDH, HKDF, and PBKDF2. See Supported algorithms for some more detail on these algorithms.

句法

const result = crypto.subtle.deriveBits(
    algorithm,
    baseKey,
    length
);
					

参数

返回值

异常

The promise is rejected when one of the following exceptions are encountered:

InvalidAccessError
Raised when the base key is not a key for the requested derivation algorithm or if the CryptoKey.usages value of that key doesn't contain deriveKey .
NotSupported

Raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length.

Supported algorithms

Supported algorithms section of the deriveKey() 文档编制 .

范例

注意 : You can try the working examples on GitHub.

ECDH

In this example Alice and Bob each generate an ECDH key pair.

We then use Alice's private key and Bob's public key to derive a shared secret. See the complete code on GitHub.

async function deriveSharedSecret(privateKey, publicKey) {
  const sharedSecret = await window.crypto.subtle.deriveBits(
    {
      name: "ECDH",
      namedCurve: "P-384",
      public: publicKey
    },
    privateKey,
    128
  );
  const buffer = new Uint8Array(sharedSecret, 0, 5);
  const sharedSecretValue = document.querySelector(".ecdh .derived-bits-value");
  sharedSecretValue.classList.add("fade-in");
  sharedSecretValue.addEventListener("animationend", () => {
    sharedSecretValue.classList.remove("fade-in");
  });
  sharedSecretValue.textContent = `${buffer}...[${sharedSecret.byteLength} bytes total]`;
}
// Generate 2 ECDH key pairs: one for Alice and one for Bob
// In more normal usage, they would generate their key pairs
// separately and exchange public keys securely
const generateAlicesKeyPair = window.crypto.subtle.generateKey(
  {
    name: "ECDH",
    namedCurve: "P-384"
  },
  false,
  ["deriveBits"]
);
const generateBobsKeyPair = window.crypto.subtle.generateKey(
  {
    name: "ECDH",
    namedCurve: "P-384"
  },
  false,
  ["deriveBits"]
);
Promise.all([generateAlicesKeyPair, generateBobsKeyPair]).then(values => {
  const alicesKeyPair = values[0];
  const bobsKeyPair = values[1];
  const deriveBitsButton = document.querySelector(".ecdh .derive-bits-button");
  deriveBitsButton.addEventListener("click", () => {
    // Alice then generates a secret using her private key and Bob's public key.
    // Bob could generate the same secret using his private key and Alice's public key.
    deriveSharedSecret(alicesKeyPair.privateKey, bobsKeyPair.publicKey);
  });
});
					

PBKDF2

In this example we ask the user for a password, then use it to derive some bits using PBKDF2. See the complete code on GitHub.

let salt;
/*
Get some key material to use as input to the deriveBits method.
The key material is a password supplied by the user.
*/
function getKeyMaterial() {
  const password = window.prompt("Enter your password");
  const enc = new TextEncoder();
  return window.crypto.subtle.importKey(
    "raw",
    enc.encode(password),
    {name: "PBKDF2"},
    false,
    ["deriveBits", "deriveKey"]
  );
}
/*
Derive some bits from a password supplied by the user.
*/
async function getDerivedBits() {
  const keyMaterial = await getKeyMaterial();
  salt = window.crypto.getRandomValues(new Uint8Array(16));
  const derivedBits = await window.crypto.subtle.deriveBits(
    {
      "name": "PBKDF2",
      salt: salt,
      "iterations": 100000,
      "hash": "SHA-256"
    },
    keyMaterial,
    256
  );
  const buffer = new Uint8Array(derivedBits, 0, 5);
  const derivedBitsValue = document.querySelector(".pbkdf2 .derived-bits-value");
  derivedBitsValue.classList.add("fade-in");
  derivedBitsValue.addEventListener("animationend", () => {
    derivedBitsValue.classList.remove("fade-in");
  });
  derivedBitsValue.textContent = `${buffer}...[${derivedBits.byteLength} bytes total]`;
}
const deriveBitsButton = document.querySelector(".pbkdf2 .derive-bits-button");
deriveBitsButton.addEventListener("click", () => {
  getDerivedBits();
});
					

规范

规范 状态 注释
Web Cryptography API
The definition of 'SubtleCrypto.deriveBits()' in that specification.
推荐 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
deriveBits Chrome 37 Edge 部分支持 12
部分支持 12
Not supported: ECDH.
Not supported: HKDF, PBKDF2.
Firefox 34
34
不支持 32 — 34 Disabled
Disabled ). To change preferences in Firefox, visit
IE No Opera 24 Safari 7 WebView Android 37 Chrome Android 37 Firefox Android 34
34
不支持 32 — 34 Disabled
Disabled ). To change preferences in Firefox, visit
Opera Android 24 Safari iOS 7 Samsung Internet Android 6.0

图例

完整支持

完整支持

部分支持

部分支持

不支持

不支持

见实现注意事项。

用户必须明确启用此特征。

用户必须明确启用此特征。

另请参阅

元数据

  • 最后修改:
  1. Web 加密 API
  2. SubtleCrypto
  3. 方法
    1. decrypt()
    2. deriveBits()
    3. deriveKey()
    4. digest()
    5. encrypt()
    6. exportKey()
    7. generateKey()
    8. importKey()
    9. sign()
    10. unwrapKey()
    11. verify()
    12. wrapKey()
  4. Related pages for Web Crypto API
    1. Crypto
    2. CryptoKey
    3. CryptoKeyPair
    4. RandomSource
    5. Window.crypto

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1