PHP OpenSSL Functions

By | August 30, 2020
PHP OpenSSL Functions

OpenSSL allows you to handle the communications that happen over the network. It is a tool that ensures the proper communication of data in transport layer security and the secure socket layers.

SSL Certificate

This SSL is commonly used by the website and uses SSL certificates. These certificates are used to protect and authenticate the transferred data between the computers with the help of encryption. These computers can be the server-client where the critical information will also get transferred and it has to be secured. SSL certificates ensure the authentication for secured communication.

Vamware

How to install OpenSSL in PHP

PHP includes the SSL module by default. All you have to activate it by removing the (;) from the start of -;extension=php_openssl.dll from the php.ini file. After making the changes you have to restart the apache and make sure that the changes are reflecting. You can save below code as .php and then you can run this file in the browser.

<?php
   phpinfo();
?>

After opening the file in the browser, it will show the enabled SSL settings.

Configuring OpenSSL

The configuration file for OpenSSL (openssl.cnf) has all the default settings in order to work properly. Whenever you run the OpenSSL, PHP will look for the OpenSSL configuration file. Add your PHP folder in the environment variable.

Below are the steps to set up the environment for the OpenSSL on Windows-

  • Right-click on My Computer and then go to settings
  • Then select Advanced System Settings
  • Select the Environment Variable option
  • Click on edit the path variables and select the edit button
  • Then add the PHP folder at the end.
  • Click ok

Once you are done with making the environment settings. Then go to the command prompt and run the below command

openssl version -a

You will get below data on the cmd screen-

C:\Windows\system32>openssl version -a

OpenSSL 1.0.2l 25 May 2017

built on: reproducible build, date unspecified

platform: mingw64

options: bn(64,64) rc4(16x,int) des(idx,cisc,2,long) idea(int) blowfish(idx)

compiler: x86_64-w64-mingw32-gcc -I. -I.. -I../include -D_WINDLL -DOPENSSL_PIC

-DOPENSSL_THREADS -D_MT -DDSO_WIN32 -static-libgcc -DL_ENDIAN -O3 -Wall -DWIN32_

LEAN_AND_MEAN -DUNICODE -D_UNICODE -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DO

PENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DRC4_ASM -DSHA1_ASM -DSHA256_ASM -DSH

A512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM

-DECP_NISTZ256_ASM

OPENSSLDIR: “/etc/ssl”

OpenSSL functions

PHP support below OpenSSL functions-

openssl_pkey_new()

a resource identifier will be returned which has new private and the public key pair. You can use openssl_pkey_get_details() function to get the information about the generated key. This key pair will later be used with other functions.

This function will take one parameter- configargs which may have different values like- digest_alg, x509_extensions, req_extensions, private_key_bits, private_key_type, encrypt_type, encrypt_key_cipher, curve_name, config.

Syntax

openssl_pkey_new ([ array $configargs ] ) : resource

Example

openssl_pkey_new() working

<?php
   $data = openssl_pkey_new(array(
      "digest_alg"=>'md5',
      "private_key_bits" => 2048,
      "private_key_type" => OPENSSL_KEYTYPE_RSA,
   ));
var_dump($data);
?>

Output

resource(4) of type (OpenSSL key)

openssl_pkey_new() and openssl_pkey_get_details working

<?php
   // Generate a new private (and public) key pair
   $data = openssl_pkey_new(array(
      "digest_alg"=>'md5',
      "private_key_bits" => 2048,
      "private_key_type" => OPENSSL_KEYTYPE_RSA,
   ));
   $details = openssl_pkey_get_details($data);
   print_r($details);
?>

Output

openssl_pkey_get_private()

This function will provide you the private key and its details. This function will take two parameters key and passphrase. Key will be taken from the .pem file or from the newly generated private key. If the key is encrypted then you have to mention the passphrase. This function will return the resource identifies if the command executed well without an error.

Syntax

openssl_pkey_get_private ( mixed $key [, string $passphrase = "" ] ) : resource

Example

openssl_pkey_get_private() working

