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()
?
To convert a SSH client key to an OpenSSH format:Install the OpenSSH tool set, available under a BSD-style license: http://www.openssh.com/ The ssh-keygen utility is used to covert SSH keys between the different formats required by MessageWay or any other secure file transfer application.
An SSH2 public key in OpenSSH format will start with "ssh-rsa". The idea behind all of this is that once you have keys on the remote server and your local host, access will be simpler since the server will only grant access to someone who has the matching private key.
The OpenSSH public key format The public key saved by ssh-keygen is written in the so-called SSH-format, which is not a standard in the cryptography world. It's structure is ALGORITHM KEY COMMENT , where the KEY part of the format is encoded with Base64.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With