KeyObject.from(key)


示例:将 CryptoKey 实例转换为 KeyObject

const { webcrypto, KeyObject } = await import('node:crypto');
const { subtle } = webcrypto;

const key = await subtle.generateKey({
  name: 'HMAC',
  hash: 'SHA-256',
  length: 256
}, true, ['sign', 'verify']);

const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// 打印: 32 ((以字节为单位的对称密钥大小))const {
  webcrypto: {
    subtle,
  },
  KeyObject,
} = require('node:crypto');

(async function() {
  const key = await subtle.generateKey({
    name: 'HMAC',
    hash: 'SHA-256',
    length: 256
  }, true, ['sign', 'verify']);

  const keyObject = KeyObject.from(key);
  console.log(keyObject.symmetricKeySize);
  // 打印: 32 ((以字节为单位的对称密钥大小))
})();

Example: Converting a CryptoKey instance to a KeyObject:

const { webcrypto, KeyObject } = await import('node:crypto');
const { subtle } = webcrypto;

const key = await subtle.generateKey({
  name: 'HMAC',
  hash: 'SHA-256',
  length: 256
}, true, ['sign', 'verify']);

const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// Prints: 32 (symmetric key size in bytes)const {
  webcrypto: {
    subtle,
  },
  KeyObject,
} = require('node:crypto');

(async function() {
  const key = await subtle.generateKey({
    name: 'HMAC',
    hash: 'SHA-256',
    length: 256
  }, true, ['sign', 'verify']);

  const keyObject = KeyObject.from(key);
  console.log(keyObject.symmetricKeySize);
  // Prints: 32 (symmetric key size in bytes)
})();