PHP Classes

File: encrypt.class.php

Recommend this page to a friend!
  Classes of Grigori Kochanov   gksEncrypt   encrypt.class.php   Download  
File: encrypt.class.php
Role: Class source
Content type: text/plain
Description: gksEncrypt class and an exception class
Class: gksEncrypt
Encrypt and decrypt data asymmetrically
Author: By
Last change:
Date: 16 years ago
Size: 5,425 bytes
 

Contents

Class file image Download
<?php

class gksEncrypt {
/**
 * Public key used for encryption
 *
 * @var resource
 */
private $public_key;

/**
 * Private key used for encryption
 *
 * @var resource
 */
private $private_key;

/**
 * Check the server configuration
 *
 */
function __construct($public_key=null){
    if (!
in_array('openssl',get_loaded_extensions())){
        throw new
gksEncryptException(560);
    }
    if (
$public_key){
       
$this->setPublicKey($public_key);
    }
}

/**
 * Assign the public key to encrypt
 *
 * @param string $key
 */
function setPublicKey($key){
   
$this->public_key = trim($key);
}

/**
 * Assign the private key to encrypt
 *
 * @param string $key
 */
function setPrivateKey($key){
   
$this->private_key = trim($key);
}

/**
 * Assign the private key to encrypt
 *
 * @param string $filename
 */
function getPublicKeyFromFile($filename){
    if (!
is_file($filename) || !is_readable($filename)){
        throw new
gksEncryptException(220);
    }
   
$this->setPublicKey(file_get_contents($filename));
}

/**
 * Assign the private key to encrypt
 *
 * @param string $filename
 */
function getPrivateKeyFromFile($filename){
    if (!
is_file($filename) || !is_readable($filename)){
        throw new
gksEncryptException(220);
    }
   
$this->setPrivateKey(file_get_contents($filename));
}

/**
 * Encrypt the data
 *
 * @param string $data
 * @param string $public_key=''
 * @return string
 */
function encrypt($data,$public_key=''){
    if (!
$public_key){
       
$public_key = $this->public_key;
    }
    if (!
$public_key){
        throw new
gksEncryptException(564);
    }
   
$result = @openssl_public_encrypt($data,$crypted,$public_key);
    if (!
$result){
       
$err = error_get_last();
        throw new
gksEncryptException(562,$err['message']);
    }
    return
$crypted;
}

function
decrypt($data,$private_key=''){
    if (!
$private_key){
       
$private_key = $this->private_key;
    }
    if (!
$private_key){
        throw new
gksEncryptException(564);
    }
   
$result = @openssl_private_decrypt($data,$dec,$private_key);
    if (!
$result){
       
$err = error_get_last();
        throw new
gksEncryptException(563,$err['message']);
    }
    return
$dec;
}

/**
 * Generate new private/public key pair
 * returns through the
 *
 * @param $bits_count int
 * @return array ('private'=>private_key string,'public'=>public_key string)
 */
static function generateKeys($bits_count=1024){
    if (!
function_exists('openssl_pkey_get_details')){
        throw new
gksEncryptException(565);
    }
   
//generate public key
   
$params = array('digest_alg' => 'sha1','private_key_type'=>OPENSSL_KEYTYPE_RSA,'encrypt_key'=>false);
   
$private_key = openssl_pkey_new($params);
   
openssl_pkey_export($private_key,$private_key_string);
   
   
//generate certificate (to get a public key from it)
   
$csr = openssl_csr_new(array(), $private_key);
   
$cert = openssl_csr_sign($csr, null, $private_key, 1);
   
openssl_x509_export($cert, $str_cert);
   
   
//get the public key from the certificate
   
$public_key = openssl_pkey_get_public($str_cert);
   
//get the PEM-encoded public key
   
$public_key_details = openssl_pkey_get_details($public_key);
   
$public_key_string = $public_key_details['key'];
   
    return array(
'private'=>$private_key_string,'public'=>$public_key_string);
}

// class end
}


class
gksEncryptException extends Exception implements gksException{

/**
 * Default error messages for the database errors
 *
 * @var array
 */
static private $error_codes=array(
220=>'Error opening file for reading',
560=>'OpenSSL not installed',
561=>'Key invalid',
562=>'Encryption error',
563=>'Decryption error',
564=>'No key to use',
565=>'PHP 5.2 or later with OpenSSL support required to generate keys',
);

/**
 * Open ssl reported error message
 *
 * @var string
 */
public $openssl_error_message='';

/**
 * Exception constructor
 *
 * @param int $code - error code from $curl_exception_codes
 */
public function __construct($code,$ssl_error=''){
   
//allow the framework to redefine the error messages
   
if (class_exists('_Config',false) && isset(_Config::$errors_file) && file_exists(_Config::$errors_file)){
       
self::$error_codes = include(_Config::$errors_file);
    }
   
   
$message=self::$error_codes[$code];

   
parent::__construct($message, $code);

   
//set the error string
   
if ($ssl_error){
       
$this->openssl_error_message= (preg_match('~^(\w*\(\)) \[<a.*</a>]: (.*)~',$ssl_error,$found))
            ?
$found[1].': '.$found[2]
            :
$ssl_error;
    }
}

/**
 * Getter for a string prepared to write to the log
 *
 * @return string
 */
public function getLogMessage(){
   
$log_string= 'Exception: '.$this->getMessage().' ('.$this->getCode().')'."\n";
    if (
$this->openssl_error_message){
       
$log_string.='Error: '.$this->openssl_error_message."\n";
    }
   
$log_string.= 'TRACE:'."\n".$this->getTraceAsString()."\n";
    return
$log_string;
}

/**
 * returns the exception dump in the readable format
 *
 * @return string
 */
public function getHtmlMessage(){
   
$message = 'Exception: '. nl2br ($this->message);
   
$trace = 'TRACE: <br />'. nl2br ($this->getTraceAsString());
    if (
$this->openssl_error_message){
       
$message .= "<br />\r\nError message: ".nl2br($this->openssl_error_message);
    }
    return
'<p style="font-weignt: bold; padding: 10px;">'.$message."<br />\r\n".$trace.'</p>';
}
//class end
}