Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

Encryption using openssl

The following script is useful to encrypt small strings using public key and enables the data decryption via the private key. The string size (2048/8-11 bites) or around 245 symbols depending on the encoding. The class also allows generation of key pairs.
<?php
/**
 * This class allowes generation of public and private key pairs 
 * @package Sami's encrypt class
 * @version $Id: samis_encrypt.class.php v.1.1 2018-05-12 10:27:00 $
 * @author Samuil Banti https://www.samiwell.eu/
 * @copyright (C) 2018 - Samuil Banti
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
class samis_encrypt {

    /**
    * Generate the public and private keys.
    * @return array - the key pair.
    */
    function generate_key_pair() {
	$result = openssl_pkey_new(array('private_key_bits' => 2048));
	openssl_pkey_export($result, $privateKey); // Extract the private key
	$publicKey = openssl_pkey_get_details($result); // Extract the public key
	return ['public' => $publicKey['key'], 'private' => $privateKey];
    }

    /**
    * Encrypt string using public key.
    * @param string $string - The string to encrypt.
    * @param mixed $public_key - The public key as string or as file path.
    * @return string $encrypted_string - The encrypted string.
    */
    function encrypt($string, $public_key) {
	if(is_file($public_key)) {
	    $public_key = file_get_contents($public_key);
	}
	$encrypted_string = '';
	openssl_public_encrypt($string, $encrypted_string, $public_key);
	return $encrypted_string;
    }

    /**
    * Decrypt string using private key.
    * @param string $encrypted_string - The encrypted string.
    * @param mixed $private_key - The private key as string or as file path.
    * @return string $decrypted_string - The decrypted string.
    */
    function decrypt($encrypted_string, $private_key) {
	if(is_file($private_key)) {
	    $private_key = file_get_contents($private_key);
	}
	$decrypted_string = '';
	openssl_private_decrypt($encrypted_string, $decrypted_string, $private_key);
	return $decrypted_string;
    }

}
Download...