· 7 years ago · Dec 11, 2018, 05:48 PM
1<?php
2/*
3 * Title: Grazely Encryption Class
4 * Author: Caleb Mingle (caleb@mingle-graphics.com).
5 * Date: 07/07/11
6 */
7
8class Encryption {
9 private static $_instance; // Instance of this class.
10
11 private $_cipher; // Cipher Storage
12 private $_iv; // Public Key (IV).
13 private $_key; // Private Key (Secret Key / Bookmark Key)
14
15 public function __construct() {
16 $this->_cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); // Cipher object. 128bit block size.
17 }
18
19 /*
20 * Return instance of the class.
21 */
22 public static function model() {
23 if (!isset(self::$instance)) {
24 $c = __CLASS__;
25 self::$_instance = new $c;
26 }
27
28 return self::$_instance;
29 }
30
31 /*
32 * Set the public key (IV).
33 */
34 public function setIV($iv) {
35 $this->_iv = $this->hex2bin($iv);
36 }
37
38 /*
39 * Set the private key (secret_key).
40 */
41 public function setKey($key) {
42 $this->_key = md5($key . $this->_iv);
43 }
44
45 /*
46 * Generate an IV (public key).
47 */
48 public function createIV() {
49 $iv = mcrypt_create_iv(16, MCRYPT_RAND);
50
51 return bin2hex($iv);
52 }
53
54 /*
55 * Encrypt a string (plain_text) to cipher_text.
56 */
57 public function encrypt($plain_text) {
58 if(empty($plain_text)) {
59 return "";
60 }
61
62 if(mcrypt_generic_init($this->_cipher, $this->_key, $this->_iv) != -1) {
63 $cipher_text = mcrypt_generic($this->_cipher, $plain_text);
64
65 mcrypt_generic_deinit($this->_cipher);
66
67 return bin2hex($cipher_text);
68 }
69 }
70
71 public function decrypt($cipher_text) {
72 if(empty($cipher_text)) {
73 return "";
74 }
75
76 if(!empty(Yii::app()->user->encryption_disabled)) {
77 return "xxxxxx";
78 }
79
80 if(mcrypt_generic_init($this->_cipher, $this->_key, $this->_iv) != -1) {
81 $plain_text = mdecrypt_generic($this->_cipher, $this->hex2bin($cipher_text));
82
83 mcrypt_generic_deinit($this->_cipher);
84
85 return trim($plain_text); // Removes extra whitespace
86 }
87 }
88
89 public function checkKey($key, $user_model = '') {
90 $user_model = (empty($user_model)) ? User::model()->currentUser() : $user_model;
91
92 $encrypted_string = $user_model->encrypted_string;
93 $public_key = $user_model->IV;
94
95 $this->setIV($public_key);
96 $this->setKey($key);
97
98 if($this->encrypt($user_model->id) == $encrypted_string) {
99 return true;
100 } else {
101 return false;
102 }
103 }
104
105 private function hex2bin($data) {
106 $len = strlen($data);
107 $newdata = "";
108
109 for($i = 0; $i < $len; $i += 2) {
110 $newdata .= pack("C",hexdec(substr($data,$i,2)));
111 }
112
113 return $newdata;
114 }
115
116 public function currentUser() {
117 $user_model = User::model()->currentUser();
118
119 if(!empty(Yii::app()->user->encryption_key)) {
120 $encryption_key = Yii::app()->user->encryption_key;
121
122 $this->setIV($user_model->IV);
123 $this->setKey($encryption_key);
124 }
125
126 return $this;
127 }
128
129}