Search code examples
node.jscryptographyed25519

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


I am using NodeJS to generate Ed25519 keypairs. I need to convert the public key to a custom character encoding. However, there seems to be no way to convert the KeyObjects returned by the crypto.generateKeyPair() to buffers.

Does the standard library offer a way to directly generate the keys as buffers instead of KeyObjects?


Solution

  • The KeyObject offers a .export() method that will give you a string or a buffer. It seems you can use that method to convert your KeyObjects and can then apply your custom encoding.

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

    You can get it to directly generate as a buffer/string only if you specify the publicKeyEncoding and/or privateKeyEncoding. But, if you're using a non-supported, custom encoding, then you can't get it to do that. You can export it to a Buffer/String and then apply your custom encoding to that.

    From the doc for the 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.