sábado, 17 de septiembre de 2011

PHP: PKI encryption tutorial

Solution

  1. Generate a self-signed certificate issuing the following command in a linux terminal:

    openssl req -x509 -days 730 -newkey rsa:2048 -keyout privateKey.pem -nodes -out certificate.pem
  2. Place both files privateKey.pem and certificate.pem in the root of your webserver (docroot)
  3. Enable PHP OpenSSL extension
  4. Create the following PHP file
$sensitiveData = 'text to cypher';
echo 'Sensitive data is: ' . $sensitiveData . '
';

//load certificate containing public key for encryption
$pubKey = openssl_pkey_get_public('file:///certificate.pem');
openssl_public_encrypt($sensitiveData, $encryptedData, $pubKey);
echo 'Encrypted data is: ' . $encryptedData . '
';

//load private key for decryption
$privateKey = openssl_pkey_get_private('file:///privateKey.pem');
openssl_private_decrypt($encryptedData, $sensitiveData, $privateKey);
echo 'Sensitive decrypted data is: ' . $sensitiveData . '
';

?>

You should now see an output similar to the following:

Sensitive data is: text to cypher
Encrypted data is: 2äÙdÆÁÕYÄ:6ÈÓnñ¬þ–ëëZW »†vÑÜùǤ¿9›øÞr[ÃâÐ$Z„Ÿ–NžRõÜBTåIùr]»o£¹ÉYr<ËúètÊÿø jÀîFÒSyýAáy@5'ÝËð(’;×3µ 9faH<ê¼ì/‰c궫¶§)qÊóú|ì³Ö^Š,ùø[-ö¢§idÕ_=d·}ò°xÄŽŽ æ1±† è O ÉÀZQìùx|WÀ0 î9QÍ‚aÉIÑ e³]/v‹/5¬÷È€NrL{–=…0µ–Æ+KÈ;ÙthÛä}Lö¼ÖB“ß<ßÝ(ÁÁ0-”
Sensitive decrypted data is: text to cypher

No hay comentarios: