PageRenderTime 78ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/fuel/core/vendor/phpseclib/Crypt/RSA.php

https://bitbucket.org/arkross/venus
PHP | 2121 lines | 1021 code | 222 blank | 878 comment | 163 complexity | 3b78e8a927b49547c2bcee66dc52c6d1 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. namespace PHPSecLib;
  4. /**
  5. * Pure-PHP PKCS#1 (v2.1) compliant implementation of RSA.
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * Here's an example of how to encrypt and decrypt text with this library:
  10. * <code>
  11. * <?php
  12. * include('Crypt/RSA.php');
  13. *
  14. * $rsa = new Crypt_RSA();
  15. * extract($rsa->createKey());
  16. *
  17. * $plaintext = 'terrafrost';
  18. *
  19. * $rsa->loadKey($privatekey);
  20. * $ciphertext = $rsa->encrypt($plaintext);
  21. *
  22. * $rsa->loadKey($publickey);
  23. * echo $rsa->decrypt($ciphertext);
  24. * ?>
  25. * </code>
  26. *
  27. * Here's an example of how to create signatures and verify signatures with this library:
  28. * <code>
  29. * <?php
  30. * include('Crypt/RSA.php');
  31. *
  32. * $rsa = new Crypt_RSA();
  33. * extract($rsa->createKey());
  34. *
  35. * $plaintext = 'terrafrost';
  36. *
  37. * $rsa->loadKey($privatekey);
  38. * $signature = $rsa->sign($plaintext);
  39. *
  40. * $rsa->loadKey($publickey);
  41. * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
  42. * ?>
  43. * </code>
  44. *
  45. * LICENSE: This library is free software; you can redistribute it and/or
  46. * modify it under the terms of the GNU Lesser General Public
  47. * License as published by the Free Software Foundation; either
  48. * version 2.1 of the License, or (at your option) any later version.
  49. *
  50. * This library is distributed in the hope that it will be useful,
  51. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  52. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  53. * Lesser General Public License for more details.
  54. *
  55. * You should have received a copy of the GNU Lesser General Public
  56. * License along with this library; if not, write to the Free Software
  57. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  58. * MA 02111-1307 USA
  59. *
  60. * @category Crypt
  61. * @package Crypt_RSA
  62. * @author Jim Wigginton <terrafrost@php.net>
  63. * @copyright MMIX Jim Wigginton
  64. * @license http://www.gnu.org/licenses/lgpl.txt
  65. * @version $Id: RSA.php,v 1.15 2010/04/10 15:57:02 terrafrost Exp $
  66. * @link http://phpseclib.sourceforge.net
  67. */
  68. /**
  69. * Include Math_BigInteger
  70. */
  71. require_once('Math/BigInteger.php');
  72. /**
  73. * Include Crypt_Random
  74. */
  75. require_once('Crypt/Random.php');
  76. /**
  77. * Include Crypt_Hash
  78. */
  79. require_once('Crypt/Hash.php');
  80. /**#@+
  81. * @access public
  82. * @see Crypt_RSA::encrypt()
  83. * @see Crypt_RSA::decrypt()
  84. */
  85. /**
  86. * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding}
  87. * (OAEP) for encryption / decryption.
  88. *
  89. * Uses sha1 by default.
  90. *
  91. * @see Crypt_RSA::setHash()
  92. * @see Crypt_RSA::setMGFHash()
  93. */
  94. define('CRYPT_RSA_ENCRYPTION_OAEP', 1);
  95. /**
  96. * Use PKCS#1 padding.
  97. *
  98. * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards
  99. * compatability with protocols (like SSH-1) written before OAEP's introduction.
  100. */
  101. define('CRYPT_RSA_ENCRYPTION_PKCS1', 2);
  102. /**#@-*/
  103. /**#@+
  104. * @access public
  105. * @see Crypt_RSA::sign()
  106. * @see Crypt_RSA::verify()
  107. * @see Crypt_RSA::setHash()
  108. */
  109. /**
  110. * Use the Probabilistic Signature Scheme for signing
  111. *
  112. * Uses sha1 by default.
  113. *
  114. * @see Crypt_RSA::setSaltLength()
  115. * @see Crypt_RSA::setMGFHash()
  116. */
  117. define('CRYPT_RSA_SIGNATURE_PSS', 1);
  118. /**
  119. * Use the PKCS#1 scheme by default.
  120. *
  121. * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards
  122. * compatability with protocols (like SSH-2) written before PSS's introduction.
  123. */
  124. define('CRYPT_RSA_SIGNATURE_PKCS1', 2);
  125. /**#@-*/
  126. /**#@+
  127. * @access private
  128. * @see Crypt_RSA::createKey()
  129. */
  130. /**
  131. * ASN1 Integer
  132. */
  133. define('CRYPT_RSA_ASN1_INTEGER', 2);
  134. /**
  135. * ASN1 Sequence (with the constucted bit set)
  136. */
  137. define('CRYPT_RSA_ASN1_SEQUENCE', 48);
  138. /**#@-*/
  139. /**#@+
  140. * @access private
  141. * @see Crypt_RSA::Crypt_RSA()
  142. */
  143. /**
  144. * To use the pure-PHP implementation
  145. */
  146. define('CRYPT_RSA_MODE_INTERNAL', 1);
  147. /**
  148. * To use the OpenSSL library
  149. *
  150. * (if enabled; otherwise, the internal implementation will be used)
  151. */
  152. define('CRYPT_RSA_MODE_OPENSSL', 2);
  153. /**#@-*/
  154. /**#@+
  155. * @access public
  156. * @see Crypt_RSA::createKey()
  157. * @see Crypt_RSA::setPrivateKeyFormat()
  158. */
  159. /**
  160. * PKCS#1 formatted private key
  161. *
  162. * Used by OpenSSH
  163. */
  164. define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0);
  165. /**#@-*/
  166. /**#@+
  167. * @access public
  168. * @see Crypt_RSA::createKey()
  169. * @see Crypt_RSA::setPublicKeyFormat()
  170. */
  171. /**
  172. * Raw public key
  173. *
  174. * An array containing two Math_BigInteger objects.
  175. *
  176. * The exponent can be indexed with any of the following:
  177. *
  178. * 0, e, exponent, publicExponent
  179. *
  180. * The modulus can be indexed with any of the following:
  181. *
  182. * 1, n, modulo, modulus
  183. */
  184. define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 1);
  185. /**
  186. * PKCS#1 formatted public key
  187. */
  188. define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 2);
  189. /**
  190. * OpenSSH formatted public key
  191. *
  192. * Place in $HOME/.ssh/authorized_keys
  193. */
  194. define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 3);
  195. /**#@-*/
  196. /**
  197. * Pure-PHP PKCS#1 compliant implementation of RSA.
  198. *
  199. * @author Jim Wigginton <terrafrost@php.net>
  200. * @version 0.1.0
  201. * @access public
  202. * @package Crypt_RSA
  203. */
  204. class Crypt_RSA {
  205. /**
  206. * Precomputed Zero
  207. *
  208. * @var Array
  209. * @access private
  210. */
  211. var $zero;
  212. /**
  213. * Precomputed One
  214. *
  215. * @var Array
  216. * @access private
  217. */
  218. var $one;
  219. /**
  220. * Private Key Format
  221. *
  222. * @var Integer
  223. * @access private
  224. */
  225. var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  226. /**
  227. * Public Key Format
  228. *
  229. * @var Integer
  230. * @access public
  231. */
  232. var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS1;
  233. /**
  234. * Modulus (ie. n)
  235. *
  236. * @var Math_BigInteger
  237. * @access private
  238. */
  239. var $modulus;
  240. /**
  241. * Modulus length
  242. *
  243. * @var Math_BigInteger
  244. * @access private
  245. */
  246. var $k;
  247. /**
  248. * Exponent (ie. e or d)
  249. *
  250. * @var Math_BigInteger
  251. * @access private
  252. */
  253. var $exponent;
  254. /**
  255. * Primes for Chinese Remainder Theorem (ie. p and q)
  256. *
  257. * @var Array
  258. * @access private
  259. */
  260. var $primes;
  261. /**
  262. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  263. *
  264. * @var Array
  265. * @access private
  266. */
  267. var $exponents;
  268. /**
  269. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  270. *
  271. * @var Array
  272. * @access private
  273. */
  274. var $coefficients;
  275. /**
  276. * Hash name
  277. *
  278. * @var String
  279. * @access private
  280. */
  281. var $hashName;
  282. /**
  283. * Hash function
  284. *
  285. * @var Crypt_Hash
  286. * @access private
  287. */
  288. var $hash;
  289. /**
  290. * Length of hash function output
  291. *
  292. * @var Integer
  293. * @access private
  294. */
  295. var $hLen;
  296. /**
  297. * Length of salt
  298. *
  299. * @var Integer
  300. * @access private
  301. */
  302. var $sLen;
  303. /**
  304. * Hash function for the Mask Generation Function
  305. *
  306. * @var Crypt_Hash
  307. * @access private
  308. */
  309. var $mgfHash;
  310. /**
  311. * Length of MGF hash function output
  312. *
  313. * @var Integer
  314. * @access private
  315. */
  316. var $mgfHLen;
  317. /**
  318. * Encryption mode
  319. *
  320. * @var Integer
  321. * @access private
  322. */
  323. var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  324. /**
  325. * Signature mode
  326. *
  327. * @var Integer
  328. * @access private
  329. */
  330. var $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  331. /**
  332. * Public Exponent
  333. *
  334. * @var Mixed
  335. * @access private
  336. */
  337. var $publicExponent = false;
  338. /**
  339. * Password
  340. *
  341. * @var String
  342. * @access private
  343. */
  344. var $password = '';
  345. /**
  346. * The constructor
  347. *
  348. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  349. * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  350. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  351. *
  352. * @return Crypt_RSA
  353. * @access public
  354. */
  355. function __construct()
  356. {
  357. if ( !defined('CRYPT_RSA_MODE') ) {
  358. switch (true) {
  359. //case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>='):
  360. // define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  361. // break;
  362. default:
  363. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  364. }
  365. }
  366. $this->zero = new Math_BigInteger();
  367. $this->one = new Math_BigInteger(1);
  368. $this->hash = new Crypt_Hash('sha1');
  369. $this->hLen = $this->hash->getLength();
  370. $this->hashName = 'sha1';
  371. $this->mgfHash = new Crypt_Hash('sha1');
  372. $this->mgfHLen = $this->mgfHash->getLength();
  373. }
  374. /**
  375. * Create public / private key pair
  376. *
  377. * Returns an array with the following three elements:
  378. * - 'privatekey': The private key.
  379. * - 'publickey': The public key.
  380. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  381. * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  382. *
  383. * @access public
  384. * @param optional Integer $bits
  385. * @param optional Integer $timeout
  386. * @param optional Math_BigInteger $p
  387. */
  388. function createKey($bits = 1024, $timeout = false, $partial = array())
  389. {
  390. if ( CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL ) {
  391. $rsa = openssl_pkey_new(array('private_key_bits' => $bits));
  392. openssl_pkey_export($rsa, $privatekey);
  393. $publickey = openssl_pkey_get_details($rsa);
  394. $publickey = $publickey['key'];
  395. if ($this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_PKCS1) {
  396. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  397. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  398. }
  399. return array(
  400. 'privatekey' => $privatekey,
  401. 'publickey' => $publickey,
  402. 'partialkey' => false
  403. );
  404. }
  405. static $e;
  406. if (!isset($e)) {
  407. if (!defined('CRYPT_RSA_EXPONENT')) {
  408. // http://en.wikipedia.org/wiki/65537_%28number%29
  409. define('CRYPT_RSA_EXPONENT', '65537');
  410. }
  411. if (!defined('CRYPT_RSA_COMMENT')) {
  412. define('CRYPT_RSA_COMMENT', 'phpseclib-generated-key');
  413. }
  414. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  415. // than 256 bits.
  416. if (!defined('CRYPT_RSA_SMALLEST_PRIME')) {
  417. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  418. }
  419. $e = new Math_BigInteger(CRYPT_RSA_EXPONENT);
  420. }
  421. extract($this->_generateMinMax($bits));
  422. $absoluteMin = $min;
  423. $temp = $bits >> 1;
  424. if ($temp > CRYPT_RSA_SMALLEST_PRIME) {
  425. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  426. $temp = CRYPT_RSA_SMALLEST_PRIME;
  427. } else {
  428. $num_primes = 2;
  429. }
  430. extract($this->_generateMinMax($temp + $bits % $temp));
  431. $finalMax = $max;
  432. extract($this->_generateMinMax($temp));
  433. $generator = new Math_BigInteger();
  434. $generator->setRandomGenerator('crypt_random');
  435. $n = $this->one->copy();
  436. if (!empty($partial)) {
  437. extract(unserialize($partial));
  438. } else {
  439. $exponents = $coefficients = $primes = array();
  440. $lcm = array(
  441. 'top' => $this->one->copy(),
  442. 'bottom' => false
  443. );
  444. }
  445. $start = time();
  446. $i0 = count($primes) + 1;
  447. do {
  448. for ($i = $i0; $i <= $num_primes; $i++) {
  449. if ($timeout !== false) {
  450. $timeout-= time() - $start;
  451. $start = time();
  452. if ($timeout <= 0) {
  453. return serialize(array(
  454. 'privatekey' => '',
  455. 'publickey' => '',
  456. 'partialkey' => array(
  457. 'primes' => $primes,
  458. 'coefficients' => $coefficients,
  459. 'lcm' => $lcm,
  460. 'exponents' => $exponents
  461. )
  462. ));
  463. }
  464. }
  465. if ($i == $num_primes) {
  466. list($min, $temp) = $absoluteMin->divide($n);
  467. if (!$temp->equals($this->zero)) {
  468. $min = $min->add($this->one); // ie. ceil()
  469. }
  470. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  471. } else {
  472. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  473. }
  474. if ($primes[$i] === false) { // if we've reached the timeout
  475. return array(
  476. 'privatekey' => '',
  477. 'publickey' => '',
  478. 'partialkey' => empty($primes) ? '' : serialize(array(
  479. 'primes' => array_slice($primes, 0, $i - 1),
  480. 'coefficients' => $coefficients,
  481. 'lcm' => $lcm,
  482. 'exponents' => $exponents
  483. ))
  484. );
  485. }
  486. // the first coefficient is calculated differently from the rest
  487. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  488. if ($i > 2) {
  489. $coefficients[$i] = $n->modInverse($primes[$i]);
  490. }
  491. $n = $n->multiply($primes[$i]);
  492. $temp = $primes[$i]->subtract($this->one);
  493. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  494. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  495. $lcm['top'] = $lcm['top']->multiply($temp);
  496. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  497. $exponents[$i] = $e->modInverse($temp);
  498. }
  499. list($lcm) = $lcm['top']->divide($lcm['bottom']);
  500. $gcd = $lcm->gcd($e);
  501. $i0 = 1;
  502. } while (!$gcd->equals($this->one));
  503. $d = $e->modInverse($lcm);
  504. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  505. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  506. // RSAPrivateKey ::= SEQUENCE {
  507. // version Version,
  508. // modulus INTEGER, -- n
  509. // publicExponent INTEGER, -- e
  510. // privateExponent INTEGER, -- d
  511. // prime1 INTEGER, -- p
  512. // prime2 INTEGER, -- q
  513. // exponent1 INTEGER, -- d mod (p-1)
  514. // exponent2 INTEGER, -- d mod (q-1)
  515. // coefficient INTEGER, -- (inverse of q) mod p
  516. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  517. // }
  518. return array(
  519. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  520. 'publickey' => $this->_convertPublicKey($n, $e),
  521. 'partialkey' => false
  522. );
  523. }
  524. /**
  525. * Convert a private key to the appropriate format.
  526. *
  527. * @access private
  528. * @see setPrivateKeyFormat()
  529. * @param String $RSAPrivateKey
  530. * @return String
  531. */
  532. function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients)
  533. {
  534. $num_primes = count($primes);
  535. $raw = array(
  536. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  537. 'modulus' => $n->toBytes(true),
  538. 'publicExponent' => $e->toBytes(true),
  539. 'privateExponent' => $d->toBytes(true),
  540. 'prime1' => $primes[1]->toBytes(true),
  541. 'prime2' => $primes[2]->toBytes(true),
  542. 'exponent1' => $exponents[1]->toBytes(true),
  543. 'exponent2' => $exponents[2]->toBytes(true),
  544. 'coefficient' => $coefficients[2]->toBytes(true)
  545. );
  546. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  547. // call _convertPublicKey() instead.
  548. switch ($this->privateKeyFormat) {
  549. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  550. $components = array();
  551. foreach ($raw as $name => $value) {
  552. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  553. }
  554. $RSAPrivateKey = implode('', $components);
  555. if ($num_primes > 2) {
  556. $OtherPrimeInfos = '';
  557. for ($i = 3; $i <= $num_primes; $i++) {
  558. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  559. //
  560. // OtherPrimeInfo ::= SEQUENCE {
  561. // prime INTEGER, -- ri
  562. // exponent INTEGER, -- di
  563. // coefficient INTEGER -- ti
  564. // }
  565. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  566. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  567. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  568. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  569. }
  570. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  571. }
  572. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  573. if (!empty($this->password)) {
  574. $iv = $this->_random(8);
  575. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  576. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  577. if (!class_exists('Crypt_TripleDES')) {
  578. require_once('Crypt/TripleDES.php');
  579. }
  580. $des = new Crypt_TripleDES();
  581. $des->setKey($symkey);
  582. $des->setIV($iv);
  583. $iv = strtoupper(bin2hex($iv));
  584. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  585. "Proc-Type: 4,ENCRYPTED\r\n" .
  586. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  587. "\r\n" .
  588. chunk_split(base64_encode($des->encrypt($RSAPrivateKey))) .
  589. '-----END RSA PRIVATE KEY-----';
  590. } else {
  591. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  592. chunk_split(base64_encode($RSAPrivateKey)) .
  593. '-----END RSA PRIVATE KEY-----';
  594. }
  595. return $RSAPrivateKey;
  596. }
  597. }
  598. /**
  599. * Convert a public key to the appropriate format
  600. *
  601. * @access private
  602. * @see setPublicKeyFormat()
  603. * @param String $RSAPrivateKey
  604. * @return String
  605. */
  606. function _convertPublicKey($n, $e)
  607. {
  608. $modulus = $n->toBytes(true);
  609. $publicExponent = $e->toBytes(true);
  610. switch ($this->publicKeyFormat) {
  611. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  612. return array('e' => $e->copy(), 'n' => $n->copy());
  613. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  614. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  615. // string "ssh-rsa"
  616. // mpint e
  617. // mpint n
  618. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  619. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . CRYPT_RSA_COMMENT;
  620. return $RSAPublicKey;
  621. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  622. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  623. // RSAPublicKey ::= SEQUENCE {
  624. // modulus INTEGER, -- n
  625. // publicExponent INTEGER -- e
  626. // }
  627. $components = array(
  628. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  629. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  630. );
  631. $RSAPublicKey = pack('Ca*a*a*',
  632. CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
  633. $components['modulus'], $components['publicExponent']
  634. );
  635. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  636. chunk_split(base64_encode($RSAPublicKey)) .
  637. '-----END PUBLIC KEY-----';
  638. return $RSAPublicKey;
  639. }
  640. }
  641. /**
  642. * Break a public or private key down into its constituant components
  643. *
  644. * @access private
  645. * @see _convertPublicKey()
  646. * @see _convertPrivateKey()
  647. * @param String $key
  648. * @param Integer $type
  649. * @return Array
  650. */
  651. function _parseKey($key, $type)
  652. {
  653. switch ($type) {
  654. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  655. if (!is_array($key)) {
  656. return false;
  657. }
  658. $components = array();
  659. switch (true) {
  660. case isset($key['e']):
  661. $components['publicExponent'] = $key['e']->copy();
  662. break;
  663. case isset($key['exponent']):
  664. $components['publicExponent'] = $key['exponent']->copy();
  665. break;
  666. case isset($key['publicExponent']):
  667. $components['publicExponent'] = $key['publicExponent']->copy();
  668. break;
  669. case isset($key[0]):
  670. $components['publicExponent'] = $key[0]->copy();
  671. }
  672. switch (true) {
  673. case isset($key['n']):
  674. $components['modulus'] = $key['n']->copy();
  675. break;
  676. case isset($key['modulo']):
  677. $components['modulus'] = $key['modulo']->copy();
  678. break;
  679. case isset($key['modulus']):
  680. $components['modulus'] = $key['modulus']->copy();
  681. break;
  682. case isset($key[1]):
  683. $components['modulus'] = $key[1]->copy();
  684. }
  685. return $components;
  686. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  687. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  688. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  689. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  690. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  691. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  692. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  693. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  694. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  695. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  696. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  697. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  698. implementation are part of the standard, as well.
  699. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  700. if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) {
  701. $iv = pack('H*', trim($matches[2]));
  702. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  703. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  704. $ciphertext = preg_replace('#.+(\r|\n|\r\n)\1|[\r\n]|-.+-#s', '', $key);
  705. $ciphertext = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $ciphertext) ? base64_decode($ciphertext) : false;
  706. if ($ciphertext === false) {
  707. $ciphertext = $key;
  708. }
  709. switch ($matches[1]) {
  710. case 'DES-EDE3-CBC':
  711. if (!class_exists('Crypt_TripleDES')) {
  712. require_once('Crypt/TripleDES.php');
  713. }
  714. $crypto = new Crypt_TripleDES();
  715. break;
  716. case 'DES-CBC':
  717. if (!class_exists('Crypt_DES')) {
  718. require_once('Crypt/DES.php');
  719. }
  720. $crypto = new Crypt_DES();
  721. break;
  722. default:
  723. return false;
  724. }
  725. $crypto->setKey($symkey);
  726. $crypto->setIV($iv);
  727. $decoded = $crypto->decrypt($ciphertext);
  728. } else {
  729. $decoded = preg_replace('#-.+-|[\r\n]#', '', $key);
  730. $decoded = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $decoded) ? base64_decode($decoded) : false;
  731. }
  732. if ($decoded !== false) {
  733. $key = $decoded;
  734. }
  735. $components = array();
  736. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  737. return false;
  738. }
  739. if ($this->_decodeLength($key) != strlen($key)) {
  740. return false;
  741. }
  742. $tag = ord($this->_string_shift($key));
  743. if ($tag == CRYPT_RSA_ASN1_SEQUENCE) {
  744. /* intended for keys for which OpenSSL's asn1parse returns the following:
  745. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  746. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  747. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  748. 17:d=2 hl=2 l= 0 prim: NULL
  749. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  750. $this->_string_shift($key, $this->_decodeLength($key));
  751. $this->_string_shift($key); // skip over the BIT STRING tag
  752. $this->_decodeLength($key); // skip over the BIT STRING length
  753. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  754. // unused bits in teh final subsequent octet. The number shall be in the range zero to seven."
  755. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  756. $this->_string_shift($key);
  757. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  758. return false;
  759. }
  760. if ($this->_decodeLength($key) != strlen($key)) {
  761. return false;
  762. }
  763. $tag = ord($this->_string_shift($key));
  764. }
  765. if ($tag != CRYPT_RSA_ASN1_INTEGER) {
  766. return false;
  767. }
  768. $length = $this->_decodeLength($key);
  769. $temp = $this->_string_shift($key, $length);
  770. if (strlen($temp) != 1 || ord($temp) > 2) {
  771. $components['modulus'] = new Math_BigInteger($temp, -256);
  772. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  773. $length = $this->_decodeLength($key);
  774. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  775. return $components;
  776. }
  777. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) {
  778. return false;
  779. }
  780. $length = $this->_decodeLength($key);
  781. $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  782. $this->_string_shift($key);
  783. $length = $this->_decodeLength($key);
  784. $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  785. $this->_string_shift($key);
  786. $length = $this->_decodeLength($key);
  787. $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  788. $this->_string_shift($key);
  789. $length = $this->_decodeLength($key);
  790. $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  791. $this->_string_shift($key);
  792. $length = $this->_decodeLength($key);
  793. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  794. $this->_string_shift($key);
  795. $length = $this->_decodeLength($key);
  796. $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  797. $this->_string_shift($key);
  798. $length = $this->_decodeLength($key);
  799. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  800. $this->_string_shift($key);
  801. $length = $this->_decodeLength($key);
  802. $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), -256));
  803. if (!empty($key)) {
  804. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  805. return false;
  806. }
  807. $this->_decodeLength($key);
  808. while (!empty($key)) {
  809. if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) {
  810. return false;
  811. }
  812. $this->_decodeLength($key);
  813. $key = substr($key, 1);
  814. $length = $this->_decodeLength($key);
  815. $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  816. $this->_string_shift($key);
  817. $length = $this->_decodeLength($key);
  818. $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  819. $this->_string_shift($key);
  820. $length = $this->_decodeLength($key);
  821. $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), -256);
  822. }
  823. }
  824. return $components;
  825. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  826. $key = base64_decode(preg_replace('#^ssh-rsa | .+$#', '', $key));
  827. if ($key === false) {
  828. return false;
  829. }
  830. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  831. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  832. $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256);
  833. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  834. $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256);
  835. if ($cleanup && strlen($key)) {
  836. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  837. return array(
  838. 'modulus' => new Math_BigInteger($this->_string_shift($key, $length), -256),
  839. 'publicExponent' => $modulus
  840. );
  841. } else {
  842. return array(
  843. 'modulus' => $modulus,
  844. 'publicExponent' => $publicExponent
  845. );
  846. }
  847. }
  848. }
  849. /**
  850. * Loads a public or private key
  851. *
  852. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  853. *
  854. * @access public
  855. * @param String $key
  856. * @param Integer $type optional
  857. */
  858. function loadKey($key, $type = CRYPT_RSA_PRIVATE_FORMAT_PKCS1)
  859. {
  860. $components = $this->_parseKey($key, $type);
  861. if ($components === false) {
  862. return false;
  863. }
  864. $this->modulus = $components['modulus'];
  865. $this->k = strlen($this->modulus->toBytes());
  866. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  867. if (isset($components['primes'])) {
  868. $this->primes = $components['primes'];
  869. $this->exponents = $components['exponents'];
  870. $this->coefficients = $components['coefficients'];
  871. $this->publicExponent = $components['publicExponent'];
  872. } else {
  873. $this->primes = array();
  874. $this->exponents = array();
  875. $this->coefficients = array();
  876. $this->publicExponent = false;
  877. }
  878. return true;
  879. }
  880. /**
  881. * Sets the password
  882. *
  883. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  884. * Or rather, pass in $password such that empty($password) is true.
  885. *
  886. * @see createKey()
  887. * @see loadKey()
  888. * @access public
  889. * @param String $password
  890. */
  891. function setPassword($password)
  892. {
  893. $this->password = $password;
  894. }
  895. /**
  896. * Defines the public key
  897. *
  898. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  899. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  900. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  901. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  902. * exponent this won't work unless you manually add the public exponent.
  903. *
  904. * Do note that when a new key is loaded the index will be cleared.
  905. *
  906. * Returns true on success, false on failure
  907. *
  908. * @see getPublicKey()
  909. * @access public
  910. * @param String $key
  911. * @param Integer $type optional
  912. * @return Boolean
  913. */
  914. function setPublicKey($key, $type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  915. {
  916. $components = $this->_parseKey($key, $type);
  917. if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) {
  918. return false;
  919. }
  920. $this->publicExponent = $components['publicExponent'];
  921. }
  922. /**
  923. * Returns the public key
  924. *
  925. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  926. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  927. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  928. *
  929. * @see getPublicKey()
  930. * @access public
  931. * @param String $key
  932. * @param Integer $type optional
  933. */
  934. function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
  935. {
  936. if (empty($this->modulus) || empty($this->publicExponent)) {
  937. return false;
  938. }
  939. $oldFormat = $this->publicKeyFormat;
  940. $this->publicKeyFormat = $type;
  941. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  942. $this->publicKeyFormat = $oldFormat;
  943. return $temp;
  944. }
  945. /**
  946. * Generates the smallest and largest numbers requiring $bits bits
  947. *
  948. * @access private
  949. * @param Integer $bits
  950. * @return Array
  951. */
  952. function _generateMinMax($bits)
  953. {
  954. $bytes = $bits >> 3;
  955. $min = str_repeat(chr(0), $bytes);
  956. $max = str_repeat(chr(0xFF), $bytes);
  957. $msb = $bits & 7;
  958. if ($msb) {
  959. $min = chr(1 << ($msb - 1)) . $min;
  960. $max = chr((1 << $msb) - 1) . $max;
  961. } else {
  962. $min[0] = chr(0x80);
  963. }
  964. return array(
  965. 'min' => new Math_BigInteger($min, 256),
  966. 'max' => new Math_BigInteger($max, 256)
  967. );
  968. }
  969. /**
  970. * DER-decode the length
  971. *
  972. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  973. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  974. *
  975. * @access private
  976. * @param String $string
  977. * @return Integer
  978. */
  979. function _decodeLength(&$string)
  980. {
  981. $length = ord($this->_string_shift($string));
  982. if ( $length & 0x80 ) { // definite length, long form
  983. $length&= 0x7F;
  984. $temp = $this->_string_shift($string, $length);
  985. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  986. }
  987. return $length;
  988. }
  989. /**
  990. * DER-encode the length
  991. *
  992. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  993. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 § 8.1.3} for more information.
  994. *
  995. * @access private
  996. * @param Integer $length
  997. * @return String
  998. */
  999. function _encodeLength($length)
  1000. {
  1001. if ($length <= 0x7F) {
  1002. return chr($length);
  1003. }
  1004. $temp = ltrim(pack('N', $length), chr(0));
  1005. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1006. }
  1007. /**
  1008. * String Shift
  1009. *
  1010. * Inspired by array_shift
  1011. *
  1012. * @param String $string
  1013. * @param optional Integer $index
  1014. * @return String
  1015. * @access private
  1016. */
  1017. function _string_shift(&$string, $index = 1)
  1018. {
  1019. $substr = substr($string, 0, $index);
  1020. $string = substr($string, $index);
  1021. return $substr;
  1022. }
  1023. /**
  1024. * Determines the private key format
  1025. *
  1026. * @see createKey()
  1027. * @access public
  1028. * @param Integer $format
  1029. */
  1030. function setPrivateKeyFormat($format)
  1031. {
  1032. $this->privateKeyFormat = $format;
  1033. }
  1034. /**
  1035. * Determines the public key format
  1036. *
  1037. * @see createKey()
  1038. * @access public
  1039. * @param Integer $format
  1040. */
  1041. function setPublicKeyFormat($format)
  1042. {
  1043. $this->publicKeyFormat = $format;
  1044. }
  1045. /**
  1046. * Determines which hashing function should be used
  1047. *
  1048. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1049. * decryption. If $hash isn't supported, sha1 is used.
  1050. *
  1051. * @access public
  1052. * @param String $hash
  1053. */
  1054. function setHash($hash)
  1055. {
  1056. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1057. switch ($hash) {
  1058. case 'md2':
  1059. case 'md5':
  1060. case 'sha1':
  1061. case 'sha256':
  1062. case 'sha384':
  1063. case 'sha512':
  1064. $this->hash = new Crypt_Hash($hash);
  1065. $this->hashName = $hash;
  1066. break;
  1067. default:
  1068. $this->hash = new Crypt_Hash('sha1');
  1069. $this->hashName = 'sha1';
  1070. }
  1071. $this->hLen = $this->hash->getLength();
  1072. }
  1073. /**
  1074. * Determines which hashing function should be used for the mask generation function
  1075. *
  1076. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1077. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1078. *
  1079. * @access public
  1080. * @param String $hash
  1081. */
  1082. function setMGFHash($hash)
  1083. {
  1084. // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1085. switch ($hash) {
  1086. case 'md2':
  1087. case 'md5':
  1088. case 'sha1':
  1089. case 'sha256':
  1090. case 'sha384':
  1091. case 'sha512':
  1092. $this->mgfHash = new Crypt_Hash($hash);
  1093. break;
  1094. default:
  1095. $this->mgfHash = new Crypt_Hash('sha1');
  1096. }
  1097. $this->mgfHLen = $this->mgfHash->getLength();
  1098. }
  1099. /**
  1100. * Determines the salt length
  1101. *
  1102. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1103. *
  1104. * Typical salt lengths in octets are hLen (the length of the output
  1105. * of the hash function Hash) and 0.
  1106. *
  1107. * @access public
  1108. * @param Integer $format
  1109. */
  1110. function setSaltLength($sLen)
  1111. {
  1112. $this->sLen = $sLen;
  1113. }
  1114. /**
  1115. * Generates a random string x bytes long
  1116. *
  1117. * @access public
  1118. * @param Integer $bytes
  1119. * @param optional Integer $nonzero
  1120. * @return String
  1121. */
  1122. function _random($bytes, $nonzero = false)
  1123. {
  1124. $temp = '';
  1125. if ($nonzero) {
  1126. for ($i = 0; $i < $bytes; $i++) {
  1127. $temp.= chr(crypt_random(1, 255));
  1128. }
  1129. } else {
  1130. $ints = ($bytes + 1) >> 2;
  1131. for ($i = 0; $i < $ints; $i++) {
  1132. $temp.= pack('N', crypt_random());
  1133. }
  1134. $temp = substr($temp, 0, $bytes);
  1135. }
  1136. return $temp;
  1137. }
  1138. /**
  1139. * Integer-to-Octet-String primitive
  1140. *
  1141. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1142. *
  1143. * @access private
  1144. * @param Math_BigInteger $x
  1145. * @param Integer $xLen
  1146. * @return String
  1147. */
  1148. function _i2osp($x, $xLen)
  1149. {
  1150. $x = $x->toBytes();
  1151. if (strlen($x) > $xLen) {
  1152. user_error('Integer too large', E_USER_NOTICE);
  1153. return false;
  1154. }
  1155. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1156. }
  1157. /**
  1158. * Octet-String-to-Integer primitive
  1159. *
  1160. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1161. *
  1162. * @access private
  1163. * @param String $x
  1164. * @return Math_BigInteger
  1165. */
  1166. function _os2ip($x)
  1167. {
  1168. return new Math_BigInteger($x, 256);
  1169. }
  1170. /**
  1171. * Exponentiate with or without Chinese Remainder Theorem
  1172. *
  1173. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1174. *
  1175. * @access private
  1176. * @param Math_BigInteger $x
  1177. * @return Math_BigInteger
  1178. */
  1179. function _exponentiate($x)
  1180. {
  1181. if (empty($this->primes) || empty($this->coefficients) || empty($this->exponents)) {
  1182. return $x->modPow($this->exponent, $this->modulus);
  1183. }
  1184. $num_primes = count($this->primes);
  1185. if (defined('CRYPT_RSA_DISABLE_BLINDING')) {
  1186. $m_i = array(
  1187. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1188. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1189. );
  1190. $h = $m_i[1]->subtract($m_i[2]);
  1191. $h = $h->multiply($this->coefficients[2]);
  1192. list(, $h) = $h->divide($this->primes[1]);
  1193. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1194. $r = $this->primes[1];
  1195. for ($i = 3; $i <= $num_primes; $i++) {
  1196. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1197. $r = $r->multiply($this->primes[$i - 1]);
  1198. $h = $m_i->subtract($m);
  1199. $h = $h->multiply($this->coefficients[$i]);
  1200. list(, $h) = $h->divide($this->primes[$i]);
  1201. $m = $m->add($r->multiply($h));
  1202. }
  1203. } else {
  1204. $smallest = $this->primes[1];
  1205. for ($i = 2; $i <= $num_primes; $i++) {
  1206. if ($smallest->compare($this->primes[$i]) > 0) {
  1207. $smallest = $this->primes[$i];
  1208. }
  1209. }
  1210. $one = new Math_BigInteger(1);
  1211. $one->setRandomGenerator('crypt_random');
  1212. $r = $one->random($one, $smallest->subtract($one));
  1213. $m_i = array(
  1214. 1 => $this->_blind($x, $r, 1),
  1215. 2 => $this->_blind($x, $r, 2)
  1216. );
  1217. $h = $m_i[1]->subtract($m_i[2]);
  1218. $h = $h->multiply($this->coefficients[2]);
  1219. list(, $h) = $h->divide($this->primes[1]);
  1220. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1221. $r = $this->primes[1];
  1222. for ($i = 3; $i <= $num_primes; $i++) {
  1223. $m_i = $this->_blind($x, $r, $i);
  1224. $r = $r->multiply($this->primes[$i - 1]);
  1225. $h = $m_i->subtract($m);
  1226. $h = $h->multiply($this->coefficients[$i]);
  1227. list(, $h) = $h->divide($this->primes[$i]);
  1228. $m = $m->add($r->multiply($h));
  1229. }
  1230. }
  1231. return $m;
  1232. }
  1233. /**
  1234. * Performs RSA Blinding
  1235. *
  1236. * Protects against timing attacks by employing RSA Blinding.
  1237. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1238. *
  1239. * @access private
  1240. * @param Math_BigInteger $x
  1241. * @param Math_BigInteger $r
  1242. * @param Integer $i
  1243. * @return Math_BigInteger
  1244. */
  1245. function _blind($x, $r, $i)
  1246. {
  1247. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1248. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1249. $r = $r->modInverse($this->primes[$i]);
  1250. $x = $x->multiply($r);
  1251. list(, $x) = $x->divide($this->primes[$i]);
  1252. return $x;
  1253. }
  1254. /**
  1255. * RSAEP
  1256. *
  1257. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1258. *
  1259. * @access private
  1260. * @param Math_BigInteger $m
  1261. * @return Math_BigInteger
  1262. */
  1263. function _rsaep($m)
  1264. {
  1265. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  1266. user_error('Message representative out of range', E_USER_NOTICE);
  1267. return false;
  1268. }
  1269. return $this->_exponentiate($m);
  1270. }
  1271. /**
  1272. * RSADP
  1273. *
  1274. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  1275. *
  1276. * @access private
  1277. * @param Math_BigInteger $c
  1278. * @return Math_BigInteger
  1279. */
  1280. function _rsadp($c)
  1281. {
  1282. if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) {
  1283. user_error('Ciphertext representative out of range', E_USER_NOTICE);
  1284. return false;
  1285. }
  1286. return $this->_exponentiate($c);
  1287. }
  1288. /**
  1289. * RSASP1
  1290. *
  1291. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  1292. *
  1293. * @access private
  1294. * @param Math_BigInteger $m
  1295. * @return Math_BigInteger
  1296. */
  1297. function _rsasp1($m)
  1298. {
  1299. if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) {
  1300. user_error('Message representative out of range', E_USER_NOTICE);
  1301. return false;
  1302. }
  1303. return $this->_exponentiate($m);
  1304. }
  1305. /**
  1306. * RSAVP1
  1307. *
  1308. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  1309. *
  1310. * @access private
  1311. * @param Math_BigInteger $s
  1312. * @return Math_BigInteger
  1313. */
  1314. function _rsavp1($s)
  1315. {
  1316. if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) {
  1317. user_error('Signature representative out of range', E_USER_NOTICE);
  1318. return false;
  1319. }
  1320. return $this->_exponentiate($s);
  1321. }
  1322. /**
  1323. * MGF1
  1324. *
  1325. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  1326. *
  1327. * @access private
  1328. * @param String $mgfSeed
  1329. * @param Integer $mgfLen
  1330. * @return String
  1331. */
  1332. function _mgf1($mgfSeed, $maskLen)
  1333. {
  1334. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  1335. $t = '';
  1336. $count = ceil($maskLen / $this->mgfHLen);
  1337. for ($i = 0; $i < $count; $i++) {
  1338. $c = pack('N', $i);
  1339. $t.= $this->mgfHash->hash($mgfSeed . $c);
  1340. }
  1341. return substr($t, 0, $maskLen);
  1342. }
  1343. /**
  1344. * RSAES-OAEP-ENCRYPT
  1345. *
  1346. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  1347. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  1348. *
  1349. * @access private
  1350. * @param String $m
  1351. * @param String $l
  1352. * @return String
  1353. */
  1354. function _rsaes_oaep_encrypt($m, $l = '')
  1355. {
  1356. $mLen = strlen($m);
  1357. // Length checking
  1358. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1359. // be output.
  1360. if ($mLen > $this->k - 2 * $this->hLen - 2) {
  1361. user_error('Message too long', E_USER_NOTICE);
  1362. return false;
  1363. }
  1364. // EME-OAEP encoding
  1365. $lHash = $this->hash->hash($l);
  1366. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  1367. $db = $lHash . $ps . chr(1) . $m;
  1368. $seed = $this->_random($this->hLen);
  1369. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1370. $maskedDB = $db ^ $dbMask;
  1371. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1372. $maskedSeed = $seed ^ $seedMask;
  1373. $em = chr(0) . $maskedSeed . $maskedDB;
  1374. // RSA encryption
  1375. $m = $this->_os2ip($em);
  1376. $c = $this->_rsaep($m);
  1377. $c = $this->_i2osp($c, $this->k);
  1378. // Output the ciphertext C
  1379. return $c;
  1380. }
  1381. /**
  1382. * RSAES-OAEP-DECRYPT
  1383. *
  1384. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  1385. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  1386. *
  1387. * Note. Care must be taken to ensure that an opponent cannot
  1388. * distinguish the different error conditions in Step 3.g, whether by
  1389. * error message or timing, or, more generally, learn partial
  1390. * information about the encoded message EM. Otherwise an opponent may
  1391. * be able to obtain useful information about the decryption of the
  1392. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  1393. * observed by Manger [36].
  1394. *
  1395. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  1396. *
  1397. * Both the encryption and the decryption operations of RSAES-OAEP take
  1398. * the value of a label L as input. In this version of PKCS #1, L is
  1399. * the empty string; other uses of the label are outside the scope of
  1400. * this document.
  1401. *
  1402. * @access private
  1403. * @param String $c
  1404. * @param String $l
  1405. * @return String
  1406. */
  1407. function _rsaes_oaep_decrypt($c, $l = '')
  1408. {
  1409. // Length checking
  1410. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1411. // be output.
  1412. if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) {
  1413. user_error('Decryption error', E_USER_NOTICE);
  1414. return false;
  1415. }
  1416. // RSA decryption
  1417. $c = $this->_os2ip($c);
  1418. $m = $this->_rsadp($c);
  1419. if ($m === false) {
  1420. user_error('Decryption error', E_USER_NOTICE);
  1421. return false;
  1422. }
  1423. $em = $this->_i2osp($m, $this->k);
  1424. // EME-OAEP decoding
  1425. $lHash = $this->hash->hash($l);
  1426. $y = ord($em[0]);
  1427. $maskedSeed = substr($em, 1, $this->hLen);
  1428. $maskedDB = substr($em, $this->hLen + 1);
  1429. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1430. $seed = $maskedSeed ^ $seedMask;
  1431. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1432. $db = $maskedDB ^ $dbMask;
  1433. $lHash2 = substr($db, 0, $this->hLen);
  1434. $m = substr($db, $this->hLen);
  1435. if ($lHash != $lHash2) {
  1436. user_error('Decryption error', E_USER_NOTICE);
  1437. return false;
  1438. }
  1439. $m = ltrim($m, chr(0));
  1440. if (ord($m[0]) != 1) {
  1441. user_error('Decryption error', E_USER_NOTICE);
  1442. return false;
  1443. }
  1444. // Output the message M
  1445. return substr($m, 1);
  1446. }
  1447. /**
  1448. * RSAES-PKCS1-V1_5-ENCRYPT
  1449. *
  1450. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  1451. *
  1452. * @access private
  1453. * @param String $m
  1454. * @return String
  1455. */
  1456. function _rsaes_pkcs1_v1_5_encrypt($m)
  1457. {
  1458. $mLen = strlen($m);
  1459. // Length checking
  1460. if ($mLen > $this->k - 11) {
  1461. user_error('Message too long', E_USER_NOTICE);
  1462. return false;
  1463. }
  1464. // EME-PKCS1-v1_5 encoding
  1465. $ps = $this->_random($this->k - $mLen - 3, true);
  1466. $em = chr(0) . chr(2) . $ps . chr(0) . $m;
  1467. // RSA encryption
  1468. $m = $this->_os2ip($em);
  1469. $c = $this->_rsaep($m);
  1470. $c = $this->_i2osp($c, $this->k);
  1471. // Output the ciphertext C
  1472. return $c;
  1473. }
  1474. /**
  1475. * RSAES-PKCS1-V1_5-DECRYPT
  1476. *
  1477. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  1478. *
  1479. * For compatability purposes, this function departs slightly from the description given in RFC3447.
  1480. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  1481. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  1482. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  1483. * to be 2 regardless of which key is used. for compatability purposes, we'll just check to make sure the
  1484. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  1485. *
  1486. * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
  1487. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  1488. * not private key encrypted ciphertext's.
  1489. *
  1490. * @access private
  1491. * @param String $c
  1492. * @return String
  1493. */
  1494. function _rsaes_pkcs1_v1_5_decrypt($c)
  1495. {
  1496. // Length checking
  1497. if (strlen($c) != $this->k) { // or if k < 11
  1498. user_error('Decryption error', E_USER_NOTICE);
  1499. return false;
  1500. }
  1501. // RSA decryption
  1502. $c = $this->_os2ip($c);
  1503. $m = $this->_rsadp($c);
  1504. if ($m === false) {
  1505. user_error('Decryption error', E_USER_NOTICE);
  1506. return false;
  1507. }
  1508. $em = $this->_i2osp($m, $this->k);
  1509. // EME-PKCS1-v1_5 decoding
  1510. if (ord($em[0]) != 0 || ord($em[1]) > 2) {
  1511. user_error('Decryption error', E_USER_NOTICE);
  1512. return false;
  1513. }
  1514. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  1515. $m = substr($em, strlen($ps) + 3);
  1516. if (strlen($ps) < 8) {
  1517. user_error('Decryption error', E_USER_NOTICE);
  1518. return false;
  1519. }
  1520. // Output M
  1521. return $m;
  1522. }
  1523. /**
  1524. * EMSA-PSS-ENCODE
  1525. *
  1526. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  1527. *
  1528. * @access private
  1529. * @param String $m
  1530. * @param Integer $emBits
  1531. */
  1532. function _emsa_pss_encode($m, $emBits)
  1533. {
  1534. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1535. // be output.
  1536. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  1537. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  1538. $mHash = $this->hash->hash($m);
  1539. if ($emLen < $this->hLen + $sLen + 2) {
  1540. user_error('Encoding error', E_USER_NOTICE);
  1541. return false;
  1542. }
  1543. $salt = $this->_random($sLen);
  1544. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1545. $h = $this->hash->hash($m2);
  1546. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  1547. $db = $ps . chr(1) . $salt;
  1548. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  1549. $maskedDB = $db ^ $dbMask;
  1550. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  1551. $em = $maskedDB . $h . chr(0xBC);
  1552. return $em;
  1553. }
  1554. /**
  1555. * EMSA-PSS-VERIFY
  1556. *
  1557. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  1558. *
  1559. * @access private
  1560. * @param String $m
  1561. * @param String $em
  1562. * @param Integer $emBits
  1563. * @return String
  1564. */
  1565. function _emsa_pss_verify($m, $em, $emBits)
  1566. {
  1567. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1568. // be output.
  1569. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  1570. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  1571. $mHash = $this->hash->hash($m);
  1572. if ($emLen < $this->hLen + $sLen + 2) {
  1573. return false;
  1574. }
  1575. if ($em[strlen($em) - 1] != chr(0xBC)) {
  1576. return false;
  1577. }
  1578. $maskedDB = substr($em, 0, $em - $this->hLen - 1);
  1579. $h = substr($em, $em - $this->hLen - 1, $this->hLen);
  1580. $temp = chr(0xFF << ($emBits & 7));
  1581. if ((~$maskedDB[0] & $temp) != $temp) {
  1582. return false;
  1583. }
  1584. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  1585. $db = $maskedDB ^ $dbMask;
  1586. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  1587. $temp = $emLen - $this->hLen - $sLen - 2;
  1588. if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) {
  1589. return false;
  1590. }
  1591. $salt = substr($db, $temp + 1); // should be $sLen long
  1592. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1593. $h2 = $this->hash->hash($m2);
  1594. return $h == $h2;
  1595. }
  1596. /**
  1597. * RSASSA-PSS-SIGN
  1598. *
  1599. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  1600. *
  1601. * @access private
  1602. * @param String $m
  1603. * @return String
  1604. */
  1605. function _rsassa_pss_sign($m)
  1606. {
  1607. // EMSA-PSS encoding
  1608. $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  1609. // RSA signature
  1610. $m = $this->_os2ip($em);
  1611. $s = $this->_rsasp1($m);
  1612. $s = $this->_i2osp($s, $this->k);
  1613. // Output the signature S
  1614. return $s;
  1615. }
  1616. /**
  1617. * RSASSA-PSS-VERIFY
  1618. *
  1619. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  1620. *
  1621. * @access private
  1622. * @param String $m
  1623. * @param String $s
  1624. * @return String
  1625. */
  1626. function _rsassa_pss_verify($m, $s)
  1627. {
  1628. // Length checking
  1629. if (strlen($s) != $this->k) {
  1630. user_error('Invalid signature', E_USER_NOTICE);
  1631. return false;
  1632. }
  1633. // RSA verification
  1634. $modBits = 8 * $this->k;
  1635. $s2 = $this->_os2ip($s);
  1636. $m2 = $this->_rsavp1($s2);
  1637. if ($m2 === false) {
  1638. user_error('Invalid signature', E_USER_NOTICE);
  1639. return false;
  1640. }
  1641. $em = $this->_i2osp($m2, $modBits >> 3);
  1642. if ($em === false) {
  1643. user_error('Invalid signature', E_USER_NOTICE);
  1644. return false;
  1645. }
  1646. // EMSA-PSS verification
  1647. return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  1648. }
  1649. /**
  1650. * EMSA-PKCS1-V1_5-ENCODE
  1651. *
  1652. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  1653. *
  1654. * @access private
  1655. * @param String $m
  1656. * @param Integer $emLen
  1657. * @return String
  1658. */
  1659. function _emsa_pkcs1_v1_5_encode($m, $emLen)
  1660. {
  1661. $h = $this->hash->hash($m);
  1662. if ($h === false) {
  1663. return false;
  1664. }
  1665. // see http://tools.ietf.org/html/rfc3447#page-43
  1666. switch ($this->hashName) {
  1667. case 'md2':
  1668. $t = pack('H*', '3020300c06082a864886f70d020205000410');
  1669. break;
  1670. case 'md5':
  1671. $t = pack('H*', '3020300c06082a864886f70d020505000410');
  1672. break;
  1673. case 'sha1':
  1674. $t = pack('H*', '3021300906052b0e03021a05000414');
  1675. break;
  1676. case 'sha256':
  1677. $t = pack('H*', '3031300d060960864801650304020105000420');
  1678. break;
  1679. case 'sha384':
  1680. $t = pack('H*', '3041300d060960864801650304020205000430');
  1681. break;
  1682. case 'sha512':
  1683. $t = pack('H*', '3051300d060960864801650304020305000440');
  1684. }
  1685. $t.= $h;
  1686. $tLen = strlen($t);
  1687. if ($emLen < $tLen + 11) {
  1688. user_error('Intended encoded message length too short', E_USER_NOTICE);
  1689. return false;
  1690. }
  1691. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  1692. $em = "\0\1$ps\0$t";
  1693. return $em;
  1694. }
  1695. /**
  1696. * RSASSA-PKCS1-V1_5-SIGN
  1697. *
  1698. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  1699. *
  1700. * @access private
  1701. * @param String $m
  1702. * @return String
  1703. */
  1704. function _rsassa_pkcs1_v1_5_sign($m)
  1705. {
  1706. // EMSA-PKCS1-v1_5 encoding
  1707. $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  1708. if ($em === false) {
  1709. user_error('RSA modulus too short', E_USER_NOTICE);
  1710. return false;
  1711. }
  1712. // RSA signature
  1713. $m = $this->_os2ip($em);
  1714. $s = $this->_rsasp1($m);
  1715. $s = $this->_i2osp($s, $this->k);
  1716. // Output the signature S
  1717. return $s;
  1718. }
  1719. /**
  1720. * RSASSA-PKCS1-V1_5-VERIFY
  1721. *
  1722. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  1723. *
  1724. * @access private
  1725. * @param String $m
  1726. * @return String
  1727. */
  1728. function _rsassa_pkcs1_v1_5_verify($m, $s)
  1729. {
  1730. // Length checking
  1731. if (strlen($s) != $this->k) {
  1732. user_error('Invalid signature', E_USER_NOTICE);
  1733. return false;
  1734. }
  1735. // RSA verification
  1736. $s = $this->_os2ip($s);
  1737. $m2 = $this->_rsavp1($s);
  1738. if ($m2 === false) {
  1739. user_error('Invalid signature', E_USER_NOTICE);
  1740. return false;
  1741. }
  1742. $em = $this->_i2osp($m2, $this->k);
  1743. if ($em === false) {
  1744. user_error('Invalid signature', E_USER_NOTICE);
  1745. return false;
  1746. }
  1747. // EMSA-PKCS1-v1_5 encoding
  1748. $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  1749. if ($em2 === false) {
  1750. user_error('RSA modulus too short', E_USER_NOTICE);
  1751. return false;
  1752. }
  1753. // Compare
  1754. return $em === $em2;
  1755. }
  1756. /**
  1757. * Set Encryption Mode
  1758. *
  1759. * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
  1760. *
  1761. * @access public
  1762. * @param Integer $mode
  1763. */
  1764. function setEncryptionMode($mode)
  1765. {
  1766. $this->encryptionMode = $mode;
  1767. }
  1768. /**
  1769. * Set Signature Mode
  1770. *
  1771. * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
  1772. *
  1773. * @access public
  1774. * @param Integer $mode
  1775. */
  1776. function setSignatureMode($mode)
  1777. {
  1778. $this->signatureMode = $mode;
  1779. }
  1780. /**
  1781. * Encryption
  1782. *
  1783. * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
  1784. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  1785. * be concatenated together.
  1786. *
  1787. * @see decrypt()
  1788. * @access public
  1789. * @param String $plaintext
  1790. * @return String
  1791. */
  1792. function encrypt($plaintext)
  1793. {
  1794. switch ($this->encryptionMode) {
  1795. case CRYPT_RSA_ENCRYPTION_PKCS1:
  1796. $length = $this->k - 11;
  1797. if ($length <= 0) {
  1798. return false;
  1799. }
  1800. $plaintext = str_split($plaintext, $length);
  1801. $ciphertext = '';
  1802. foreach ($plaintext as $m) {
  1803. $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
  1804. }
  1805. return $ciphertext;
  1806. //case CRYPT_RSA_ENCRYPTION_OAEP:
  1807. default:
  1808. $length = $this->k - 2 * $this->hLen - 2;
  1809. if ($length <= 0) {
  1810. return false;
  1811. }
  1812. $plaintext = str_split($plaintext, $length);
  1813. $ciphertext = '';
  1814. foreach ($plaintext as $m) {
  1815. $ciphertext.= $this->_rsaes_oaep_encrypt($m);
  1816. }
  1817. return $ciphertext;
  1818. }
  1819. }
  1820. /**
  1821. * Decryption
  1822. *
  1823. * @see encrypt()
  1824. * @access public
  1825. * @param String $plaintext
  1826. * @return String
  1827. */
  1828. function decrypt($ciphertext)
  1829. {
  1830. if ($this->k <= 0) {
  1831. return false;
  1832. }
  1833. $ciphertext = str_split($ciphertext, $this->k);
  1834. $plaintext = '';
  1835. switch ($this->encryptionMode) {
  1836. case CRYPT_RSA_ENCRYPTION_PKCS1:
  1837. $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
  1838. break;
  1839. //case CRYPT_RSA_ENCRYPTION_OAEP:
  1840. default:
  1841. $decrypt = '_rsaes_oaep_decrypt';
  1842. }
  1843. foreach ($ciphertext as $c) {
  1844. $temp = $this->$decrypt($c);
  1845. if ($temp === false) {
  1846. return false;
  1847. }
  1848. $plaintext.= $temp;
  1849. }
  1850. return $plaintext;
  1851. }
  1852. /**
  1853. * Create a signature
  1854. *
  1855. * @see verify()
  1856. * @access public
  1857. * @param String $message
  1858. * @return String
  1859. */
  1860. function sign($message)
  1861. {
  1862. if (empty($this->modulus) || empty($this->exponent)) {
  1863. return false;
  1864. }
  1865. switch ($this->signatureMode) {
  1866. case CRYPT_RSA_SIGNATURE_PKCS1:
  1867. return $this->_rsassa_pkcs1_v1_5_sign($message);
  1868. //case CRYPT_RSA_SIGNATURE_PSS:
  1869. default:
  1870. return $this->_rsassa_pss_sign($message);
  1871. }
  1872. }
  1873. /**
  1874. * Verifies a signature
  1875. *
  1876. * @see sign()
  1877. * @access public
  1878. * @param String $message
  1879. * @param String $signature
  1880. * @return Boolean
  1881. */
  1882. function verify($message, $signature)
  1883. {
  1884. if (empty($this->modulus) || empty($this->exponent)) {
  1885. return false;
  1886. }
  1887. switch ($this->signatureMode) {
  1888. case CRYPT_RSA_SIGNATURE_PKCS1:
  1889. return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  1890. //case CRYPT_RSA_SIGNATURE_PSS:
  1891. default:
  1892. return $this->_rsassa_pss_verify($message, $signature);
  1893. }
  1894. }
  1895. }