<?php
$data = openssl_pkey_new();
openssl_pkey_export($data, $priv_key);
$test_key = openssl_pkey_get_private($priv_key);
if ($test_key === false) {
var_dump(openssl_error_string());
} else {
var_dump($test_key);
}
?>

Output

resource(5) of type (OpenSSL key)

openssl_pkey_get_private() with passphrase

<?php
   $data = openssl_pkey_new();
openssl_pkey_export($data, $testkey, 'helloworld');
$test_key = openssl_pkey_get_private($testkey, 'helloworld');
if ($test_key === false) {
var_dump(openssl_error_string());
} else {
//var_dump($test_key);
$key_details = openssl_pkey_get_details($test_key);
print_r($key_details);
}
?>

Output

openssl_pkey_get_public()- this function will provide you with the public key that is taken from the installed certificate in order to be used with other functions. This function will take one parameter that is the certificate to get the public key.

You can use certificates for the public key- x.509 certificate, from the .pem file and public key in the PEM format. This function will provide a resource identifier if the execution is successful without any error.

Example with X.509 certificate

<?php
   $dom = array(
      "countryName" => "IN",
"stateOrProvinceName" => "Delhi",
"localityName" => "addr1",
"organizationName" => "addr2",
"organizationalUnitName" => "addr3",
"commonName" => "www.XXX.com",
"emailAddress" => "test@XXX.com"
);
   // private /public key pair
$key = openssl_pkey_new();
$cert = openssl_csr_new($dom, $key, array('digest_alg' => 'sha256'));
$r_cert = openssl_csr_sign($cert, null, $key, 365);
openssl_x509_export($r_cert, $x_509_certificate);
echo $res_pubkey = openssl_pkey_get_public($x_509_certificate);
?>

Output

Resource id #7

Example with .pem file-

<?php
   $dom = array(
      "countryName" => "IN",
"stateOrProvinceName" => "Delhi",
"localityName" => "addr1",
"organizationName" => "addr2",
"organizationalUnitName" => "addr3",
"commonName" => "www.XXX.com",
"emailAddress" => "test@XXX.com"
);
$pr_k = openssl_pkey_new();
// Generating certificate
$csr_demo = openssl_csr_new($dn, $pr_k, array('digest_alg' => 'sha256'));
$cert = openssl_csr_sign($csr_demo, null, $pr_k, 365);
openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/x_509.pem');
echo $res_pubkey = openssl_pkey_get_public(file_get_contents('C:/xampp/htdocs/modules/openssl/x_509.pem'));
?>

Output-

Resource id #7

openssl_pkey_export_to_file()

his function will allow you to export the given key to the file. This function will keep the key in pem format which used to store crypto keys and certificates. This function will take four parameters-

Syntax

openssl_pkey_export_to_file ( mixed $key , string $outfilename [, string $passphrase [, array $configargs ]] ) : bool
  • Key- that you want to export
  • Outfilename- to which file to want to export.
  • Passphrase- it is the password to keep your file safe.
  • Configargs- details to generate a public/private key pair. Below are the keys that can be used for configargs- digest_alg, x509_extensions, req_extensions, private_key_bits, private_key_type, encrypt_type, encrypt_key_cipher, curve_name, config.

If the function runs successfully it will return a true value.

Example

<?php
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/keytest.pem');
?>

Output

