PHP + OpenSSL = RSA Shared Key Generation

OK, so I’m super excited and wanted to jot down a note about RSA shared key generation.

Drama Mama

First, I wanted to generate some PEM formatted RSA public and private key pairs. I was going to do it the risky/hard way and exec openssl commands. Using exec is not a good idea if avoidable, but I was desperate. Just to put my mind at ease, I did some quick googling and found out it is possible to do this natively in PHP if you have the openssl extension installed and configured. FANTASTIC!

Then I got the curve ball. Using openssl_pkey_get_public doesn’t work as expected: it wouldn’t take a pkey resource handler and get the public key – how deceiving! I thought the thrill was over and I’d have to resort back to exec until the all mighty Brad shed his light upon us… four years ago (doh).

TL;DR

Here’s the code that generates the RSA shared key and fetched the public and private keys.

 

Alternatively, one could call the openssl commands directly: