javascript基础学习系列三百四十一:导出和导入密钥

本文详细介绍了如何在JavaScript的WebCryptoAPI中生成支持ECDSA算法、基于P-256椭圆曲线的密钥,并展示了如何使用exportKey()和importKey()方法进行密钥导出和导入的过程,以及AES-CTR加密示例。
摘要由CSDN通过智能技术生成

假设要生成一个满足如下条件的非对称密钥:  支持 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)}
})();
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值