OpenSSL PHP Guide: Encryption & Security
In PHP, the OpenSSL library offers a set of functions to perform encryption and decryption, generate digital certificates, and verify signatures. Here are some common examples of how to use OpenSSL functions.
- Generate RSA key pair.
$keypair = openssl_pkey_new(array(
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
openssl_pkey_export($keypair, $privateKey);
$publicKey = openssl_pkey_get_details($keypair)['key'];
- Encrypting and decrypting data:
$data = 'Hello, World!';
$encrypted = '';
openssl_public_encrypt($data, $encrypted, $publicKey);
$decrypted = '';
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
echo $decrypted; // Output: Hello, World!
- Creating a digital signature and verifying the signature:
$data = 'Hello, World!';
$signature = '';
openssl_sign($data, $signature, $privateKey, OPENSSL_ALGO_SHA256);
$verified = openssl_verify($data, $signature, $publicKey, OPENSSL_ALGO_SHA256);
echo $verified; // Output: 1 (verified)
- Create a self-signed certificate.
$dn = array(
'countryName' => 'US',
'organizationName' => 'Example Company',
'commonName' => 'example.com',
);
$csr = openssl_csr_new($dn, $privateKey);
$cert = openssl_csr_sign($csr, null, $privateKey, 365);
openssl_x509_export($cert, $certout);
echo $certout;
These examples demonstrate common OpenSSL function usage so that you can select the appropriate functions based on your specific needs to implement encryption, signing, and certificate generation functions.