假设要生成一个满足如下条件的非对称密钥: 支持 ECDSA 算法;
使用 P-256 椭圆曲线;
可以从 CryptoKey 中提取;
可以跟 sign()和 verify()方法一起使用。
那么可以参考如下代码:
(async function() { const params = { name: 'ECDSA',
namedCurve: 'P-256'
};
const keyUsages = ['sign', 'verify'];
const {publicKey, privateKey} = await crypto.subtle.generateKey(params, true, keyUsages);
// CryptoKey {type: "private", extractable: true, algorithm: {...}, usages: Array(1)} 16 })();
导出和导入密钥
如果密钥是可提取的,那么就可以在 CryptoKey 对象内部暴露密钥原始的二进制内容。使用 17 exportKey()方法并指定目标格式(“raw”、“pkcs8”、“spki"或"jwk”)就可以取得密钥。这个方
console.log(publicKey);
// CryptoKey {type: "public", extractable: true, algorithm: {...}, usages: Array(1)}
console.log(privateKey);
法返回一个期约,解决后的 ArrayBuffer 中包含密钥:
(async function() {
const params = {
name: 'AES-CTR',
length: 128
};
const keyUsages = ['encrypt', 'decrypt'];
const key = await crypto.subtle.generateKey(params, true, keyUsages); const rawKey = await crypto.subtle.exportKey('raw', key);
console.log(new Uint8Array(rawKey));
// Uint8Array[93, 122, 66, 135, 144, 182, 119, 196, 234, 73, 84, 7, 139, 43, 238,
// 110] 21
})();
与 exportKey()相反的操作要使用 importKey()方法实现。importKey()方法的签名实际上是 generateKey()和 exportKey()的组合。下面的方法会生成密钥、导出密钥,然后再导入密钥: 22
(async function() {
const params = {
name: 'AES-CTR',
length: 128
};
const keyUsages = ['encrypt', 'decrypt'];
const keyFormat = 'raw';
const isExtractable = true; 24
const key = await crypto.subtle.generateKey(params, isExtractable, keyUsages);
const rawKey = await crypto.subtle.exportKey(keyFormat, key);
const importedKey = await crypto.subtle.importKey(keyFormat, rawKey, params.name, isExtractable, keyUsages);
console.log(importedKey);
// CryptoKey {type: "secret", extractable: true, algorithm: {...}, usages: Array(2)}
})();