1

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?

adrian
  • 1,439
  • 1
  • 15
  • 23

1 Answers1

1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 2
    Unfortunately it seems that for asymmetric keys `.export()` can only output PEM or DER. My current solution is to parse the outputted key, which is pretty inelegant but it works – adrian Jan 27 '21 at 16:55
  • please post your version of the code @adrian – SwiftiSwift Oct 06 '22 at 21:24