最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to correctly implement Web Crypto API generateKey and exportKey? - Stack Overflow

programmeradmin0浏览0评论

Hello everyone!

I have this code:

async function generateKey() {
  const algoritm = { name: "AES-CBC", length: 256 };
  const exportable = true;
  const usage = ['encrypt'];
  return await window.crypto.subtle.generateKey(algoritm, exportable, usage).then(key => { return key; 
  });
}

when I call console.log(generateKey ()); I get: >Promise at first load and >Promise {<pending>} when update browser window.

async function exportKey(key) {
  const format = "jwk";
  return await window.crypto.subtle.exportKey(format, key).then(key => { return key; });
}

when I call let key =generateKey(); console.log(exportKey (key)); I get: 'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

I have two questions about

  • What is the correct way to generate a key with the given parameters?

  • What is the correct way to export a generated key in JSON format?

I e read from: SubtleCrypto MDN Web Docs

Hello everyone!

I have this code:

async function generateKey() {
  const algoritm = { name: "AES-CBC", length: 256 };
  const exportable = true;
  const usage = ['encrypt'];
  return await window.crypto.subtle.generateKey(algoritm, exportable, usage).then(key => { return key; 
  });
}

when I call console.log(generateKey ()); I get: >Promise at first load and >Promise {<pending>} when update browser window.

async function exportKey(key) {
  const format = "jwk";
  return await window.crypto.subtle.exportKey(format, key).then(key => { return key; });
}

when I call let key =generateKey(); console.log(exportKey (key)); I get: 'SubtleCrypto': parameter 2 is not of type 'CryptoKey'.

I have two questions about

  • What is the correct way to generate a key with the given parameters?

  • What is the correct way to export a generated key in JSON format?

I e read from: SubtleCrypto MDN Web Docs

Share Improve this question edited May 28, 2020 at 17:58 LT-Sites asked May 28, 2020 at 17:37 LT-SitesLT-Sites 4156 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

Your API usage looks correct. You are getting the error 'SubtleCrypto': parameter 2 is not of type 'CryptoKey' because parameter 2 is of type Promise. To fix this issue, resolve the promise from generateKey before passing it to exportKey

const main = async () => {
  const key = await generateKey()
  const exported = await exportKey(key)
  console.log(exported)
}

Of course, this can get even simpler if you use my library, rubico

const { pipe } = require('rubico')

const main = pipe([generateKey, exportKey, console.log])

The two examples are equivalent.

发布评论

评论列表(0)

  1. 暂无评论