aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/comments/backend/classes/encryption.php
blob: 2e21f48c7e358ac37fd3bc8f4bb1df1315585b6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<?php namespace HashOver;

// Copyright (C) 2010-2018 Jacob Barkdull
// This file is part of HashOver.
//
// HashOver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// HashOver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with HashOver.  If not, see <http://www.gnu.org/licenses/>.


// Encryption methods
class Encryption
{
	protected $prefix;
	protected $cost = '$10$';
	protected $encryptionHash;
	protected $ivSize;
	protected $cipher = 'aes-128-cbc';
	protected $options;
	protected $alphabet = 'aAbBcCdDeEfFgGhHiIjJkKlLmM.nNoOpPqQrRsStTuUvVwWxXyYzZ/0123456789';

	public function __construct ($encryption_key)
	{
		// Throw exception if encryption key isn't at least 8 characters long
		if (mb_strlen ($encryption_key, '8bit') < 8) {
			throw new Exception ('Encryption key must by at least 8 characters long.');
		}

		// Blowfish prefix
		$this->prefix = (version_compare (PHP_VERSION, '5.3.7') < 0) ? '$2a' : '$2y';

		// OpenSSL raw output/options
		$this->options = defined ('OPENSSL_RAW_DATA') ? OPENSSL_RAW_DATA : true;

		// SHA-256 hash array
		$this->encryptionHash = str_split (hash ('sha256', $encryption_key));

		// OpenSSL cipher IV
		$this->ivSize = openssl_cipher_iv_length ($this->cipher);
	}

	// Creates Blowfish hash for passwords
	public function createHash ($string)
	{
		// Alphanumeric character array
		$alphabet = str_split ($this->alphabet);

		// Shuffle alphanumeric character array as to randomize it
		shuffle ($alphabet);

		// Initial salt
		$salt = '';

		// Generate random 20 character alphanumeric string
		foreach (array_rand ($alphabet, 20) as $character) {
			$salt .= $alphabet[$character];
		}

		// Blowfish hash
		$hash = crypt ($string, $this->prefix . $this->cost . $salt . '$$');

		// Return hashed string
		return $hash;
	}

	// Creates Blowfish hash with salt from supplied hash
	public function verifyHash ($string, $compare)
	{
		// Split string by dollar sign
		$parts = explode ('$', $compare);

		// Hash salt
		$salt = !empty ($parts[3]) ? $parts[3] : '';

		// Encryption string as Blowfish hash
		$hash = crypt ($string, $this->prefix . $this->cost . $salt . '$$');

		// Returns true if both match
		return ($hash === $compare);
	}

	// Generates a random encryption key
	public function createKey ($string)
	{
		// Shuffle alphanumeric character array as to randomize it
		shuffle ($string);

		// Initial array keys
		$keys = array ();

		// Initial key
		$key = '';

		// Generate random string from encryption key SHA-256 hash
		for ($k = 0; $k < 16; $k++) {
			// Add encryption key character index to keys array
			$keys[] = array_search ($string[$k], $this->encryptionHash);

			// Add encryption key character to key
			$key .= $string[$k];
		}

		// Return random string and list of encryption hash array keys
		return array (
			'key' => $key,
			'keys' => join (',', $keys)
		);
	}

	// OpenSSL encrypt with random key from SHA-256 hash for e-mails
	public function encrypt ($string)
	{
		// Get a random encryption key
		$key_pair = $this->createKey ($this->encryptionHash);

		// Get pseudo-random bytes for OpenSSL IV
		$iv = openssl_random_pseudo_bytes ($this->ivSize);

		// OpenSSL encrypt using random encryption key
		$ciphertext = openssl_encrypt (
			$string,
			$this->cipher,
			$key_pair['key'],
			$this->options,
			$iv
		);

		// Return encrypted value and list of encryption hash array keys
		return array (
			'encrypted' => base64_encode ($iv . $ciphertext),
			'keys' => $key_pair['keys']
		);
	}

	// Decrypt OpenSSL encrypted string
	public function decrypt ($string, $keys)
	{
		// Return false if string or keys is empty
		if (empty ($string) or empty ($keys)) {
			return false;
		}

		// Initial key
		$key = '';

		// Split keys string into array
		$keys = explode (',', $keys);

		// Retrieve random key from array
		foreach ($keys as $value) {
			// Cast key to integer
			$hash_key = (int)($value);

			// Give up if any array value isn't valid
			if (!isset ($this->encryptionHash[$hash_key])) {
				return '';
			}

			// Add character to decryption key
			$key .= $this->encryptionHash[$hash_key];
		}

		// Decode base64 encoded string
		$decode = base64_decode ($string, true);

		// Setup OpenSSL IV
		$iv = mb_substr ($decode, 0, $this->ivSize, '8bit');

		// Setup OpenSSL cipher text
		$full_length = mb_strlen ($decode, '8bit');
		$deciphertext = mb_substr ($decode, $this->ivSize, $full_length, '8bit');

		// Return OpenSSL decrypted string
		return openssl_decrypt (
			$deciphertext,
			$this->cipher,
			$key,
			$this->options,
			$iv
		);
	}
}