Creating SSH keys using PHP

Continuous Deployment, Quick Tip

So in my day-to-day development I like to use Continuous Deployment for every project where I can. Continuous Deployment means that every time 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 I don't have any basic problems, like handling untracked changes in production. It just works.

Now, one thing I always struggle with when adding Continuous Deployment is managing the SSH keys. SSH keys are used so that the deployment procedure can log in to the server without using a password. SSH keys consist of two files: a public file and a private file. You keep the private file on your local system; the public file you add to the server. Using these two keys, you don't need a password to log in.

I have an SSH key on my local system, but this gives me access to all servers I log in to on a regular basis. For Continuous Deployment to work safely, I like to create a new key set. This process normally looks 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

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 two keys: publickey and privatekey. Nice. Now we want to increase the key length for increased security. Just call createKey with the desired key length:

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

The public key can contain a name for the key, which defaults 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.

Michiel Gerritsen
About the author

Michiel Gerritsen

Connect on LinkedIn

Founder of Control Alt Delete, a Magento agency specialised in testing, CI/CD and checkout integrations. Working with Magento since 2015, and board member of Mage-OS.

Missing anything?
What are you missing? X
Thank you for your feedback!