decrypt
注意
实验性模块
k6/experimental/webcrypto
已经升级,其功能现在通过crypto
对象全局可用。k6/experimental/webcrypto
已被废弃,并将在不久的将来移除。要迁移您的脚本,请移除
k6/experimental/webcrypto
导入,转而使用crypto
对象。
decrypt()
方法解密加密的数据。
使用
decrypt(algorithm, key, data)
参数
名称 | 类型 | 描述 |
---|---|---|
algorithm | AesCbcParams、AesCtrParams 或 AesGcmParams 对象 | 定义要使用的算法和任何额外参数。为额外参数提供的值必须与相应的 [encrypt] 调用中使用的值匹配。 |
key | CryptoKey | 用于解密的 密钥。 |
data | ArrayBuffer 、TypedArray 或 DataView | 要解密的加密数据(也称为 ciphertext)。 |
支持的算法
AES-CBC | AES-CTR | AES-GCM | RSA-OAEP |
---|---|---|---|
✅ AesCbcParams | ✅ AesCtrParams | ✅ AesGcmParams | ✅ RsaOaepParams |
返回值
一个解析为包含解密数据的新 ArrayBuffer
的 Promise
。
抛出
类型 | 描述 |
---|---|
InvalidAccessError | 当所请求的操作与提供的密钥无效时抛出。例如,使用了无效的加密算法,或者提供的密钥与选定的算法不匹配。 |
OperationError | 当操作因特定原因失败时抛出。例如,算法大小无效,或者在解密密文过程中发生错误。 |
示例
import { crypto } from 'k6/experimental/webcrypto';
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;
}