-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDaqNK97A+mL9Xu
IDt3rz9yfFUvrLcDEvsDa9JsjQByJVbdRtaNl6nfg91/LfKO8zAeG8srd292jcYk
9MgBhkpMCHvF/QhWjA4IdPLdWHCbYfjF/LHmo/z022/FqTnjQtFws992/ClhZdo6
kpDlU/H2lmbnCwrsqHlqcQ7bzBgC5U5SW0t3A03PSqxQTIFPOHi1Yx1Il5jH/H11
6UXDKogAWsseRpdwVdsCy6Wj3rkybr1pr7CDkHSS49MAvJ4e6xhs+je12lrtyChR
ZTIYLICzEG7a1n0BPGAI1bQcivHXNipUkAYFn221gKRuB+9SQvC3VKbNXy8Oc7N9
HEahD8S3AgMBAAECggEBAKzEU68og7zlcvzxjsskNtd4kb5Xk0rkhlzPprWKO131
TssLm57IxLoMcMh6P3rff5dqkn9HoVRk9LhiiF1cA/xLf7CSGzJ2+ueHsBVgOaks
IeodnVsFG2tEru3YphqAwwdvuBNFblS8q084WzA3waj6cVgAi6MuArEtn3XfruEp
Yryc4Y1I1SB92x4y85tZ/PcomumPH0djKQeuhzy7f7GloJRfdshNENRbkdLc65N5
j8hy7WxMSa0dpJ3ZJMmgNfek9nALntSZfOsHGMZ/Wog8eV6+HzCwqqrMkR15pZI1
HqvVszU1iwoUJvlGoxInJOqJ2c6lBSBOBBR8DuuQixECgYEA+8RKXcw0U3VU8zJO
NTFzSDEtFYKZ5Bg4IPaYSTSo/ojiL3VrLeocRq3/2zdeCw8wx9eNZbcBW93lWVxK
q2G0X4XgonorEEONBvL9aE/D7wBCMYPWDXd/KQVZW8CPwcy10g2oIi3SqbcTQ/gT
fcmcHAQD2wVgo9XBlg24ESAP01MCgYEA3lYGasOvDweca5GCiP4m1oOH605haIUU
f5CDWXbZ6QjcoUQQB0CoDtTl3QpBd3KGbd+PbqU8xb44+LhrVIsjUyZs6k+eLACe
Dufzq00mIRSl/TZ0R3q17lAMmxId9QramDScpmqqqXonpOpdEoonThynhLyANgX3
eYGLXeqaII0CgYBPVi/JFwx2MEcwy+1xPcACQ9zdJmawRiGJ4atjhkCq1R/RrMK1
mUyHyVUTE4ODIKpSj05zexPmiyo22qp9DzDz2RBMowrm+SJ7yh6ovFoV+pLhX5YY
cEuV9aWPEEM84vF42+zbuGzmJlbf2FDsFpgnC+zbG/q0Jiv2ySPz4ZKbGQKBgQDM
ek9ih1+LshNAts1Xkm5DoSoy1Z4uUx48B7tVX0If2N+YjRE0qlklctWIiXMWGMTb
bdzrBJq0vjKFRI6pbWFqio9mmxy8GUFEMjzekZB8ohHao+cjCg8iAorlXy8f+wB5
NQHQ547XWRn2yPgaIebuJtpF8Fr11Fz6aZK0KBvhzQKBgGRwuxq6IhIROupoDRpU
RHuqICeQQYcf7Cfk7+ZyYJnA1fbOowj4Q5zvbWa6N2Ygyq2KIl0P5YL4Atb7aRKS
e6ol8lIKZM9ysbS+wR0OhhTJs/9CqpgvDbYNQFiaVZtGRpSNCxHkhn0cAR7lzK4P
ROQC7p9zXJhAmzE8/hTD9eaH
-----END PRIVATE KEY-----

Example using PEM file

<?php
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/keytest.pem');
//using .pem file 
$test_pri = openssl_get_privatekey(file_get_contents('C:/xampp/htdocs/modules/openssl/keytest.pem'));
if ($test_pri === false) {
var_dump(openssl_error_string());
} else {
$key_data = openssl_pkey_get_details($test_pri);
print_r($key_data["key"]);
}
?>

openssl_private_encrypt()- this function uses the private key to encrypt the data. Then the encrypted data can be decrypted using openssl_private_decrypt() function. Encrypt function takes four parameters-data encrypted, key padding.

Syntax

openssl_private_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool
  • Data is the provided data
  • Encrypted will keep the encrypted data
  • Key is the private key to encrypt the data
  • Padding – OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING can be applied here.

Example

<?php
   // To encrpt data
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
$test_data = 'Welcome';
openssl_private_encrypt ($test_data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING);
echo $crypted;
?>

Output

