I need to generate a rsa key pair on node js
code in order to use it with an openssh
client on an docker
container.
I'm using the generateKeyPair function of crypto
to generate keys and parse[Private]Key
of sshpk to translate keys from pem
to openssh
format.
import { generateKeyPair } from 'crypto';
import sshpk from 'sshpk';
const createSShKeys = () => {
return new Promise((resolve, reject) => {
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
}, (error, publicKey, privateKey) => {
if (error) {
reject(error);
} else {
const publicKeySShEncoded = sshpk
.parseKey(publicKey, 'pem')
.toString('ssh');
const privateKeySShEncoded = sshpk
.parsePrivateKey(privateKey, 'pem')
.toBuffer('ssh', {}) // toString('ssh') is documented, but I not find it in code.
.toString();
resolve({
publicKey: publicKeySShEncoded,
privateKey: privateKeySShEncoded,
});
}
});
});
};
I create a docker secret
with the private key, and use it inside the container, but then I get :
Host key verification failed.
After search, I have found this answer, and I have added the host fingerprint inside the .ssh/known_hosts
file :
ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
But nothing has changed
To test the key pair, I have logged this :
const {
publicKey,
privateKey,
} = await createSShKeys();
console.log('#PUBLIC KEY');
console.log(publicKey);
console.log('#PRIVATE KEY');
console.log(privateKey);
And I have stored the private key in a file. I try to verify it with :
$ ssh-keygen -y -t private_key
bad key type
Has anyone already generated keys with crypto
and sshpk
with success ?
Or encoutered similar problem ?
Thank you for your help ! :)
The problem was really the key of the host, not the generated keys.
But the "clean" method doesn't work :
ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
The only working method is append these lines on /etc/ssh/ssh_config
:
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
I don't know why. (if anyone have idea ?)
But finaly, the keys are okay, it's probably a mistake on copy/paste (Lol)
Thank you all !