Creating SSH keys using PHP

Continuous Deployment, Quick Tip

So in my day to day development i like to use continues deployment for every project where i can. Continues deployment means that everytime i push a commit to master the latest version of master will automatically be deployed to my production environment. This makes my development cycle way faster, and it makes sure that it don't have any basic problems, like handling untracked changes on the production. It just works.

Now, one thing i always struggle with when adding continues deployment is managing the SSH keys. SSH keys are use so that the deployment procedure can login on the server without using a password. SSH keys consist out of 2 files: a public file and a private file. The private file you keep on you local system, the public file you add to the server. Using this 2 keys you don't need an password to login.

I have an SSH key on my local system, but this gives me access to all servers is login on a regular basis. For a continues deployment to work safely i like to create a new keyset. This process normal looks like something like this:

  • Search the correct command, as ssh-keygen is not enough.

  • Run ssh-keygen -t rsa -b 4096.

  • Manually type a new path as the command does not support autocomplete and the default location is already taken.

  • Press enter a few times.

  • Copy the public file: cat ~/.ssh/new-key.rsa.pub

  • Copy the private file: cat ~/.ssh/new-key.rsa

SSHkeygen.io

I hate this process as it is quite cumberstone. As i was having some travel time to a freelance gig, i decided to code something out i wanted to do for a while. This turned out to be sshkeygen.io. When you visit this site the public and private keys are automatically generated. But how are the keys generated exactly?

phpseclib

Meet phpseclib: This library gives you a few possibilities. You can use it to access ssh and sftp servers, encrypt data, etc. It also has an option to create SSH keys.

So to start we first need to require it in our project:

composer require phpseclib/phpseclib

After doing this the creation of keys is pretty simple:

$rsa = new phpseclibCryptRSA();
$rsa->setPrivateKeyFormat(phpseclibCryptRSA::PUBLIC_FORMAT_OPENSSH);
$rsa->setPublicKeyFormat(phpseclibCryptRSA::PUBLIC_FORMAT_OPENSSH);

$keys = $rsa->createKey();

The result in the $keys variable is an array with 2 keys: publickey and privatekey. Nice. Now we want to increase the key length for increased security. Just call the createKey with the desired key length:

$keys = $rsa->createKey(4096);

The public key can contain an name of the key, which default in this case to phpseclib-generated-key. We can easily change this by calling the setComment method:

$rsa->setComment('my-customer-generated-key');

And that's it. Now you can generate SSH keys using PHP.

Want to respond?