SubtleCrypto
The SubtleCrypto
接口提供了一组低级别的加密原语,例如加密、解密、数字签名生成和验证,以及密钥生成和管理。它对于在 k6 脚本中使用安全高效的加密操作非常有用。
方法
方法 | 描述 |
---|---|
encrypt | 使用指定的算法和密钥加密给定的明文数据。 |
decrypt | 使用指定的算法和密钥解密给定的密文数据。 |
sign | 使用指定的算法和密钥对给定数据进行签名。 |
verify | 使用指定的算法和密钥验证给定数据的签名。 |
digest | 使用指定的算法计算给定数据的摘要(哈希)。 |
generateKey | 为指定的算法生成一个新的加密密钥。 |
importKey | 将原始密钥材料导入 Web Crypto API,生成一个新的密钥对象用于指定的算法。 |
exportKey | 导出给定密钥对象的原始密钥材料。 |
deriveBits | 使用提供的输入派生比特。 |
示例
export default async function () {
const plaintext = stringToArrayBuffer('Hello, World!');
/**
* Generate a symmetric key using the AES-CBC algorithm.
*/
const key = await crypto.subtle.generateKey(
{
name: 'AES-CBC',
length: 256,
},
true,
['encrypt', 'decrypt']
);
/**
* Encrypt the plaintext using the AES-CBC key with
* have generated.
*/
const iv = crypto.getRandomValues(new Uint8Array(16));
const ciphertext = await crypto.subtle.encrypt(
{
name: 'AES-CBC',
iv: iv,
},
key,
plaintext
);
/**
* Decrypt the ciphertext using the same key to verify
* that the resulting plaintext is the same as the original.
*/
const deciphered = await crypto.subtle.decrypt(
{
name: 'AES-CBC',
iv: iv,
},
key,
ciphertext
);
console.log(
'deciphered text == original plaintext: ',
arrayBufferToHex(deciphered) === arrayBufferToHex(plaintext)
);
}
function arrayBufferToHex(buffer) {
return [...new Uint8Array(buffer)].map((x) => x.toString(16).padStart(2, '0')).join('');
}
function stringToArrayBuffer(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;
}