Reputation: 4773
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()
?
Upvotes: 6
Views: 3877
Reputation: 11196
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);
}
});
Upvotes: 8