DiffieHellman.php
12.1 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Crypt
* @subpackage DiffieHellman
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: DiffieHellman.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* PHP implementation of the Diffie-Hellman public key encryption algorithm.
* Allows two unassociated parties to establish a joint shared secret key
* to be used in encrypting subsequent communications.
*
* @category Zend
* @package Zend_Crypt
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Crypt_DiffieHellman
{
/**
* Static flag to select whether to use PHP5.3's openssl extension
* if available.
*
* @var boolean
*/
public static $useOpenssl = true;
/**
* Default large prime number; required by the algorithm.
*
* @var string
*/
private $_prime = null;
/**
* The default generator number. This number must be greater than 0 but
* less than the prime number set.
*
* @var string
*/
private $_generator = null;
/**
* A private number set by the local user. It's optional and will
* be generated if not set.
*
* @var string
*/
private $_privateKey = null;
/**
* BigInteger support object courtesy of Zend_Crypt_Math
*
* @var Zend_Crypt_Math_BigInteger
*/
private $_math = null;
/**
* The public key generated by this instance after calling generateKeys().
*
* @var string
*/
private $_publicKey = null;
/**
* The shared secret key resulting from a completed Diffie Hellman
* exchange
*
* @var string
*/
private $_secretKey = null;
/**
* Constants
*/
const BINARY = 'binary';
const NUMBER = 'number';
const BTWOC = 'btwoc';
/**
* Constructor; if set construct the object using the parameter array to
* set values for Prime, Generator and Private.
* If a Private Key is not set, one will be generated at random.
*
* @param string $prime
* @param string $generator
* @param string $privateKey
* @param string $privateKeyType
* @return void
*/
public function __construct($prime, $generator, $privateKey = null, $privateKeyType = self::NUMBER)
{
$this->setPrime($prime);
$this->setGenerator($generator);
if ($privateKey !== null) {
$this->setPrivateKey($privateKey, $privateKeyType);
}
$this->setBigIntegerMath();
}
/**
* Generate own public key. If a private number has not already been
* set, one will be generated at this stage.
*
* @return Zend_Crypt_DiffieHellman
*/
public function generateKeys()
{
if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) {
$details = array();
$details['p'] = $this->getPrime();
$details['g'] = $this->getGenerator();
if ($this->hasPrivateKey()) {
$details['priv_key'] = $this->getPrivateKey();
}
$opensslKeyResource = openssl_pkey_new( array('dh' => $details) );
$data = openssl_pkey_get_details($opensslKeyResource);
$this->setPrivateKey($data['dh']['priv_key'], self::BINARY);
$this->setPublicKey($data['dh']['pub_key'], self::BINARY);
} else {
// Private key is lazy generated in the absence of PHP 5.3's ext/openssl
$publicKey = $this->_math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime());
$this->setPublicKey($publicKey);
}
return $this;
}
/**
* Setter for the value of the public number
*
* @param string $number
* @param string $type
* @return Zend_Crypt_DiffieHellman
*/
public function setPublicKey($number, $type = self::NUMBER)
{
if ($type == self::BINARY) {
$number = $this->_math->fromBinary($number);
}
if (!preg_match("/^\d+$/", $number)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
}
$this->_publicKey = (string) $number;
return $this;
}
/**
* Returns own public key for communication to the second party to this
* transaction.
*
* @param string $type
* @return string
*/
public function getPublicKey($type = self::NUMBER)
{
if ($this->_publicKey === null) {
require_once 'Zend/Crypt/DiffieHellman/Exception.php';
throw new Zend_Crypt_DiffieHellman_Exception('A public key has not yet been generated using a prior call to generateKeys()');
}
if ($type == self::BINARY) {
return $this->_math->toBinary($this->_publicKey);
} elseif ($type == self::BTWOC) {
return $this->_math->btwoc($this->_math->toBinary($this->_publicKey));
}
return $this->_publicKey;
}
/**
* Compute the shared secret key based on the public key received from the
* the second party to this transaction. This should agree to the secret
* key the second party computes on our own public key.
* Once in agreement, the key is known to only to both parties.
* By default, the function expects the public key to be in binary form
* which is the typical format when being transmitted.
*
* If you need the binary form of the shared secret key, call
* getSharedSecretKey() with the optional parameter for Binary output.
*
* @param string $publicKey
* @param string $type
* @return mixed
*/
public function computeSecretKey($publicKey, $type = self::NUMBER, $output = self::NUMBER)
{
if ($type == self::BINARY) {
$publicKey = $this->_math->fromBinary($publicKey);
}
if (!preg_match("/^\d+$/", $publicKey)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
}
if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) {
$this->_secretKey = openssl_dh_compute_key($publicKey, $this->getPublicKey());
} else {
$this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime());
}
return $this->getSharedSecretKey($output);
}
/**
* Return the computed shared secret key from the DiffieHellman transaction
*
* @param string $type
* @return string
*/
public function getSharedSecretKey($type = self::NUMBER)
{
if (!isset($this->_secretKey)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()');
}
if ($type == self::BINARY) {
return $this->_math->toBinary($this->_secretKey);
} elseif ($type == self::BTWOC) {
return $this->_math->btwoc($this->_math->toBinary($this->_secretKey));
}
return $this->_secretKey;
}
/**
* Setter for the value of the prime number
*
* @param string $number
* @return Zend_Crypt_DiffieHellman
*/
public function setPrime($number)
{
if (!preg_match("/^\d+$/", $number) || $number < 11) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number or too small: should be a large natural number prime');
}
$this->_prime = (string) $number;
return $this;
}
/**
* Getter for the value of the prime number
*
* @return string
*/
public function getPrime()
{
if (!isset($this->_prime)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('No prime number has been set');
}
return $this->_prime;
}
/**
* Setter for the value of the generator number
*
* @param string $number
* @return Zend_Crypt_DiffieHellman
*/
public function setGenerator($number)
{
if (!preg_match("/^\d+$/", $number) || $number < 2) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number greater than 1');
}
$this->_generator = (string) $number;
return $this;
}
/**
* Getter for the value of the generator number
*
* @return string
*/
public function getGenerator()
{
if (!isset($this->_generator)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('No generator number has been set');
}
return $this->_generator;
}
/**
* Setter for the value of the private number
*
* @param string $number
* @param string $type
* @return Zend_Crypt_DiffieHellman
*/
public function setPrivateKey($number, $type = self::NUMBER)
{
if ($type == self::BINARY) {
$number = $this->_math->fromBinary($number);
}
if (!preg_match("/^\d+$/", $number)) {
require_once('Zend/Crypt/DiffieHellman/Exception.php');
throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
}
$this->_privateKey = (string) $number;
return $this;
}
/**
* Getter for the value of the private number
*
* @param string $type
* @return string
*/
public function getPrivateKey($type = self::NUMBER)
{
if (!$this->hasPrivateKey()) {
$this->setPrivateKey($this->_generatePrivateKey(), self::BINARY);
}
if ($type == self::BINARY) {
return $this->_math->toBinary($this->_privateKey);
} elseif ($type == self::BTWOC) {
return $this->_math->btwoc($this->_math->toBinary($this->_privateKey));
}
return $this->_privateKey;
}
/**
* Check whether a private key currently exists.
*
* @return boolean
*/
public function hasPrivateKey()
{
return isset($this->_privateKey);
}
/**
* Setter to pass an extension parameter which is used to create
* a specific BigInteger instance for a specific extension type.
* Allows manual setting of the class in case of an extension
* problem or bug.
*
* @param string $extension
* @return void
*/
public function setBigIntegerMath($extension = null)
{
/**
* @see Zend_Crypt_Math
*/
require_once 'Zend/Crypt/Math.php';
$this->_math = new Zend_Crypt_Math($extension);
}
/**
* In the event a private number/key has not been set by the user,
* or generated by ext/openssl, a best attempt will be made to
* generate a random key. Having a random number generator installed
* on linux/bsd is highly recommended! The alternative is not recommended
* for production unless without any other option.
*
* @return string
*/
protected function _generatePrivateKey()
{
$rand = $this->_math->rand($this->getGenerator(), $this->getPrime());
return $rand;
}
}