This is documentation for the next version of Grafana k6 documentation. For the latest stable release, go to the latest version.

Open source

deriveBits

It takes as its arguments the base key, the derivation algorithm to use, and the length of the bits to derive. It returns a Promise which will be fulfilled with an ArrayBuffer containing the derived bits. This array of bits can be used as a key for encryption or decryption as a shared secret.

Usage

deriveBits(algorithm, baseKey, length)

Parameters

NameTypeDescription
algorithmEcdhKeyDeriveParams or Pbkdf2ParamsAn object defining a derivation algorithm to use.
baseKeyCryptoKeyRepresents an input to derivation algorithm. Could be an ECDH private key or a PBKDF2 password imported as a CryptoKey.
lengthnumberThe requested number of bits. It must be greater than zero. PBKDF2 requires a multiple of eight; ECDH and X25519 also accept non-byte-aligned lengths.

Supported algorithms

ECDHX25519PBKDF2HKDF
✅ EcdhKeyDeriveParams✅✅ Pbkdf2Params❌

Return Value

A Promise that resolves to a new ArrayBuffer containing the derived bits.

Throws

TypeDescription
OperationErrorRaised when length is zero or negative, when a requested ECDH or X25519 length exceeds the shared secret, or when a PBKDF2 length is not a multiple of eight.

For ECDH and X25519, the returned ArrayBuffer contains ceil(length / 8) bytes. k6 clears the unused low bits of the final byte. Provide an explicit positive numeric length. HKDF is not supported by this method.

Examples

Deriving a non-byte-aligned ECDH secret

JavaScript
export default async function () {
  const alice = await crypto.subtle.generateKey(
    { name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']
  );
  const bob = await crypto.subtle.generateKey(
    { name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']
  );
  const bits = await crypto.subtle.deriveBits(
    { name: 'ECDH', public: bob.publicKey }, alice.privateKey, 9
  );
  const bytes = new Uint8Array(bits);
  console.log(bytes.length === 2 && (bytes[1] & 0x7f) === 0);
}

Deriving the same X25519 secret on both sides

JavaScript
export default async function () {
  const alice = await crypto.subtle.generateKey('X25519', true, ['deriveBits']);
  const bob = await crypto.subtle.generateKey('X25519', true, ['deriveBits']);
  const aliceBits = await crypto.subtle.deriveBits(
    { name: 'X25519', public: bob.publicKey }, alice.privateKey, 256
  );
  const bobBits = await crypto.subtle.deriveBits(
    { name: 'X25519', public: alice.publicKey }, bob.privateKey, 256
  );
  const a = new Uint8Array(aliceBits);
  const b = new Uint8Array(bobBits);
  console.log(a.length === 32 && a.every((byte, index) => byte === b[index]));
}

Deriving bits using ECDH

JavaScript
export default async function () {
  // Generate a key pair for Alice
  const aliceKeyPair = await crypto.subtle.generateKey(
    {
      name: 'ECDH',
      namedCurve: 'P-256',
    },
    true,
    ['deriveKey', 'deriveBits']
  );

  // Generate a key pair for Bob
  const bobKeyPair = await crypto.subtle.generateKey(
    {
      name: 'ECDH',
      namedCurve: 'P-256',
    },
    true,
    ['deriveKey', 'deriveBits']
  );

  // Derive shared secret for Alice
  const aliceSharedSecret = await deriveSharedSecret(aliceKeyPair.privateKey, bobKeyPair.publicKey);

  // Derive shared secret for Bob
  const bobSharedSecret = await deriveSharedSecret(bobKeyPair.privateKey, aliceKeyPair.publicKey);

  console.log('alice shared secret: ' + printArrayBuffer(aliceSharedSecret));
  console.log('bob shared secret: ' + printArrayBuffer(bobSharedSecret));
}

async function deriveSharedSecret(privateKey, publicKey) {
  return crypto.subtle.deriveBits(
    {
      name: 'ECDH',
      public: publicKey,
    },
    privateKey,
    256
  );
}

const printArrayBuffer = (buffer) => {
  const view = new Uint8Array(buffer);
  return Array.from(view);
};

Deriving bits using PBKDF2

JavaScript
export default async function () {
  const password = new TextEncoder().encode('my secret password');

  // Import the password as a key
  const baseKey = await crypto.subtle.importKey('raw', password, 'PBKDF2', false, [
    'deriveBits',
    'deriveKey',
  ]);

  // Generate a random salt
  const salt = crypto.getRandomValues(new Uint8Array(16));

  // Derive 256 bits using PBKDF2
  const derivedBits = await crypto.subtle.deriveBits(
    {
      name: 'PBKDF2',
      hash: 'SHA-256',
      salt: salt,
      iterations: 310000,
    },
    baseKey,
    256
  );

  console.log('derived bits: ' + printArrayBuffer(derivedBits));
}

const printArrayBuffer = (buffer) => {
  const view = new Uint8Array(buffer);
  return Array.from(view);
};