如何导入 ECDH 公钥(无法使用指定的密钥用法创建密钥)

gas*_*ard 6 webcrypto-api ecdh

我正在尝试使用 webcrypto 运行代码,但似乎无法导入 ECDH 公钥。我错过了什么?

我收到此错误:无法使用指定的密钥用法创建密钥。

浏览器:Google Chrome 版本 71.0.3578.98(官方版本)(64 位)

(在 Firefox 上工作正常)。

window.crypto.subtle
  .generateKey(
    {
      name: 'ECDH',
      namedCurve: 'P-256',
    },
    true,
    ['deriveKey', 'deriveBits']
  )
  .then(function(key) {
    return window.crypto.subtle
      .exportKey('raw', key.publicKey)
      .then(function(ecdhPub) {
        return window.crypto.subtle
          .importKey(
            'raw',
            ecdhPub,
            {
              name: 'ECDH',
              namedCurve: 'P-256',
            },
            false,
            ['deriveKey', 'deriveBits']
          )
          .then(function(ecdhPubKey) {
            console.log('DONE !!', ecdhPubKey)
          })
          .catch(function(err) {
            console.log('COULD NOT IMPORT...')
            console.error(err)
          })
      })
      .catch(function(err) {
        console.log('COULD NOT EXPORT...')
        console.error(err)
      })
  })
  .catch(function(err) {
    console.log('COULD NOT GENERATE KEYS...')
    console.error(err)
  })
Run Code Online (Sandbox Code Playgroud)

Wil*_*gan 2

截至 2022 年和 Chrome 107,不幸的是 @Anna B 仍然正确 - 您需要将 keyUsages 设置为[]。这适用于 Chrome、Firefox 和 Safari。