PageRenderTime 31ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/system/expressionengine/third_party/updater/libraries/phpseclib/Crypt/RSA.php

https://bitbucket.org/studiobreakfast/sync
PHP | 2356 lines | 1171 code | 242 blank | 943 comment | 184 complexity | e53ca425873e88ddbc3a943002bf5bf0 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * Here's an example of how to encrypt and decrypt text with this library:
  9. * <code>
  10. * <?php
  11. * include('Crypt/RSA.php');
  12. *
  13. * $rsa = new Crypt_RSA();
  14. * extract($rsa->createKey());
  15. *
  16. * $plaintext = 'terrafrost';
  17. *
  18. * $rsa->loadKey($privatekey);
  19. * $ciphertext = $rsa->encrypt($plaintext);
  20. *
  21. * $rsa->loadKey($publickey);
  22. * echo $rsa->decrypt($ciphertext);
  23. * ?>
  24. * </code>
  25. *
  26. * Here's an example of how to create signatures and verify signatures with this library:
  27. * <code>
  28. * <?php
  29. * include('Crypt/RSA.php');
  30. *
  31. * $rsa = new Crypt_RSA();
  32. * extract($rsa->createKey());
  33. *
  34. * $plaintext = 'terrafrost';
  35. *
  36. * $rsa->loadKey($privatekey);
  37. * $signature = $rsa->sign($plaintext);
  38. *
  39. * $rsa->loadKey($publickey);
  40. * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
  41. * ?>
  42. * </code>
  43. *
  44. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  45. * of this software and associated documentation files (the "Software"), to deal
  46. * in the Software without restriction, including without limitation the rights
  47. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  48. * copies of the Software, and to permit persons to whom the Software is
  49. * furnished to do so, subject to the following conditions:
  50. *
  51. * The above copyright notice and this permission notice shall be included in
  52. * all copies or substantial portions of the Software.
  53. *
  54. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  55. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  56. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  57. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  58. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  59. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  60. * THE SOFTWARE.
  61. *
  62. * @category Crypt
  63. * @package Crypt_RSA
  64. * @author Jim Wigginton <terrafrost@php.net>
  65. * @copyright MMIX Jim Wigginton
  66. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  67. * @version $Id: RSA.php,v 1.19 2010/09/12 21:58:54 terrafrost Exp $
  68. * @link http://phpseclib.sourceforge.net
  69. */
  70. /**
  71. * Include Math_BigInteger
  72. */
  73. require_once('Math/BigInteger.php');
  74. /**
  75. * Include Crypt_Random
  76. */
  77. require_once('Crypt/Random.php');
  78. /**
  79. * Include Crypt_Hash
  80. */
  81. require_once('Crypt/Hash.php');
  82. /**#@+
  83. * @access public
  84. * @see Crypt_RSA::encrypt()
  85. * @see Crypt_RSA::decrypt()
  86. */
  87. /**
  88. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  89. * (OAEP) for encryption / decryption.
  90. *
  91. * Uses sha1 by default.
  92. *
  93. * @see Crypt_RSA::setHash()
  94. * @see Crypt_RSA::setMGFHash()
  95. */
  96. define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
  97. /**
  98. * Use PKCS#1 padding.
  99. *
  100. * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  101. * compatability with protocols (like SSH-1) written before OAEP's introduction.
  102. */
  103. define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
  104. /**#@-*/
  105. /**#@+
  106. * @access public
  107. * @see Crypt_RSA::sign()
  108. * @see Crypt_RSA::verify()
  109. * @see Crypt_RSA::setHash()
  110. */
  111. /**
  112. * Use the Probabilistic Signature Scheme for signing
  113. *
  114. * Uses sha1 by default.
  115. *
  116. * @see Crypt_RSA::setSaltLength()
  117. * @see Crypt_RSA::setMGFHash()
  118. */
  119. define('CRYPT_RSA_SIGNATURE_PSS', 1);
  120. /**
  121. * Use the PKCS#1 scheme by default.
  122. *
  123. * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  124. * compatability with protocols (like SSH-2) written before PSS's introduction.
  125. */
  126. define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
  127. /**#@-*/
  128. /**#@+
  129. * @access private
  130. * @see Crypt_RSA::createKey()
  131. */
  132. /**
  133. * ASN1 Integer
  134. */
  135. define('CRYPT_RSA_ASN1_INTEGER', 2);
  136. /**
  137. * ASN1 Sequence (with the constucted bit set)
  138. */
  139. define('CRYPT_RSA_ASN1_SEQUENCE', 48);
  140. /**#@-*/
  141. /**#@+
  142. * @access private
  143. * @see Crypt_RSA::Crypt_RSA()
  144. */
  145. /**
  146. * To use the pure-PHP implementation
  147. */
  148. define('CRYPT_RSA_MODE_INTERNAL', 1);
  149. /**
  150. * To use the OpenSSL library
  151. *
  152. * (if enabled; otherwise, the internal implementation will be used)
  153. */
  154. define('CRYPT_RSA_MODE_OPENSSL', 2);
  155. /**#@-*/
  156. /**#@+
  157. * @access public
  158. * @see Crypt_RSA::createKey()
  159. * @see Crypt_RSA::setPrivateKeyFormat()
  160. */
  161. /**
  162. * PKCS#1 formatted private key
  163. *
  164. * Used by OpenSSH
  165. */
  166. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
  167. /**
  168. * PuTTY formatted private key
  169. */
  170. define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1);
  171. /**
  172. * XML formatted private key
  173. */
  174. define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2);
  175. /**#@-*/
  176. /**#@+
  177. * @access public
  178. * @see Crypt_RSA::createKey()
  179. * @see Crypt_RSA::setPublicKeyFormat()
  180. */
  181. /**
  182. * Raw public key
  183. *
  184. * An array containing two Math_BigInteger objects.
  185. *
  186. * The exponent can be indexed with any of the following:
  187. *
  188. * 0, e, exponent, publicExponent
  189. *
  190. * The modulus can be indexed with any of the following:
  191. *
  192. * 1, n, modulo, modulus
  193. */
  194. define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3);
  195. /**
  196. * PKCS#1 formatted public key
  197. */
  198. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 4);
  199. /**
  200. * XML formatted public key
  201. */
  202. define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5);
  203. /**
  204. * OpenSSH formatted public key
  205. *
  206. * Place in $HOME/.ssh/authorized_keys
  207. */
  208. define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6);
  209. /**#@-*/
  210. /**
  211. * Pure-PHP PKCS#1 compliant implementation of RSA.
  212. *
  213. * @author Jim Wigginton <terrafrost@php.net>
  214. * @version 0.1.0
  215. * @access public
  216. * @package Crypt_RSA
  217. */
  218. class Crypt_RSA {
  219. /**
  220. * Precomputed Zero
  221. *
  222. * @var Array
  223. * @access private
  224. */
  225. var $zero;
  226. /**
  227. * Precomputed One
  228. *
  229. * @var Array
  230. * @access private
  231. */
  232. var $one;
  233. /**
  234. * Private Key Format
  235. *
  236. * @var Integer
  237. * @access private
  238. */
  239. var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  240. /**
  241. * Public Key Format
  242. *
  243. * @var Integer
  244. * @access public
  245. */
  246. var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
  247. /**
  248. * Modulus (ie. n)
  249. *
  250. * @var Math_BigInteger
  251. * @access private
  252. */
  253. var $modulus;
  254. /**
  255. * Modulus length
  256. *
  257. * @var Math_BigInteger
  258. * @access private
  259. */
  260. var $k;
  261. /**
  262. * Exponent (ie. e or d)
  263. *
  264. * @var Math_BigInteger
  265. * @access private
  266. */
  267. var $exponent;
  268. /**
  269. * Primes for Chinese Remainder Theorem (ie. p and q)
  270. *
  271. * @var Array
  272. * @access private
  273. */
  274. var $primes;
  275. /**
  276. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  277. *
  278. * @var Array
  279. * @access private
  280. */
  281. var $exponents;
  282. /**
  283. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  284. *
  285. * @var Array
  286. * @access private
  287. */
  288. var $coefficients;
  289. /**
  290. * Hash name
  291. *
  292. * @var String
  293. * @access private
  294. */
  295. var $hashName;
  296. /**
  297. * Hash function
  298. *
  299. * @var Crypt_Hash
  300. * @access private
  301. */
  302. var $hash;
  303. /**
  304. * Length of hash function output
  305. *
  306. * @var Integer
  307. * @access private
  308. */
  309. var $hLen;
  310. /**
  311. * Length of salt
  312. *
  313. * @var Integer
  314. * @access private
  315. */
  316. var $sLen;
  317. /**
  318. * Hash function for the Mask Generation Function
  319. *
  320. * @var Crypt_Hash
  321. * @access private
  322. */
  323. var $mgfHash;
  324. /**
  325. * Length of MGF hash function output
  326. *
  327. * @var Integer
  328. * @access private
  329. */
  330. var $mgfHLen;
  331. /**
  332. * Encryption mode
  333. *
  334. * @var Integer
  335. * @access private
  336. */
  337. var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  338. /**
  339. * Signature mode
  340. *
  341. * @var Integer
  342. * @access private
  343. */
  344. var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  345. /**
  346. * Public Exponent
  347. *
  348. * @var Mixed
  349. * @access private
  350. */
  351. var $publicExponent = false;
  352. /**
  353. * Password
  354. *
  355. * @var String
  356. * @access private
  357. */
  358. var $password = '';
  359. /**
  360. * Components
  361. *
  362. * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
  363. * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
  364. *
  365. * @see Crypt_RSA::_start_element_handler()
  366. * @var Array
  367. * @access private
  368. */
  369. var $components = array();
  370. /**
  371. * Current String
  372. *
  373. * For use with parsing XML formatted keys.
  374. *
  375. * @see Crypt_RSA::_character_handler()
  376. * @see Crypt_RSA::_stop_element_handler()
  377. * @var Mixed
  378. * @access private
  379. */
  380. var $current;
  381. /**
  382. * The constructor
  383. *
  384. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  385. * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  386. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  387. *
  388. * @return Crypt_RSA
  389. * @access public
  390. */
  391. function Crypt_RSA()
  392. {
  393. if ( !defined('CRYPT_RSA_MODE') ) {
  394. switch (true) {
  395. //case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):
  396. // define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  397. // break;
  398. default:
  399. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  400. }
  401. }
  402. $this->zero = new Math_BigInteger();
  403. $this->one = new Math_BigInteger(1);
  404. $this->hash = new Crypt_Hash('sha1');
  405. $this->hLen = $this->hash->getLength();
  406. $this->hashName = 'sha1';
  407. $this->mgfHash = new Crypt_Hash('sha1');
  408. $this->mgfHLen = $this->mgfHash->getLength();
  409. }
  410. /**
  411. * Create public / private key pair
  412. *
  413. * Returns an array with the following three elements:
  414. * - 'privatekey': The private key.
  415. * - 'publickey': The public key.
  416. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  417. * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  418. *
  419. * @access public
  420. * @param optional Integer $bits
  421. * @param optional Integer $timeout
  422. * @param optional Math_BigInteger $p
  423. */
  424. function createKey($bits = 1024, $timeout = false, $partial = array())
  425. {
  426. if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL ) {
  427. $rsa = openssl_pkey_new(array('private_key_bits' => $bits));
  428. openssl_pkey_export($rsa, $privatekey);
  429. $publickey = openssl_pkey_get_details($rsa);
  430. $publickey = $publickey['key'];
  431. if ($this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_PKCS1) {
  432. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  433. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  434. }
  435. return array(
  436. 'privatekey' => $privatekey,
  437. 'publickey' => $publickey,
  438. 'partialkey' => false
  439. );
  440. }
  441. static $e;
  442. if (!isset($e)) {
  443. if (!defined('CRYPT_RSA_EXPONENT')) {
  444. // http://en.wikipedia.org/wiki/65537_%28number%29
  445. define('CRYPT_RSA_EXPONENT', '65537');
  446. }
  447. if (!defined('CRYPT_RSA_COMMENT')) {
  448. define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');
  449. }
  450. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  451. // than 256 bits.
  452. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  453. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  454. }
  455. $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
  456. }
  457. extract($this->_generateMinMax($bits));
  458. $absoluteMin = $min;
  459. $temp = $bits >> 1;
  460. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  461. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  462. $temp = CRYPT_RSA_SMALLEST_PRIME;
  463. } else {
  464. $num_primes = 2;
  465. }
  466. extract($this->_generateMinMax($temp + $bits % $temp));
  467. $finalMax = $max;
  468. extract($this->_generateMinMax($temp));
  469. $generator = new Math_BigInteger();
  470. $generator->setRandomGenerator('crypt_random');
  471. $n = $this->one->copy();
  472. if (!empty($partial)) {
  473. extract(unserialize($partial));
  474. } else {
  475. $exponents = $coefficients = $primes = array();
  476. $lcm = array(
  477. 'top' => $this->one->copy(),
  478. 'bottom' => false
  479. );
  480. }
  481. $start = time();
  482. $i0 = count($primes) + 1;
  483. do {
  484. for ($i = $i0; $i <= $num_primes; $i++) {
  485. if ($timeout !== false) {
  486. $timeout-= time() - $start;
  487. $start = time();
  488. if ($timeout <= 0) {
  489. return array(
  490. 'privatekey' => '',
  491. 'publickey' => '',
  492. 'partialkey' => serialize(array(
  493. 'primes' => $primes,
  494. 'coefficients' => $coefficients,
  495. 'lcm' => $lcm,
  496. 'exponents' => $exponents
  497. ))
  498. );
  499. }
  500. }
  501. if ($i == $num_primes) {
  502. list($min, $temp) = $absoluteMin->divide($n);
  503. if (!$temp->equals($this->zero)) {
  504. $min = $min->add($this->one); // ie. ceil()
  505. }
  506. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  507. } else {
  508. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  509. }
  510. if ($primes[$i] === false) { // if we've reached the timeout
  511. if (count($primes) > 1) {
  512. $partialkey = '';
  513. } else {
  514. array_pop($primes);
  515. $partialkey = serialize(array(
  516. 'primes' => $primes,
  517. 'coefficients' => $coefficients,
  518. 'lcm' => $lcm,
  519. 'exponents' => $exponents
  520. ));
  521. }
  522. return array(
  523. 'privatekey' => '',
  524. 'publickey' => '',
  525. 'partialkey' => $partialkey
  526. );
  527. }
  528. // the first coefficient is calculated differently from the rest
  529. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  530. if ($i > 2) {
  531. $coefficients[$i] = $n->modInverse($primes[$i]);
  532. }
  533. $n = $n->multiply($primes[$i]);
  534. $temp = $primes[$i]->subtract($this->one);
  535. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  536. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  537. $lcm['top'] = $lcm['top']->multiply($temp);
  538. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  539. $exponents[$i] = $e->modInverse($temp);
  540. }
  541. list($lcm) = $lcm['top']->divide($lcm['bottom']);
  542. $gcd = $lcm->gcd($e);
  543. $i0 = 1;
  544. } while (!$gcd->equals($this->one));
  545. $d = $e->modInverse($lcm);
  546. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  547. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  548. // RSAPrivateKey ::= SEQUENCE {
  549. // version Version,
  550. // modulus INTEGER, -- n
  551. // publicExponent INTEGER, -- e
  552. // privateExponent INTEGER, -- d
  553. // prime1 INTEGER, -- p
  554. // prime2 INTEGER, -- q
  555. // exponent1 INTEGER, -- d mod (p-1)
  556. // exponent2 INTEGER, -- d mod (q-1)
  557. // coefficient INTEGER, -- (inverse of q) mod p
  558. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  559. // }
  560. return array(
  561. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  562. 'publickey' => $this->_convertPublicKey($n, $e),
  563. 'partialkey' => false
  564. );
  565. }
  566. /**
  567. * Convert a private key to the appropriate format.
  568. *
  569. * @access private
  570. * @see setPrivateKeyFormat()
  571. * @param String $RSAPrivateKey
  572. * @return String
  573. */
  574. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  575. {
  576. $num_primes = count($primes);
  577. $raw = array(
  578. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  579. 'modulus' => $n->toBytes(true),
  580. 'publicExponent' => $e->toBytes(true),
  581. 'privateExponent' => $d->toBytes(true),
  582. 'prime1' => $primes[1]->toBytes(true),
  583. 'prime2' => $primes[2]->toBytes(true),
  584. 'exponent1' => $exponents[1]->toBytes(true),
  585. 'exponent2' => $exponents[2]->toBytes(true),
  586. 'coefficient' => $coefficients[2]->toBytes(true)
  587. );
  588. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  589. // call _convertPublicKey() instead.
  590. switch ($this->privateKeyFormat) {
  591. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  592. $components = array();
  593. foreach ($raw as $name => $value) {
  594. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  595. }
  596. $RSAPrivateKey = implode('', $components);
  597. if ($num_primes > 2) {
  598. $OtherPrimeInfos = '';
  599. for ($i = 3; $i <= $num_primes; $i++) {
  600. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  601. //
  602. // OtherPrimeInfo ::= SEQUENCE {
  603. // prime INTEGER, -- ri
  604. // exponent INTEGER, -- di
  605. // coefficient INTEGER -- ti
  606. // }
  607. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  608. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  609. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  610. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  611. }
  612. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  613. }
  614. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  615. if (!empty($this->password)) {
  616. $iv = $this->_random(8);
  617. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  618. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  619. if (!class_exists('Crypt_TripleDES')) {
  620. require_once('Crypt/TripleDES.php');
  621. }
  622. $des = new Crypt_TripleDES();
  623. $des->setKey($symkey);
  624. $des->setIV($iv);
  625. $iv = strtoupper(bin2hex($iv));
  626. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  627. "Proc-Type: 4,ENCRYPTED\r\n" .
  628. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  629. "\r\n" .
  630. chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
  631. '-----END RSA PRIVATE KEY-----';
  632. } else {
  633. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  634. chunk_split(base64_encode($RSAPrivateKey)) .
  635. '-----END RSA PRIVATE KEY-----';
  636. }
  637. return $RSAPrivateKey;
  638. }
  639. }
  640. /**
  641. * Convert a public key to the appropriate format
  642. *
  643. * @access private
  644. * @see setPublicKeyFormat()
  645. * @param String $RSAPrivateKey
  646. * @return String
  647. */
  648. function _convertPublicKey($n, $e)
  649. {
  650. $modulus = $n->toBytes(true);
  651. $publicExponent = $e->toBytes(true);
  652. switch ($this->publicKeyFormat) {
  653. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  654. return array('e' => $e->copy(), 'n' => $n->copy());
  655. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  656. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  657. // string "ssh-rsa"
  658. // mpint e
  659. // mpint n
  660. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  661. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
  662. return $RSAPublicKey;
  663. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  664. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  665. // RSAPublicKey ::= SEQUENCE {
  666. // modulus INTEGER, -- n
  667. // publicExponent INTEGER -- e
  668. // }
  669. $components = array(
  670. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  671. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  672. );
  673. $RSAPublicKey = pack('Ca*a*a*',
  674. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  675. $components['modulus'], $components['publicExponent']
  676. );
  677. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  678. chunk_split(base64_encode($RSAPublicKey)) .
  679. '-----END PUBLIC KEY-----';
  680. return $RSAPublicKey;
  681. }
  682. }
  683. /**
  684. * Break a public or private key down into its constituant components
  685. *
  686. * @access private
  687. * @see _convertPublicKey()
  688. * @see _convertPrivateKey()
  689. * @param String $key
  690. * @param Integer $type
  691. * @return Array
  692. */
  693. function _parseKey($key, $type)
  694. {
  695. switch ($type) {
  696. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  697. if (!is_array($key)) {
  698. return false;
  699. }
  700. $components = array();
  701. switch (true) {
  702. case isset($key['e']):
  703. $components['publicExponent'] = $key['e']->copy();
  704. break;
  705. case isset($key['exponent']):
  706. $components['publicExponent'] = $key['exponent']->copy();
  707. break;
  708. case isset($key['publicExponent']):
  709. $components['publicExponent'] = $key['publicExponent']->copy();
  710. break;
  711. case isset($key[0]):
  712. $components['publicExponent'] = $key[0]->copy();
  713. }
  714. switch (true) {
  715. case isset($key['n']):
  716. $components['modulus'] = $key['n']->copy();
  717. break;
  718. case isset($key['modulo']):
  719. $components['modulus'] = $key['modulo']->copy();
  720. break;
  721. case isset($key['modulus']):
  722. $components['modulus'] = $key['modulus']->copy();
  723. break;
  724. case isset($key[1]):
  725. $components['modulus'] = $key[1]->copy();
  726. }
  727. return $components;
  728. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  729. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  730. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  731. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  732. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  733. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  734. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  735. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  736. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  737. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  738. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  739. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  740. implementation are part of the standard, as well.
  741. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  742. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  743. $iv = pack('H*', trim($matches[2]));
  744. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  745. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  746. $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);
  747. $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
  748. if ($ciphertext === false) {
  749. $ciphertext = $key;
  750. }
  751. switch ($matches[1]) {
  752. case 'AES-128-CBC':
  753. if (!class_exists('Crypt_AES')) {
  754. require_once('Crypt/AES.php');
  755. }
  756. $symkey = substr($symkey, 0, 16);
  757. $crypto = new Crypt_AES();
  758. break;
  759. case 'DES-EDE3-CFB':
  760. if (!class_exists('Crypt_TripleDES')) {
  761. require_once('Crypt/TripleDES.php');
  762. }
  763. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  764. break;
  765. case 'DES-EDE3-CBC':
  766. if (!class_exists('Crypt_TripleDES')) {
  767. require_once('Crypt/TripleDES.php');
  768. }
  769. $crypto = new Crypt_TripleDES();
  770. break;
  771. case 'DES-CBC':
  772. if (!class_exists('Crypt_DES')) {
  773. require_once('Crypt/DES.php');
  774. }
  775. $crypto = new Crypt_DES();
  776. break;
  777. default:
  778. return false;
  779. }
  780. $crypto->setKey($symkey);
  781. $crypto->setIV($iv);
  782. $decoded = $crypto->decrypt($ciphertext);
  783. } else {
  784. $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);
  785. $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
  786. }
  787. if ($decoded !== false) {
  788. $key = $decoded;
  789. }
  790. $components = array();
  791. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  792. return false;
  793. }
  794. if ($this->_decodeLength($key) != strlen($key)) {
  795. return false;
  796. }
  797. $tag = ord($this->_string_shift($key));
  798. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  799. /* intended for keys for which OpenSSL's asn1parse returns the following:
  800. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  801. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  802. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  803. 17:d=2 hl=2 l= 0 prim: NULL
  804. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  805. $this->_string_shift($key, $this->_decodeLength($key));
  806. $this->_string_shift($key); // skip over the BIT STRING tag
  807. $this->_decodeLength($key); // skip over the BIT STRING length
  808. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  809. // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."
  810. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  811. $this->_string_shift($key);
  812. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  813. return false;
  814. }
  815. if ($this->_decodeLength($key) != strlen($key)) {
  816. return false;
  817. }
  818. $tag = ord($this->_string_shift($key));
  819. }
  820. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  821. return false;
  822. }
  823. $length = $this->_decodeLength($key);
  824. $temp = $this->_string_shift($key, $length);
  825. if (strlen($temp) != 1 || ord($temp) > 2) {
  826. $components['modulus'] = new Math_BigInteger($temp, -256);
  827. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  828. $length = $this->_decodeLength($key);
  829. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  830. return $components;
  831. }
  832. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  833. return false;
  834. }
  835. $length = $this->_decodeLength($key);
  836. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  837. $this->_string_shift($key);
  838. $length = $this->_decodeLength($key);
  839. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  840. $this->_string_shift($key);
  841. $length = $this->_decodeLength($key);
  842. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  843. $this->_string_shift($key);
  844. $length = $this->_decodeLength($key);
  845. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  846. $this->_string_shift($key);
  847. $length = $this->_decodeLength($key);
  848. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  849. $this->_string_shift($key);
  850. $length = $this->_decodeLength($key);
  851. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  852. $this->_string_shift($key);
  853. $length = $this->_decodeLength($key);
  854. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  855. $this->_string_shift($key);
  856. $length = $this->_decodeLength($key);
  857. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  858. if (!empty($key)) {
  859. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  860. return false;
  861. }
  862. $this->_decodeLength($key);
  863. while (!empty($key)) {
  864. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  865. return false;
  866. }
  867. $this->_decodeLength($key);
  868. $key = substr($key, 1);
  869. $length = $this->_decodeLength($key);
  870. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  871. $this->_string_shift($key);
  872. $length = $this->_decodeLength($key);
  873. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  874. $this->_string_shift($key);
  875. $length = $this->_decodeLength($key);
  876. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  877. }
  878. }
  879. return $components;
  880. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  881. $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
  882. if ($key === false) {
  883. return false;
  884. }
  885. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  886. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  887. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  888. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  889. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  890. if ($cleanup && strlen($key)) {
  891. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  892. return array(
  893. 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
  894. 'publicExponent' => $modulus
  895. );
  896. } else {
  897. return array(
  898. 'modulus' => $modulus,
  899. 'publicExponent' => $publicExponent
  900. );
  901. }
  902. // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
  903. // http://en.wikipedia.org/wiki/XML_Signature
  904. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  905. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  906. $this->components = array();
  907. $xml = xml_parser_create('UTF-8');
  908. xml_set_object($xml, $this);
  909. xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
  910. xml_set_character_data_handler($xml, '_data_handler');
  911. if (!xml_parse($xml, $key)) {
  912. return false;
  913. }
  914. return $this->components;
  915. // from PuTTY's SSHPUBK.C
  916. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  917. $components = array();
  918. $key = preg_split('#\r\n|\r|\n#', $key);
  919. $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
  920. if ($type != 'ssh-rsa') {
  921. return false;
  922. }
  923. $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
  924. $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
  925. $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
  926. $public = substr($public, 11);
  927. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  928. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  929. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  930. $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256);
  931. $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
  932. $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
  933. switch ($encryption) {
  934. case 'aes256-cbc':
  935. if (!class_exists('Crypt_AES')) {
  936. require_once('Crypt/AES.php');
  937. }
  938. $symkey = '';
  939. $sequence = 0;
  940. while (strlen($symkey) < 32) {
  941. $temp = pack('Na*', $sequence++, $this->password);
  942. $symkey.= pack('H*', sha1($temp));
  943. }
  944. $symkey = substr($symkey, 0, 32);
  945. $crypto = new Crypt_AES();
  946. }
  947. if ($encryption != 'none') {
  948. $crypto->setKey($symkey);
  949. $crypto->disablePadding();
  950. $private = $crypto->decrypt($private);
  951. if ($private === false) {
  952. return false;
  953. }
  954. }
  955. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  956. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  957. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  958. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  959. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  960. $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256);
  961. $temp = $components['primes'][1]->subtract($this->one);
  962. $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
  963. $temp = $components['primes'][2]->subtract($this->one);
  964. $components['exponents'][] = $components['publicExponent']->modInverse($temp);
  965. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  966. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256));
  967. return $components;
  968. }
  969. }
  970. /**
  971. * Start Element Handler
  972. *
  973. * Called by xml_set_element_handler()
  974. *
  975. * @access private
  976. * @param Resource $parser
  977. * @param String $name
  978. * @param Array $attribs
  979. */
  980. function _start_element_handler($parser, $name, $attribs)
  981. {
  982. //$name = strtoupper($name);
  983. switch ($name) {
  984. case 'MODULUS':
  985. $this->current = &$this->components['modulus'];
  986. break;
  987. case 'EXPONENT':
  988. $this->current = &$this->components['publicExponent'];
  989. break;
  990. case 'P':
  991. $this->current = &$this->components['primes'][1];
  992. break;
  993. case 'Q':
  994. $this->current = &$this->components['primes'][2];
  995. break;
  996. case 'DP':
  997. $this->current = &$this->components['exponents'][1];
  998. break;
  999. case 'DQ':
  1000. $this->current = &$this->components['exponents'][2];
  1001. break;
  1002. case 'INVERSEQ':
  1003. $this->current = &$this->components['coefficients'][2];
  1004. break;
  1005. case 'D':
  1006. $this->current = &$this->components['privateExponent'];
  1007. break;
  1008. default:
  1009. unset($this->current);
  1010. }
  1011. $this->current = '';
  1012. }
  1013. /**
  1014. * Stop Element Handler
  1015. *
  1016. * Called by xml_set_element_handler()
  1017. *
  1018. * @access private
  1019. * @param Resource $parser
  1020. * @param String $name
  1021. */
  1022. function _stop_element_handler($parser, $name)
  1023. {
  1024. //$name = strtoupper($name);
  1025. if ($name == 'RSAKEYVALUE') {
  1026. return;
  1027. }
  1028. $this->current = new Math_BigInteger(base64_decode($this->current), 256);
  1029. }
  1030. /**
  1031. * Data Handler
  1032. *
  1033. * Called by xml_set_character_data_handler()
  1034. *
  1035. * @access private
  1036. * @param Resource $parser
  1037. * @param String $data
  1038. */
  1039. function _data_handler($parser, $data)
  1040. {
  1041. if (!isset($this->current) || is_object($this->current)) {
  1042. return;
  1043. }
  1044. $this->current.= trim($data);
  1045. }
  1046. /**
  1047. * Loads a public or private key
  1048. *
  1049. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  1050. *
  1051. * @access public
  1052. * @param String $key
  1053. * @param Integer $type optional
  1054. */
  1055. function loadKey($key, $type = false)
  1056. {
  1057. if ($type === false) {
  1058. $types = array(
  1059. CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1060. CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
  1061. CRYPT_RSA_PRIVATE_FORMAT_XML,
  1062. CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
  1063. CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1064. );
  1065. foreach ($types as $type) {
  1066. $components = $this->_parseKey($key, $type);
  1067. if ($components !== false) {
  1068. break;
  1069. }
  1070. }
  1071. } else {
  1072. $components = $this->_parseKey($key, $type);
  1073. }
  1074. if ($components === false) {
  1075. return false;
  1076. }
  1077. $this->modulus = $components['modulus'];
  1078. $this->k = strlen($this->modulus->toBytes());
  1079. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  1080. if (isset($components['primes'])) {
  1081. $this->primes = $components['primes'];
  1082. $this->exponents = $components['exponents'];
  1083. $this->coefficients = $components['coefficients'];
  1084. $this->publicExponent = $components['publicExponent'];
  1085. } else {
  1086. $this->primes = array();
  1087. $this->exponents = array();
  1088. $this->coefficients = array();
  1089. $this->publicExponent = false;
  1090. }
  1091. return true;
  1092. }
  1093. /**
  1094. * Sets the password
  1095. *
  1096. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  1097. * Or rather, pass in $password such that empty($password) is true.
  1098. *
  1099. * @see createKey()
  1100. * @see loadKey()
  1101. * @access public
  1102. * @param String $password
  1103. */
  1104. function setPassword($password)
  1105. {
  1106. $this->password = $password;
  1107. }
  1108. /**
  1109. * Defines the public key
  1110. *
  1111. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  1112. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  1113. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  1114. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  1115. * exponent this won't work unless you manually add the public exponent.
  1116. *
  1117. * Do note that when a new key is loaded the index will be cleared.
  1118. *
  1119. * Returns true on success, false on failure
  1120. *
  1121. * @see getPublicKey()
  1122. * @access public
  1123. * @param String $key
  1124. * @param Integer $type optional
  1125. * @return Boolean
  1126. */
  1127. function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1128. {
  1129. $components = $this->_parseKey($key, $type);
  1130. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  1131. user_error('Trying to load a public key? Use loadKey() instead. It\'s called loadKey() and not loadPrivateKey() for a reason.', E_USER_NOTICE);
  1132. return false;
  1133. }
  1134. $this->publicExponent = $components['publicExponent'];
  1135. return true;
  1136. }
  1137. /**
  1138. * Returns the public key
  1139. *
  1140. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  1141. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  1142. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  1143. *
  1144. * @see getPublicKey()
  1145. * @access public
  1146. * @param String $key
  1147. * @param Integer $type optional
  1148. */
  1149. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  1150. {
  1151. if (empty($this->modulus) || empty($this->publicExponent)) {
  1152. return false;
  1153. }
  1154. $oldFormat = $this->publicKeyFormat;
  1155. $this->publicKeyFormat = $type;
  1156. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  1157. $this->publicKeyFormat = $oldFormat;
  1158. return $temp;
  1159. }
  1160. /**
  1161. * Generates the smallest and largest numbers requiring $bits bits
  1162. *
  1163. * @access private
  1164. * @param Integer $bits
  1165. * @return Array
  1166. */
  1167. function _generateMinMax($bits)
  1168. {
  1169. $bytes = $bits >> 3;
  1170. $min = str_repeat(chr(0), $bytes);
  1171. $max = str_repeat(chr(0xFF), $bytes);
  1172. $msb = $bits & 7;
  1173. if ($msb) {
  1174. $min = chr(1 << ($msb - 1)) . $min;
  1175. $max = chr((1 << $msb) - 1) . $max;
  1176. } else {
  1177. $min[0] = chr(0x80);
  1178. }
  1179. return array(
  1180. 'min' => new Math_BigInteger($min, 256),
  1181. 'max' => new Math_BigInteger($max, 256)
  1182. );
  1183. }
  1184. /**
  1185. * DER-decode the length
  1186. *
  1187. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1188. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 � 8.1.3} for more information.
  1189. *
  1190. * @access private
  1191. * @param String $string
  1192. * @return Integer
  1193. */
  1194. function _decodeLength(&$string)
  1195. {
  1196. $length = ord($this->_string_shift($string));
  1197. if ( $length & 0x80 ) { // definite length, long form
  1198. $length&= 0x7F;
  1199. $temp = $this->_string_shift($string, $length);
  1200. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1201. }
  1202. return $length;
  1203. }
  1204. /**
  1205. * DER-encode the length
  1206. *
  1207. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1208. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 � 8.1.3} for more information.
  1209. *
  1210. * @access private
  1211. * @param Integer $length
  1212. * @return String
  1213. */
  1214. function _encodeLength($length)
  1215. {
  1216. if ($length <= 0x7F) {
  1217. return chr($length);
  1218. }
  1219. $temp = ltrim(pack('N', $length), chr(0));
  1220. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1221. }
  1222. /**
  1223. * String Shift
  1224. *
  1225. * Inspired by array_shift
  1226. *
  1227. * @param String $string
  1228. * @param optional Integer $index
  1229. * @return String
  1230. * @access private
  1231. */
  1232. function _string_shift(&$string, $index = 1)
  1233. {
  1234. $substr = substr($string, 0, $index);
  1235. $string = substr($string, $index);
  1236. return $substr;
  1237. }
  1238. /**
  1239. * Determines the private key format
  1240. *
  1241. * @see createKey()
  1242. * @access public
  1243. * @param Integer $format
  1244. */
  1245. function setPrivateKeyFormat($format)
  1246. {
  1247. $this->privateKeyFormat = $format;
  1248. }
  1249. /**
  1250. * Determines the public key format
  1251. *
  1252. * @see createKey()
  1253. * @access public
  1254. * @param Integer $format
  1255. */
  1256. function setPublicKeyFormat($format)
  1257. {
  1258. $this->publicKeyFormat = $format;
  1259. }
  1260. /**
  1261. * Determines which hashing function should be used
  1262. *
  1263. * Used wi…

Large files files are truncated, but you can click here to view the full file