Tuesday, May 22, 2012

Data encryption with OpenSSL in PHP

PKI is well-known and widely spread technology. It is very easy to use it for data encryption in PHP using the standard OpenSSL extension. Data are encrypted with the public key and decrypted with the private key. There is one restriction though - the size of data encrypted with the public key can be up to the length of the key (usually 1024 or 2048 bytes), which may not be enough. Of course, you could divide your data into chunks and encrypt them separately, but there is a better solution.


Instead of directly encrypting data with the public key, you can use another technology with a symmetric key and then encrypt the symmetric key with the public key. The "recipient" will get the encrypted key along with the encrypted data. Then he will first decrypt the key using his private key and then use it to decrypt data.

In the OpenSSL extension there are functions, which implement that.You can use the openssl_seal() function, which encrypts data using RC4 with a randomly generated key and encrypts that key with the public key. Encrypted data can be then decrypted using the openssl_open() function.

Although there is no problem in using these functions directly, I wrote a simple object oriented library to make the process easier and more "programmer-firendly". It offers more convenience with key manipulation and mey be extended in the future. Example usage:
namespace OpenSslCrypt;

$processor = new Processor();

/*
 * Encryption with the public key.
 */
$pubKey = Key\Pub::fromCertificateFile('ssl/crypt.crt');
$encData = $processor->encrypt($data, $pubKey);

/*
 * Decryption with the private key.
 */
$privKey = Key\Priv::fromPrivateKeyFile('ssl/crypt.key');
$decData = $processor->decrypt($encData, $privKey);

You can find it on GitHub.

No comments:

Post a Comment