Search code examples
javascriptexportopenssh

Exporting ed25519 private key in OpenSSH Format JavaScript


I have created an ed25519 key pair using the javascript crypto library

    import crypto from 'crypto'
    import sshpk from 'sshpk'

    const keypair = crypto.generateKeyPairSync(
      'ed25519',
      {
        modulusLength: 256,
        privateKeyEncoding: { format: 'pem', type: 'pkcs8' },
        publicKeyEncoding: { format: 'pem', type: 'spki' }
      }
    )

Now I need to save the private key in openssh format.

I have tried using the sshpk library but when I try to export my private key to 'ssh' format, the library exports the public key not the private key.

 var sshpkKey = sshpk.parseKey(keypair.privateKey.toString(), 'ssh-private')
 console.log(sshpkKey.toString('ssh'))

outputs

ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIodXPD2GDD5tcgCdsmktQux+tDM8yJhzX09V9yZn4Q6 (unnamed)

So I obviously have the wrong function call here ".toString('ssh')", but, I cannot for the life of me find the right call to export the private key into the following format.

-----BEGIN OPENSSH PRIVATE KEY-----
.
.
.
-----END OPENSSH PRIVATE KEY-----

Maybe I am using the wrong library all together?


Solution

  • Ok I figured out the answer and it was of course simple. But for anyone else banging there heads on it when it is right in front of them. This works.

        var parsedKey = sshpk.parsePrivateKey(pemString, 'pem');
        var exported = parsedKey.toString('openssh');