Node.js: How to convert RSA public key to OpenSSH format?
Asked Answered
D

1

6

I am on node version: v10.14.1 and I generate keyPairs with this code:

generateKeyPair('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: ''
    }
}, (err, publicKey, privateKey) => {
  // Do stuff
});

This will create a public key in this format:

-----BEGIN RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----

Unfortunately sometimes different formats are needed. In my case to upload public key to AWS the OpenSSH format is needed which I believe is something like this:

ssh-rsa 
...

How can I either convert the RSA public key format to OpenSSH format or generate it directly with generateKeyPair()?

Decastere answered 22/12, 2018 at 16:23 Comment(0)
H
8

The node-sshpk package might help you: https://github.com/joyent/node-sshpk

You can use pubKey.toBuffer() or, a bit more sophisticated, pubKey.toBuffer('ssh'). Or pubKey.toString('ssh') in case you need it as a string.

In your example the code should be something like this:

const { generateKeyPair }   = require('crypto');
const sshpk                 = require('sshpk');

generateKeyPair('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
        type: 'pkcs1',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
    }
}, (err, publicKey, privateKey) => {
    if(err){
        // handle Error
    }
    else{
        const pemKey = sshpk.parseKey(publicKey, 'pem');
        const sshRsa = pemKey.toString('ssh');
        console.log(ssh_rsa_2);
    }
});
Hammers answered 28/1, 2019 at 16:9 Comment(1)
Sorry that it took so long to accept your answer, even though it helped (and still does) to solve my question.Decastere

© 2022 - 2024 — McMap. All rights reserved.