The experimental module k6/experimental/webcrypto has graduated, and its functionality is now available globally through the crypto object. The k6/experimental/webcrypto is deprecated and will be removed in the near future.
To migrate your scripts, remove the k6/experimental/webcrypto imports and use the crypto object instead.
The sign() operation generates a digital signature of the provided data, using the given CryptoKey object.
A Promise that resolves with the signature as an ArrayBuffer.
Throws
Type
Description
InvalidAccessError
Raised when the signing key either does not support signing operation, or is incompatible with the selected algorithm.
Examples
Signing data with HMAC key
JavaScript
import{ crypto }from'k6/experimental/webcrypto';exportdefaultasyncfunction(){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);}functionstring2ArrayBuffer(str){const buf =newArrayBuffer(str.length *2);// 2 bytes for each charconst bufView =newUint16Array(buf);for(let i =0, strLen = str.length; i < strLen; i++){
bufView[i]= str.charCodeAt(i);}return buf;}
Signing and verifying data with ECDSA
JavaScript
import{ crypto }from'k6/experimental/webcrypto';exportdefaultasyncfunction(){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 keyconst signature =await crypto.subtle.sign(alg, keyPair.privateKey, data);
console.log('signature: ',printArrayBuffer(signature));//Verifies the signature of the encoded data with the provided keyconst verified =await crypto.subtle.verify(alg, keyPair.publicKey, signature, data);
console.log('verified: ', verified);}conststring2ArrayBuffer=(str)=>{const buf =newArrayBuffer(str.length *2);// 2 bytes for each charconst bufView =newUint16Array(buf);for(let i =0, strLen = str.length; i < strLen; i++){
bufView[i]= str.charCodeAt(i);}return buf;};constprintArrayBuffer=(buffer)=>{const view =newUint8Array(buffer);return Array.from(view);};