����Z甌�3�g[.zT�J�tn��g�M�P>���7U���k�vJ�@/��ɥ�����U�j���ː�RC��bQGQ: �NN��������Z���#J0J ��C�t�SC޳

openssl_public_encrypt()

This function will uses the public key to encrypt the data. This function is the same as the openssl_provate_encrypt but the key uses here is the public key. This function will take the same four parameters- data, encrypt, key and padding (OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.)

Syntax

openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

Example

<?php
   // Private Key
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
// Public Key
$dom = array(
"countryName" => "IN",
"stateOrProvinceName" => "delhi",
"localityName" => "addr1",
"organizationName" => "addr2",
"organizationalUnitName" => "addr3",
"commonName" => "www.XXX.com",
"emailAddress" => "test@XXX.com"
);
$t_cer = openssl_csr_new($dom, $pri_key);
$t_cer = openssl_csr_sign($t_cer, null, $pri_key, 365);
openssl_x509_export_to_file($t_cer, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
// encrypting data
$test_data = 'Welcome';
$isvalid = openssl_public_encrypt ($test_data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data encryption : ".$crypted;
?>

Output

Data encryption : ��E �wC�ݭ�+c��f*��o���W�7�EW��$�p�.rng�_N��A1���2Uݴ~s�ap۳)w��=� ��#���g;���u��_%�Z�
openssl_public_decrypt()

This function will use the public key to decrypt the encrypted data. This function will take the same four parameters as the encrypt functions- data, decrypted, key and padding (OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING.).

Syntax

openssl_public_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

Example

<?php
   // Private Key
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
// encrypting data
$test_data = 'Welcome';
$isvalid = openssl_public_encrypt ($test_data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data encryption : ".$crypted;
// Public Key
$dom = array(
"countryName" => "IN",
"stateOrProvinceName" => "delhi",
"localityName" => "addr1",
"organizationName" => "addr2",
"organizationalUnitName" => "addr3",
"commonName" => "www.XXX.com",
"emailAddress" => "test@XXX.com"
);
$t_cer = openssl_csr_new($dom, $pri_key);
$t_cer = openssl_csr_sign($t_cer, null, $pri_key, 365);
openssl_x509_export_to_file($t_cer, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
if ($isvalid) {
openssl_public_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data decryption: ".$decrypted;
}
?>

Output

Data encryption : k���G��7)xy{�N3Г�x<�J^�gd��Ψ�I?{��<�Ws3�mW$��h��(F;tJ�J�W��|�9L�vL��xF���f����,�(N�ΰ��n���Y%Oo,�2����Qh��G�|-����}���1�6Tm�qS�wb���[�i�-r�F��rQhZ���$�
Data decryption: Welcome

openssl_private_decrypt()- this function will use the private key to decrypt the encrypted data. This function will also take fours parameters- data, decrypted, key and padding (OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING)

Syntax

openssl_private_decrypt ( string $data , string &$decrypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool

Example

<?php
   // Private Key
$pri_key = openssl_pkey_new();
openssl_pkey_export_to_file($pri_key, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
// Public Key
$dom = array(
"countryName" => "IN",
"stateOrProvinceName" => "delhi",
"localityName" => "addr1",
"organizationName" => "addr2",
"organizationalUnitName" => "addr3",
"commonName" => "www.XXX.com",
"emailAddress" => "test@XXX.com"
);
$t_cer = openssl_csr_new($dom, $pri_key);
$t_cer = openssl_csr_sign($t_cer, null, $pri_key, 365);
openssl_x509_export_to_file($t_cer, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
// encrypting data
$test_data = 'Welcome';
$isvalid = openssl_public_encrypt ($test_data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data encryption : ".$crypted;
if ($isvalid) {
openssl_public_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data decryption : ".$decrypted;
}
?>

Output

Data encryption : L�_}{�E*?���9[w����7p �\ϸI�?ݟ'��ݹ�n��!����ɿ�*����Xcw�����Ւ�)��/��{��!j�L��I*Ï"9eV�9�=Y\�m�i䁦�M(�0PJ���Ԇ�9��C�`�a�ݧ
Data decryption : Welcome

Leave a Reply

Your email address will not be published. Required fields are marked *