importKey
The importKey()
imports a key from an external, portable format, and gives you a CryptoKey object that can be used with the Web Crypto API.
Usage
importKey(format, keyData, algorithm, extractable, keyUsages)
Parameters
Supported algorithms
Supported formats
ECDH
andECDSA
algorithms have support forpkcs8
,spki
,raw
andjwk
formats.RSA-OAEP
,RSASSA-PKCS1-v1_5
andRSA-PSS
algorithms have support forpkcs8
,spki
andjwk
formats.AES-*
andHMAC
algorithms have currently support forraw
andjwk
formats.
Return Value
A Promise
that resolves with the imported key as a CryptoKey object.
Throws
Examples
Round-trip key export/import
import { crypto } from 'k6/experimental/webcrypto';
export default async function () {
/**
* Generate a symmetric key using the AES-CBC algorithm.
*/
const generatedKey = await crypto.subtle.generateKey(
{
name: 'AES-CBC',
length: '256',
},
true,
['encrypt', 'decrypt']
);
/**
* Export the key in raw format.
*/
const exportedKey = await crypto.subtle.exportKey('raw', generatedKey);
/**
* Reimport the key in raw format to verify its integrity.
*/
const importedKey = await crypto.subtle.importKey('raw', exportedKey, 'AES-CBC', true, [
'encrypt',
'decrypt',
]);
console.log(JSON.stringify(importedKey));
}
Import a static raw key and decrypt transmitted data
This example demonstrates how to import a static raw
key and decrypt some transmitted data in base64
. The transmitted data in this example represents an initialization vector and encoded data, and in a real-world scenario, it can be a response body or other data received from a request.
Import a static JWK key and decrypt transmitted data
This example is similar to the previous one. It demonstrates how to import a static jwk
key and decrypt some transmitted data (which contains the initialization vector and encoded data) in base64
.