Generating Public & Private Keys Using PHPSECLIB

A few tasks that I’ve been working on this weekend have needed public/private key pairs. The very useful phpseclib library provides the tools that you need to generate these within your application.

// Get a new RSA object and set the type, hash and comment
$rsa = new RSA;

// Actually generate the key, change 4096 for the desired number of bytes
$keys = $rsa->createKey(4096);
$keyPrivate = $keys[“privatekey”];
$keyPublic = $keys[“publickey”];

// Get the fingerprint for this key
$keyFingerprint = $rsa->getPublicKeyFingerprint();