User Contributed Notes 3 notes

I was having a heck of a time finding help on making asynchronous encryption/decryption using private key/public key systems working, and I had to have it for creating a credit card module that uses recurring billing.

You'd be a fool to use normal, 'synchronous' or two-way encryption for this, so the whole mcrypt library won't help.

But, it turns out OpenSSL is extremely easy to use...yet it is so sparsely documented that it seems it would be incredibly hard.

So I share my day of hacking with you - I hope you find it helpful!

<?php

if (isset($_SERVER['HTTPS']) ){ echo "SECURE: This page is being accessed through a secure connection.<br><br>";}else{ echo "UNSECURE: This page is being access through an unsecure connection.<br><br>";}

// Create the keypair$res=openssl_pkey_new();

// Get private keyopenssl_pkey_export($res, $privatekey);

// Get public key$publickey=openssl_pkey_get_details($res);$publickey=$publickey["key"];

Many thanks to other contributors in the docs for making this less painful.

Note that you will want to use these sorts of functions to generate a key ONCE - save your privatekey offline for decryption, and put your public key in your scripts/configuration file. If your data is compromised you don't care about the encrypted stuff or the public key, it's only the private key and cleartext that really matter.

Normally, you can extract the ocsp url from the client certificate. Also, an OCSP request contains only the hash of the issuer name, the hash of the issuer's key, and the serial number of the client certificate. All three can be extracted directly from the client certificate.

OpenSSL creates asynchronous key pairs, however I wanted to have the private key something that was human-memorizable. With the standard keys generated, this is not possible. How I achieved it was to use two types of encryption.

After generating a key pair with OpenSSL, the public key can be stored in plain text format. I then encrypted the private key itself using regular mcrypt with the human-memorizable key of my choice and converted it to ACSII using base64_encode. Then to get the private key back, I just decrypted it with mcrypt. This way I could store the encrypted private key on the server without worrying about having things stored unencrypted.

Of course, this will only be as good as your human-memorizable key is and can potentially reduce the security of your script if you choose something simple or don't use salts.