Search code examples
node.jsdockeropensshcryptojs

openssh return "bad key type" with a crypto generated key pair


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.

my function is :

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.

hint #1 : gitlab.com is not a known host

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

hint #2 : the keys are wrong

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

the generated private key is as follow

https://pastebin.com/2JC7kz9r

Has anyone already generated keys with crypto and sshpk with success ? Or encoutered similar problem ?

Thank you for your help ! :)


Solution

  • 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 !