PHP OpenSSL Functions

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

    In this article, we will discuss PHP OpenSSL functions, but before that, let's know what  SSL is.

    SSL Certificate

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

    How to Install OpenSSL in PHP?

    PHP includes the SSL module by default. All you have to do is to activate it by removing the (;) from the start of -;extension=php_openssl.dll in the php.ini file. After making the changes, you have to restart Apache HTTP Server and make sure that the changes are reflected. You can save the 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 OpenSSL on Windows:

    • Right-click on My Computer and then go to settings.
    • 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 environment settings, then go to the command prompt and run the following command:

    openssl version -a

    You will get the 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"

    PHP OpenSSL Functions

    PHP supports the following OpenSSL functions:

    1. openssl_pkey_new()

    A resource identifier will be returned that has new private and public key pairs. You can use the 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, and curve_name, config.

    Syntax

    openssl_pkey_new ([ array $configargs ] ) : resource

    Code 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

    2. openssl_pkey_get_private()

    This function will provide you with the private key and its details. This function will take two parameters, key, and passphrase. The 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 identifiers if the command executes without any error.

    Syntax

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

    Code 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

    The openssl_pkey_get_public() 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, and 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.

    Code 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 the .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

    3. openssl_pkey_export_to_file()

    This function will allow you to export the given key to the file. It will keep the key in the .pem format that is 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
    1. Key - The key that you want to export.
    2. Outfilename - To the file you want to export.
    3. Passphrase - It is the password to keep your file safe.
    4. Configargs - Details to generate a public/private key pair. Below are the keys that can be used for configargs:
      1. digest_alg,
      2. x509_extensions,
      3. req_extensions,
      4. private_key_bits,
      5. private_key_type,
      6. encrypt_type,
      7. encrypt_key_cipher,
      8. curve_name, and
      9. config.

    If the function runs successfully, it will return a true value. Code 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-----

    Code Example Using the 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"]);
    }
    ?>

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

    Syntax

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

    Code 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?

    4. openssl_public_encrypt()

    This function will use the public key to encrypt the data. It is the same as the openssl_private_encrypt() function, but the key used here is a public key. This function will take the same four parameters:

    1. Data
    2. Encrypt
    3. Key
    4. Padding - OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, and OPENSSL_NO_PADDING.

    Syntax

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

    Code 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, namely data, decrypted, key, and padding (OPENSSL_PKCS1_PADDING and OPENSSL_NO_PADDING).

    Syntax

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

    Code 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 four parameters, which are data, decrypted, key, and padding (OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, and OPENSSL_NO_PADDING).

    Syntax

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

    Code 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

    Conclusion

    That was all about PHP OpenSSL functions. You need to know about them if you are to work in networking. As you can see, there are several of them. You need to choose one depending on your requirements.

    People are also reading: