有没有一种简单的方法可以将 NodeJS KeyObject 转换为 Buffer?

Is there a simple way to convert a NodeJS KeyObject to a Buffer?

我正在使用 NodeJS 生成 Ed25519 密钥对。我需要将 public 键转换为自定义字符编码。但是,似乎无法将 crypto.generateKeyPair() 返回的 KeyObject 转换为缓冲区。

标准库是否提供一种直接将密钥生成为缓冲区而不是 KeyObjects 的方法?

KeyObject 提供了一个 .export() 方法,可以为您提供字符串或缓冲区。看来您可以使用该方法转换您的 KeyObject,然后可以应用您的自定义编码。

https://nodejs.org/api/crypto.html#crypto_keyobject_export_options

只有指定publicKeyEncodingand/orprivateKeyEncoding才能直接生成buffer/string。但是,如果您使用的是不受支持的自定义编码,那么您将无法做到这一点。您可以将其导出到 Buffer/String,然后对其应用您的自定义编码。

来自 API 的文档:

If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.