菜单
开源

sign

注意

实验性模块 k6/experimental/webcrypto 已经毕业,其功能现已通过 crypto 对象全局可用。k6/experimental/webcrypto 已被弃用,并将在不久的将来移除。

要迁移您的脚本,请移除 k6/experimental/webcrypto 导入,并改用 crypto 对象。

sign() 操作使用给定的 CryptoKey 对象生成所提供 data 的数字签名。

用法

sign(algorithm, key, data)

参数

名称类型描述
algorithmstring 或带有单个 name 字符串属性的对象 ({name: "RSASSA-PKCS1-v1_5"}) 或 EcdsaParamsHmacKeyGenParamsRsaPssParams 对象。要使用的签名算法。
keyCryptoKey用于签名的密钥。
dataArrayBufferTypedArrayDataView要签名的数据。

支持的算法

ECDSAHMACRSASSA-PKCS1-v1_5RSA-PSS
EcdsaParamsHmacKeyGenParamsRsaPssParams

返回值

一个 Promise,解析后返回签名作为 ArrayBuffer

抛出

类型描述
InvalidAccessError当签名密钥不支持签名操作或与所选算法不兼容时抛出。

示例

使用 HMAC 密钥签名数据

JavaScript
import { crypto } from 'k6/experimental/webcrypto';

export default async function () {
  const generatedKey = await crypto.subtle.generateKey(
    {
      name: 'HMAC',
      hash: { name: 'SHA-1' },
    },
    true,
    ['sign', 'verify']
  );

  const data = string2ArrayBuffer('Hello World');

  /**
   * Signes the encoded data with the provided key using the HMAC algorithm
   * the returned signature can be verified using the verify method.
   */
  const signature = await crypto.subtle.sign('HMAC', generatedKey, data);

  /**
   * Verifies the signature of the encoded data with the provided key using the HMAC algorithm.
   */
  const verified = await crypto.subtle.verify('HMAC', generatedKey, signature, data);

  console.log('verified: ', verified);
}

function string2ArrayBuffer(str) {
  const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
  const bufView = new Uint16Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

使用 ECDSA 签名和验证数据

JavaScript
import { crypto } from 'k6/experimental/webcrypto';

export default async function () {
  const keyPair = await crypto.subtle.generateKey(
    {
      name: 'ECDSA',
      namedCurve: 'P-256',
    },
    true,
    ['sign', 'verify']
  );

  const data = string2ArrayBuffer('Hello World');

  const alg = { name: 'ECDSA', hash: { name: 'SHA-256' } };

  // makes a signature of the encoded data with the provided key
  const signature = await crypto.subtle.sign(alg, keyPair.privateKey, data);

  console.log('signature: ', printArrayBuffer(signature));

  //Verifies the signature of the encoded data with the provided key
  const verified = await crypto.subtle.verify(alg, keyPair.publicKey, signature, data);

  console.log('verified: ', verified);
}

const string2ArrayBuffer = (str) => {
  const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
  const bufView = new Uint16Array(buf);
  for (let i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
};

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