PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/php5-3/core/tools/secure/crypt/RSA.class.php

https://bitbucket.org/ronaldobrandini/framework
PHP | 2652 lines | 1477 code | 282 blank | 893 comment | 235 complexity | 55deb97840ebe742c5152ac7fd5c73d9 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. <?php
  2. namespace core\tools\secure\crypt;
  3. /*
  4. * To change this license header, choose License Headers in Project Properties.
  5. * To change this template file, choose Tools | Templates
  6. * and open the template in the editor.
  7. */
  8. /**
  9. * Description of RSA
  10. *
  11. * @author ronaldo.silva
  12. * @version 1.0 22/08/2014
  13. */
  14. class RSA{
  15. /**
  16. * Precomputed Zero
  17. *
  18. * @var Array
  19. * @access private
  20. */
  21. private $zero;
  22. /**
  23. * Precomputed One
  24. *
  25. * @var Array
  26. * @access private
  27. */
  28. private $one;
  29. /**
  30. * Private Key Format
  31. *
  32. * @var Integer
  33. * @access private
  34. */
  35. private $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1;
  36. /**
  37. * Public Key Format
  38. *
  39. * @var Integer
  40. * @access public
  41. */
  42. public $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS8;
  43. /**
  44. * Modulus (ie. n)
  45. *
  46. * @var \core\tools\secure\math\BigInteger
  47. * @access private
  48. */
  49. private $modulus;
  50. /**
  51. * Modulus length
  52. *
  53. * @var \core\tools\secure\math\BigInteger
  54. * @access private
  55. */
  56. private $k;
  57. /**
  58. * Exponent (ie. e or d)
  59. *
  60. * @var \core\tools\secure\math\BigInteger
  61. * @access private
  62. */
  63. private $exponent;
  64. /**
  65. * Primes for Chinese Remainder Theorem (ie. p and q)
  66. *
  67. * @var Array
  68. * @access private
  69. */
  70. private $primes;
  71. /**
  72. * Exponents for Chinese Remainder Theorem (ie. dP and dQ)
  73. *
  74. * @var Array
  75. * @access private
  76. */
  77. private $exponents;
  78. /**
  79. * Coefficients for Chinese Remainder Theorem (ie. qInv)
  80. *
  81. * @var Array
  82. * @access private
  83. */
  84. private $coefficients;
  85. /**
  86. * Hash name
  87. *
  88. * @var String
  89. * @access private
  90. */
  91. private $hashName;
  92. /**
  93. * Hash function
  94. *
  95. * @var Hash
  96. * @access private
  97. */
  98. private $hash;
  99. /**
  100. * Length of hash function output
  101. *
  102. * @var Integer
  103. * @access private
  104. */
  105. private $hLen;
  106. /**
  107. * Length of salt
  108. *
  109. * @var Integer
  110. * @access private
  111. */
  112. private $sLen;
  113. /**
  114. * Hash function for the Mask Generation Function
  115. *
  116. * @var Hash
  117. * @access private
  118. */
  119. private $mgfHash;
  120. /**
  121. * Length of MGF hash function output
  122. *
  123. * @var Integer
  124. * @access private
  125. */
  126. private $mgfHLen;
  127. /**
  128. * Encryption mode
  129. *
  130. * @var Integer
  131. * @access private
  132. */
  133. private $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP;
  134. /**
  135. * Signature mode
  136. *
  137. * @var Integer
  138. * @access private
  139. */
  140. private $signatureMode = CRYPT_RSA_SIGNATURE_PSS;
  141. /**
  142. * Public Exponent
  143. *
  144. * @var Mixed
  145. * @access private
  146. */
  147. private $publicExponent = false;
  148. /**
  149. * Password
  150. *
  151. * @var String
  152. * @access private
  153. */
  154. private $password = false;
  155. /**
  156. * Components
  157. *
  158. * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions -
  159. * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't.
  160. *
  161. * @see Crypt_RSA::_start_element_handler()
  162. * @var Array
  163. * @access private
  164. */
  165. private $components = array();
  166. /**
  167. * Current String
  168. *
  169. * For use with parsing XML formatted keys.
  170. *
  171. * @see Crypt_RSA::_character_handler()
  172. * @see Crypt_RSA::_stop_element_handler()
  173. * @var Mixed
  174. * @access private
  175. */
  176. private $current;
  177. /**
  178. * OpenSSL configuration file name.
  179. *
  180. * Set to null to use system configuration file.
  181. * @see Crypt_RSA::createKey()
  182. * @var Mixed
  183. * @Access public
  184. */
  185. public $configFile;
  186. /**
  187. * Public key comment field.
  188. *
  189. * @var String
  190. * @access private
  191. */
  192. private $comment = 'phpseclib-generated-key';
  193. /**
  194. * The constructor
  195. *
  196. * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason
  197. * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires
  198. * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late.
  199. *
  200. * @return Crypt_RSA
  201. * @access public
  202. */
  203. public function __construct(){
  204. $this->configFile = CRYPT_RSA_OPENSSL_CONFIG;
  205. if(!defined('CRYPT_RSA_MODE')){
  206. // Math/\core\tools\secure\math\BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular,
  207. // Math/\core\tools\secure\math\BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/\core\tools\secure\math\BigInteger
  208. // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either.
  209. if(defined('MATH_BIGINTEGER_OPENSSL_DISABLE')){
  210. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  211. }
  212. switch(!defined('CRYPT_RSA_MODE')){ // ie. only run this if the above didn't set CRYPT_RSA_MODE already
  213. // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0
  214. case!function_exists('openssl_pkey_get_details'):
  215. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  216. break;
  217. case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile):
  218. // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work
  219. ob_start();
  220. @phpinfo();
  221. $content = ob_get_contents();
  222. ob_end_clean();
  223. preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches);
  224. $versions = array();
  225. if(!empty($matches[1])){
  226. for($i = 0; $i < count($matches[1]); $i++){
  227. $versions[$matches[1][$i]] = trim(str_replace('=>', '', strip_tags($matches[2][$i])));
  228. }
  229. }
  230. // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+
  231. switch(true){
  232. case!isset($versions['Header']):
  233. case!isset($versions['Library']):
  234. case $versions['Header'] == $versions['Library']:
  235. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL);
  236. break;
  237. default:
  238. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  239. define('MATH_BIGINTEGER_OPENSSL_DISABLE', true);
  240. }
  241. break;
  242. case true:
  243. define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
  244. }
  245. }
  246. $this->zero = new \core\tools\secure\math\BigInteger();
  247. $this->one = new \core\tools\secure\math\BigInteger(1);
  248. $this->hash = new Hash('sha1');
  249. $this->hLen = $this->hash->getLength();
  250. $this->hashName = 'sha1';
  251. $this->mgfHash = new Hash('sha1');
  252. $this->mgfHLen = $this->mgfHash->getLength();
  253. }
  254. /**
  255. * Create public / private key pair
  256. *
  257. * Returns an array with the following three elements:
  258. * - 'privatekey': The private key.
  259. * - 'publickey': The public key.
  260. * - 'partialkey': A partially computed key (if the execution time exceeded $timeout).
  261. * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing.
  262. *
  263. * @access public
  264. * @param optional Integer $bits
  265. * @param optional Integer $timeout
  266. * @param optional \core\tools\secure\math\BigInteger $p
  267. */
  268. public function createKey($bits = 1024, $timeout = false, $partial = array()){
  269. if(!defined('CRYPT_RSA_EXPONENT')){
  270. // http://en.wikipedia.org/wiki/65537_%28number%29
  271. define('CRYPT_RSA_EXPONENT', '65537');
  272. }
  273. // per <http://cseweb.ucsd.edu/~hovav/dist/survey.pdf#page=5>, this number ought not result in primes smaller
  274. // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME
  275. // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if
  276. // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then
  277. // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key
  278. // generation when there's a chance neither gmp nor OpenSSL are installed)
  279. if(!defined('CRYPT_RSA_SMALLEST_PRIME')){
  280. define('CRYPT_RSA_SMALLEST_PRIME', 4096);
  281. }
  282. // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum
  283. if(CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537){
  284. $config = array();
  285. if(isset($this->configFile)){
  286. $config['config'] = $this->configFile;
  287. }
  288. $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config);
  289. openssl_pkey_export($rsa, $privatekey, null, $config);
  290. $publickey = openssl_pkey_get_details($rsa);
  291. $publickey = $publickey['key'];
  292. $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1)));
  293. $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1)));
  294. // clear the buffer of error strings stemming from a minimalistic openssl.cnf
  295. while(openssl_error_string() !== false);
  296. return array(
  297. 'privatekey' => $privatekey,
  298. 'publickey' => $publickey,
  299. 'partialkey' => false
  300. );
  301. }
  302. static $e;
  303. if(!isset($e)){
  304. $e = new \core\tools\secure\math\BigInteger(CRYPT_RSA_EXPONENT);
  305. }
  306. extract($this->_generateMinMax($bits));
  307. $absoluteMin = $min;
  308. $temp = $bits >> 1; // divide by two to see how many bits P and Q would be
  309. if($temp > CRYPT_RSA_SMALLEST_PRIME){
  310. $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME);
  311. $temp = CRYPT_RSA_SMALLEST_PRIME;
  312. }else{
  313. $num_primes = 2;
  314. }
  315. extract($this->_generateMinMax($temp + $bits % $temp));
  316. $finalMax = $max;
  317. extract($this->_generateMinMax($temp));
  318. $generator = new \core\tools\secure\math\BigInteger();
  319. $n = $this->one->copy();
  320. if(!empty($partial)){
  321. extract(unserialize($partial));
  322. }else{
  323. $exponents = $coefficients = $primes = array();
  324. $lcm = array(
  325. 'top' => $this->one->copy(),
  326. 'bottom' => false
  327. );
  328. }
  329. $start = time();
  330. $i0 = count($primes) + 1;
  331. do{
  332. for($i = $i0; $i <= $num_primes; $i++){
  333. if($timeout !== false){
  334. $timeout-= time() - $start;
  335. $start = time();
  336. if($timeout <= 0){
  337. return array(
  338. 'privatekey' => '',
  339. 'publickey' => '',
  340. 'partialkey' => serialize(array(
  341. 'primes' => $primes,
  342. 'coefficients' => $coefficients,
  343. 'lcm' => $lcm,
  344. 'exponents' => $exponents
  345. ))
  346. );
  347. }
  348. }
  349. if($i == $num_primes){
  350. list($min, $temp) = $absoluteMin->divide($n);
  351. if(!$temp->equals($this->zero)){
  352. $min = $min->add($this->one); // ie. ceil()
  353. }
  354. $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout);
  355. }else{
  356. $primes[$i] = $generator->randomPrime($min, $max, $timeout);
  357. }
  358. if($primes[$i] === false){ // if we've reached the timeout
  359. if(count($primes) > 1){
  360. $partialkey = '';
  361. }else{
  362. array_pop($primes);
  363. $partialkey = serialize(array(
  364. 'primes' => $primes,
  365. 'coefficients' => $coefficients,
  366. 'lcm' => $lcm,
  367. 'exponents' => $exponents
  368. ));
  369. }
  370. return array(
  371. 'privatekey' => '',
  372. 'publickey' => '',
  373. 'partialkey' => $partialkey
  374. );
  375. }
  376. // the first coefficient is calculated differently from the rest
  377. // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1])
  378. if($i > 2){
  379. $coefficients[$i] = $n->modInverse($primes[$i]);
  380. }
  381. $n = $n->multiply($primes[$i]);
  382. $temp = $primes[$i]->subtract($this->one);
  383. // textbook RSA implementations use Euler's totient function instead of the least common multiple.
  384. // see http://en.wikipedia.org/wiki/Euler%27s_totient_function
  385. $lcm['top'] = $lcm['top']->multiply($temp);
  386. $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp);
  387. $exponents[$i] = $e->modInverse($temp);
  388. }
  389. list($temp) = $lcm['top']->divide($lcm['bottom']);
  390. $gcd = $temp->gcd($e);
  391. $i0 = 1;
  392. }while(!$gcd->equals($this->one));
  393. $d = $e->modInverse($temp);
  394. $coefficients[2] = $primes[2]->modInverse($primes[1]);
  395. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.2>:
  396. // RSAPrivateKey ::= SEQUENCE {
  397. // version Version,
  398. // modulus INTEGER, -- n
  399. // publicExponent INTEGER, -- e
  400. // privateExponent INTEGER, -- d
  401. // prime1 INTEGER, -- p
  402. // prime2 INTEGER, -- q
  403. // exponent1 INTEGER, -- d mod (p-1)
  404. // exponent2 INTEGER, -- d mod (q-1)
  405. // coefficient INTEGER, -- (inverse of q) mod p
  406. // otherPrimeInfos OtherPrimeInfos OPTIONAL
  407. // }
  408. return array(
  409. 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients),
  410. 'publickey' => $this->_convertPublicKey($n, $e),
  411. 'partialkey' => false
  412. );
  413. }
  414. /**
  415. * Convert a private key to the appropriate format.
  416. *
  417. * @access private
  418. * @see setPrivateKeyFormat()
  419. * @param String $RSAPrivateKey
  420. * @return String
  421. */
  422. private function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients){
  423. $num_primes = count($primes);
  424. $raw = array(
  425. 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi
  426. 'modulus' => $n->toBytes(true),
  427. 'publicExponent' => $e->toBytes(true),
  428. 'privateExponent' => $d->toBytes(true),
  429. 'prime1' => $primes[1]->toBytes(true),
  430. 'prime2' => $primes[2]->toBytes(true),
  431. 'exponent1' => $exponents[1]->toBytes(true),
  432. 'exponent2' => $exponents[2]->toBytes(true),
  433. 'coefficient' => $coefficients[2]->toBytes(true)
  434. );
  435. // if the format in question does not support multi-prime rsa and multi-prime rsa was used,
  436. // call _convertPublicKey() instead.
  437. switch($this->privateKeyFormat){
  438. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  439. if($num_primes != 2){
  440. return false;
  441. }
  442. return "<RSAKeyValue>\r\n" .
  443. ' <Modulus>' . base64_encode($raw['modulus']) . "</Modulus>\r\n" .
  444. ' <Exponent>' . base64_encode($raw['publicExponent']) . "</Exponent>\r\n" .
  445. ' <P>' . base64_encode($raw['prime1']) . "</P>\r\n" .
  446. ' <Q>' . base64_encode($raw['prime2']) . "</Q>\r\n" .
  447. ' <DP>' . base64_encode($raw['exponent1']) . "</DP>\r\n" .
  448. ' <DQ>' . base64_encode($raw['exponent2']) . "</DQ>\r\n" .
  449. ' <InverseQ>' . base64_encode($raw['coefficient']) . "</InverseQ>\r\n" .
  450. ' <D>' . base64_encode($raw['privateExponent']) . "</D>\r\n" .
  451. '</RSAKeyValue>';
  452. break;
  453. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  454. if($num_primes != 2){
  455. return false;
  456. }
  457. $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: ";
  458. $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none';
  459. $key.= $encryption;
  460. $key.= "\r\nComment: " . $this->comment . "\r\n";
  461. $public = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($raw['publicExponent']), $raw['publicExponent'], strlen($raw['modulus']), $raw['modulus']
  462. );
  463. $source = pack('Na*Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($encryption), $encryption, strlen($this->comment), $this->comment, strlen($public), $public
  464. );
  465. $public = base64_encode($public);
  466. $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n";
  467. $key.= chunk_split($public, 64);
  468. $private = pack('Na*Na*Na*Na*', strlen($raw['privateExponent']), $raw['privateExponent'], strlen($raw['prime1']), $raw['prime1'], strlen($raw['prime2']), $raw['prime2'], strlen($raw['coefficient']), $raw['coefficient']
  469. );
  470. if(empty($this->password) && !is_string($this->password)){
  471. $source.= pack('Na*', strlen($private), $private);
  472. $hashkey = 'putty-private-key-file-mac-key';
  473. }else{
  474. $private.= crypt_random_string(16 - (strlen($private) & 15));
  475. $source.= pack('Na*', strlen($private), $private);
  476. if(!class_exists('Crypt_AES')){
  477. include_once 'Crypt/AES.php';
  478. }
  479. $sequence = 0;
  480. $symkey = '';
  481. while(strlen($symkey) < 32){
  482. $temp = pack('Na*', $sequence++, $this->password);
  483. $symkey.= pack('H*', sha1($temp));
  484. }
  485. $symkey = substr($symkey, 0, 32);
  486. $crypto = new Crypt_AES();
  487. $crypto->setKey($symkey);
  488. $crypto->disablePadding();
  489. $private = $crypto->encrypt($private);
  490. $hashkey = 'putty-private-key-file-mac-key' . $this->password;
  491. }
  492. $private = base64_encode($private);
  493. $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n";
  494. $key.= chunk_split($private, 64);
  495. if(!class_exists('Hash')){
  496. include_once 'Crypt/Hash.php';
  497. }
  498. $hash = new Hash('sha1');
  499. $hash->setKey(pack('H*', sha1($hashkey)));
  500. $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n";
  501. return $key;
  502. default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1
  503. $components = array();
  504. foreach($raw as $name => $value){
  505. $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value);
  506. }
  507. $RSAPrivateKey = implode('', $components);
  508. if($num_primes > 2){
  509. $OtherPrimeInfos = '';
  510. for($i = 3; $i <= $num_primes; $i++){
  511. // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo
  512. //
  513. // OtherPrimeInfo ::= SEQUENCE {
  514. // prime INTEGER, -- ri
  515. // exponent INTEGER, -- di
  516. // coefficient INTEGER -- ti
  517. // }
  518. $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true));
  519. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true));
  520. $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true));
  521. $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo);
  522. }
  523. $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos);
  524. }
  525. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  526. if($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8){
  527. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  528. $RSAPrivateKey = pack('Ca*a*Ca*a*', CRYPT_RSA_ASN1_INTEGER, "\01\00", $rsaOID, 4, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  529. );
  530. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  531. if(!empty($this->password) || is_string($this->password)){
  532. $salt = crypt_random_string(8);
  533. $iterationCount = 2048;
  534. if(!class_exists('Crypt_DES')){
  535. include_once 'Crypt/DES.php';
  536. }
  537. $crypto = new Crypt_DES();
  538. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  539. $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey);
  540. $parameters = pack('Ca*a*Ca*N', CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($salt)), $salt, CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(4), $iterationCount
  541. );
  542. $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03";
  543. $encryptionAlgorithm = pack('Ca*a*Ca*a*', CRYPT_RSA_ASN1_OBJECT, $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), $pbeWithMD5AndDES_CBC, CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($parameters)), $parameters
  544. );
  545. $RSAPrivateKey = pack('Ca*a*Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($encryptionAlgorithm)), $encryptionAlgorithm, CRYPT_RSA_ASN1_OCTETSTRING, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey
  546. );
  547. $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey);
  548. $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" .
  549. chunk_split(base64_encode($RSAPrivateKey), 64) .
  550. '-----END ENCRYPTED PRIVATE KEY-----';
  551. }else{
  552. $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" .
  553. chunk_split(base64_encode($RSAPrivateKey), 64) .
  554. '-----END PRIVATE KEY-----';
  555. }
  556. return $RSAPrivateKey;
  557. }
  558. if(!empty($this->password) || is_string($this->password)){
  559. $iv = crypt_random_string(8);
  560. $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key
  561. $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8);
  562. if(!class_exists('Crypt_TripleDES')){
  563. include_once 'Crypt/TripleDES.php';
  564. }
  565. $des = new Crypt_TripleDES();
  566. $des->setKey($symkey);
  567. $des->setIV($iv);
  568. $iv = strtoupper(bin2hex($iv));
  569. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  570. "Proc-Type: 4,ENCRYPTED\r\n" .
  571. "DEK-Info: DES-EDE3-CBC,$iv\r\n" .
  572. "\r\n" .
  573. chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) .
  574. '-----END RSA PRIVATE KEY-----';
  575. }else{
  576. $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" .
  577. chunk_split(base64_encode($RSAPrivateKey), 64) .
  578. '-----END RSA PRIVATE KEY-----';
  579. }
  580. return $RSAPrivateKey;
  581. }
  582. }
  583. /**
  584. * Convert a public key to the appropriate format
  585. *
  586. * @access private
  587. * @see setPublicKeyFormat()
  588. * @param String $RSAPrivateKey
  589. * @return String
  590. */
  591. private function _convertPublicKey($n, $e){
  592. $modulus = $n->toBytes(true);
  593. $publicExponent = $e->toBytes(true);
  594. switch($this->publicKeyFormat){
  595. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  596. return array('e' => $e->copy(), 'n' => $n->copy());
  597. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  598. return "<RSAKeyValue>\r\n" .
  599. ' <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
  600. ' <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
  601. '</RSAKeyValue>';
  602. break;
  603. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  604. // from <http://tools.ietf.org/html/rfc4253#page-15>:
  605. // string "ssh-rsa"
  606. // mpint e
  607. // mpint n
  608. $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
  609. $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;
  610. return $RSAPublicKey;
  611. default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
  612. // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
  613. // RSAPublicKey ::= SEQUENCE {
  614. // modulus INTEGER, -- n
  615. // publicExponent INTEGER -- e
  616. // }
  617. $components = array(
  618. 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
  619. 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
  620. );
  621. $RSAPublicKey = pack('Ca*a*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), $components['modulus'], $components['publicExponent']
  622. );
  623. if($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW){
  624. $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
  625. chunk_split(base64_encode($RSAPublicKey), 64) .
  626. '-----END RSA PUBLIC KEY-----';
  627. }else{
  628. // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
  629. $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
  630. $RSAPublicKey = chr(0) . $RSAPublicKey;
  631. $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;
  632. $RSAPublicKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), $rsaOID . $RSAPublicKey
  633. );
  634. $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
  635. chunk_split(base64_encode($RSAPublicKey), 64) .
  636. '-----END PUBLIC KEY-----';
  637. }
  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. private function _parseKey($key, $type){
  652. if($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)){
  653. return false;
  654. }
  655. switch($type){
  656. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  657. if(!is_array($key)){
  658. return false;
  659. }
  660. $components = array();
  661. switch(true){
  662. case isset($key['e']):
  663. $components['publicExponent'] = $key['e']->copy();
  664. break;
  665. case isset($key['exponent']):
  666. $components['publicExponent'] = $key['exponent']->copy();
  667. break;
  668. case isset($key['publicExponent']):
  669. $components['publicExponent'] = $key['publicExponent']->copy();
  670. break;
  671. case isset($key[0]):
  672. $components['publicExponent'] = $key[0]->copy();
  673. }
  674. switch(true){
  675. case isset($key['n']):
  676. $components['modulus'] = $key['n']->copy();
  677. break;
  678. case isset($key['modulo']):
  679. $components['modulus'] = $key['modulo']->copy();
  680. break;
  681. case isset($key['modulus']):
  682. $components['modulus'] = $key['modulus']->copy();
  683. break;
  684. case isset($key[1]):
  685. $components['modulus'] = $key[1]->copy();
  686. }
  687. return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false;
  688. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  689. case CRYPT_RSA_PRIVATE_FORMAT_PKCS8:
  690. case CRYPT_RSA_PUBLIC_FORMAT_PKCS1:
  691. /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is
  692. "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to
  693. protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding
  694. two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here:
  695. http://tools.ietf.org/html/rfc1421#section-4.6.1.1
  696. http://tools.ietf.org/html/rfc1421#section-4.6.1.3
  697. DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell.
  698. DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation
  699. function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's
  700. own implementation. ie. the implementation *is* the standard and any bugs that may exist in that
  701. implementation are part of the standard, as well.
  702. * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */
  703. if(preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)){
  704. $iv = pack('H*', trim($matches[2]));
  705. $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key
  706. $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8)));
  707. // remove the Proc-Type / DEK-Info sections as they're no longer needed
  708. $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key);
  709. $ciphertext = $this->_extractBER($key);
  710. if($ciphertext === false){
  711. $ciphertext = $key;
  712. }
  713. switch($matches[1]){
  714. case 'AES-256-CBC':
  715. if(!class_exists('Crypt_AES')){
  716. include_once 'Crypt/AES.php';
  717. }
  718. $crypto = new Crypt_AES();
  719. break;
  720. case 'AES-128-CBC':
  721. if(!class_exists('Crypt_AES')){
  722. include_once 'Crypt/AES.php';
  723. }
  724. $symkey = substr($symkey, 0, 16);
  725. $crypto = new Crypt_AES();
  726. break;
  727. case 'DES-EDE3-CFB':
  728. if(!class_exists('Crypt_TripleDES')){
  729. include_once 'Crypt/TripleDES.php';
  730. }
  731. $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
  732. break;
  733. case 'DES-EDE3-CBC':
  734. if(!class_exists('Crypt_TripleDES')){
  735. include_once 'Crypt/TripleDES.php';
  736. }
  737. $symkey = substr($symkey, 0, 24);
  738. $crypto = new Crypt_TripleDES();
  739. break;
  740. case 'DES-CBC':
  741. if(!class_exists('Crypt_DES')){
  742. include_once 'Crypt/DES.php';
  743. }
  744. $crypto = new Crypt_DES();
  745. break;
  746. default:
  747. return false;
  748. }
  749. $crypto->setKey($symkey);
  750. $crypto->setIV($iv);
  751. $decoded = $crypto->decrypt($ciphertext);
  752. }else{
  753. $decoded = $this->_extractBER($key);
  754. }
  755. if($decoded !== false){
  756. $key = $decoded;
  757. }
  758. $components = array();
  759. if(ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE){
  760. return false;
  761. }
  762. if($this->_decodeLength($key) != strlen($key)){
  763. return false;
  764. }
  765. $tag = ord($this->_string_shift($key));
  766. /* intended for keys for which OpenSSL's asn1parse returns the following:
  767. 0:d=0 hl=4 l= 631 cons: SEQUENCE
  768. 4:d=1 hl=2 l= 1 prim: INTEGER :00
  769. 7:d=1 hl=2 l= 13 cons: SEQUENCE
  770. 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  771. 20:d=2 hl=2 l= 0 prim: NULL
  772. 22:d=1 hl=4 l= 609 prim: OCTET STRING
  773. ie. PKCS8 keys */
  774. if($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30"){
  775. $this->_string_shift($key, 3);
  776. $tag = CRYPT_RSA_ASN1_SEQUENCE;
  777. }
  778. if($tag == CRYPT_RSA_ASN1_SEQUENCE){
  779. $temp = $this->_string_shift($key, $this->_decodeLength($key));
  780. if(ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT){
  781. return false;
  782. }
  783. $length = $this->_decodeLength($temp);
  784. switch($this->_string_shift($temp, $length)){
  785. case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption
  786. break;
  787. case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC
  788. /*
  789. PBEParameter ::= SEQUENCE {
  790. salt OCTET STRING (SIZE(8)),
  791. iterationCount INTEGER }
  792. */
  793. if(ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE){
  794. return false;
  795. }
  796. if($this->_decodeLength($temp) != strlen($temp)){
  797. return false;
  798. }
  799. $this->_string_shift($temp); // assume it's an octet string
  800. $salt = $this->_string_shift($temp, $this->_decodeLength($temp));
  801. if(ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER){
  802. return false;
  803. }
  804. $this->_decodeLength($temp);
  805. list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT));
  806. $this->_string_shift($key); // assume it's an octet string
  807. $length = $this->_decodeLength($key);
  808. if(strlen($key) != $length){
  809. return false;
  810. }
  811. if(!class_exists('Crypt_DES')){
  812. include_once 'Crypt/DES.php';
  813. }
  814. $crypto = new Crypt_DES();
  815. $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount);
  816. $key = $crypto->decrypt($key);
  817. if($key === false){
  818. return false;
  819. }
  820. return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
  821. default:
  822. return false;
  823. }
  824. /* intended for keys for which OpenSSL's asn1parse returns the following:
  825. 0:d=0 hl=4 l= 290 cons: SEQUENCE
  826. 4:d=1 hl=2 l= 13 cons: SEQUENCE
  827. 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
  828. 17:d=2 hl=2 l= 0 prim: NULL
  829. 19:d=1 hl=4 l= 271 prim: BIT STRING */
  830. $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag
  831. $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length
  832. // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of
  833. // unused bits in the final subsequent octet. The number shall be in the range zero to seven."
  834. // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2)
  835. if($tag == CRYPT_RSA_ASN1_BITSTRING){
  836. $this->_string_shift($key);
  837. }
  838. if(ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE){
  839. return false;
  840. }
  841. if($this->_decodeLength($key) != strlen($key)){
  842. return false;
  843. }
  844. $tag = ord($this->_string_shift($key));
  845. }
  846. if($tag != CRYPT_RSA_ASN1_INTEGER){
  847. return false;
  848. }
  849. $length = $this->_decodeLength($key);
  850. $temp = $this->_string_shift($key, $length);
  851. if(strlen($temp) != 1 || ord($temp) > 2){
  852. $components['modulus'] = new \core\tools\secure\math\BigInteger($temp, 256);
  853. $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER
  854. $length = $this->_decodeLength($key);
  855. $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  856. return $components;
  857. }
  858. if(ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER){
  859. return false;
  860. }
  861. $length = $this->_decodeLength($key);
  862. $components['modulus'] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  863. $this->_string_shift($key);
  864. $length = $this->_decodeLength($key);
  865. $components['publicExponent'] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  866. $this->_string_shift($key);
  867. $length = $this->_decodeLength($key);
  868. $components['privateExponent'] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  869. $this->_string_shift($key);
  870. $length = $this->_decodeLength($key);
  871. $components['primes'] = array(1 => new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256));
  872. $this->_string_shift($key);
  873. $length = $this->_decodeLength($key);
  874. $components['primes'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  875. $this->_string_shift($key);
  876. $length = $this->_decodeLength($key);
  877. $components['exponents'] = array(1 => new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256));
  878. $this->_string_shift($key);
  879. $length = $this->_decodeLength($key);
  880. $components['exponents'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  881. $this->_string_shift($key);
  882. $length = $this->_decodeLength($key);
  883. $components['coefficients'] = array(2 => new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256));
  884. if(!empty($key)){
  885. if(ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE){
  886. return false;
  887. }
  888. $this->_decodeLength($key);
  889. while(!empty($key)){
  890. if(ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE){
  891. return false;
  892. }
  893. $this->_decodeLength($key);
  894. $key = substr($key, 1);
  895. $length = $this->_decodeLength($key);
  896. $components['primes'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  897. $this->_string_shift($key);
  898. $length = $this->_decodeLength($key);
  899. $components['exponents'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  900. $this->_string_shift($key);
  901. $length = $this->_decodeLength($key);
  902. $components['coefficients'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), 256);
  903. }
  904. }
  905. return $components;
  906. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  907. $parts = explode(' ', $key, 3);
  908. $key = isset($parts[1]) ? base64_decode($parts[1]) : false;
  909. if($key === false){
  910. return false;
  911. }
  912. $comment = isset($parts[2]) ? $parts[2] : false;
  913. $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa";
  914. if(strlen($key) <= 4){
  915. return false;
  916. }
  917. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  918. $publicExponent = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), -256);
  919. if(strlen($key) <= 4){
  920. return false;
  921. }
  922. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  923. $modulus = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), -256);
  924. if($cleanup && strlen($key)){
  925. if(strlen($key) <= 4){
  926. return false;
  927. }
  928. extract(unpack('Nlength', $this->_string_shift($key, 4)));
  929. $realModulus = new \core\tools\secure\math\BigInteger($this->_string_shift($key, $length), -256);
  930. return strlen($key) ? false : array(
  931. 'modulus' => $realModulus,
  932. 'publicExponent' => $modulus,
  933. 'comment' => $comment
  934. );
  935. }else{
  936. return strlen($key) ? false : array(
  937. 'modulus' => $modulus,
  938. 'publicExponent' => $publicExponent,
  939. 'comment' => $comment
  940. );
  941. }
  942. // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue
  943. // http://en.wikipedia.org/wiki/XML_Signature
  944. case CRYPT_RSA_PRIVATE_FORMAT_XML:
  945. case CRYPT_RSA_PUBLIC_FORMAT_XML:
  946. $this->components = array();
  947. $xml = xml_parser_create('UTF-8');
  948. xml_set_object($xml, $this);
  949. xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler');
  950. xml_set_character_data_handler($xml, '_data_handler');
  951. // add <xml></xml> to account for "dangling" tags like <BitStrength>...</BitStrength> that are sometimes added
  952. if(!xml_parse($xml, '<xml>' . $key . '</xml>')){
  953. return false;
  954. }
  955. return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false;
  956. // from PuTTY's SSHPUBK.C
  957. case CRYPT_RSA_PRIVATE_FORMAT_PUTTY:
  958. $components = array();
  959. $key = preg_split('#\r\n|\r|\n#', $key);
  960. $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0]));
  961. if($type != 'ssh-rsa'){
  962. return false;
  963. }
  964. $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1]));
  965. $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2]));
  966. $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3]));
  967. $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength))));
  968. $public = substr($public, 11);
  969. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  970. $components['publicExponent'] = new \core\tools\secure\math\BigInteger($this->_string_shift($public, $length), -256);
  971. extract(unpack('Nlength', $this->_string_shift($public, 4)));
  972. $components['modulus'] = new \core\tools\secure\math\BigInteger($this->_string_shift($public, $length), -256);
  973. $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4]));
  974. $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength))));
  975. switch($encryption){
  976. case 'aes256-cbc':
  977. if(!class_exists('Crypt_AES')){
  978. include_once 'Crypt/AES.php';
  979. }
  980. $symkey = '';
  981. $sequence = 0;
  982. while(strlen($symkey) < 32){
  983. $temp = pack('Na*', $sequence++, $this->password);
  984. $symkey.= pack('H*', sha1($temp));
  985. }
  986. $symkey = substr($symkey, 0, 32);
  987. $crypto = new Crypt_AES();
  988. }
  989. if($encryption != 'none'){
  990. $crypto->setKey($symkey);
  991. $crypto->disablePadding();
  992. $private = $crypto->decrypt($private);
  993. if($private === false){
  994. return false;
  995. }
  996. }
  997. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  998. if(strlen($private) < $length){
  999. return false;
  1000. }
  1001. $components['privateExponent'] = new \core\tools\secure\math\BigInteger($this->_string_shift($private, $length), -256);
  1002. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1003. if(strlen($private) < $length){
  1004. return false;
  1005. }
  1006. $components['primes'] = array(1 => new \core\tools\secure\math\BigInteger($this->_string_shift($private, $length), -256));
  1007. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1008. if(strlen($private) < $length){
  1009. return false;
  1010. }
  1011. $components['primes'][] = new \core\tools\secure\math\BigInteger($this->_string_shift($private, $length), -256);
  1012. $temp = $components['primes'][1]->subtract($this->one);
  1013. $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp));
  1014. $temp = $components['primes'][2]->subtract($this->one);
  1015. $components['exponents'][] = $components['publicExponent']->modInverse($temp);
  1016. extract(unpack('Nlength', $this->_string_shift($private, 4)));
  1017. if(strlen($private) < $length){
  1018. return false;
  1019. }
  1020. $components['coefficients'] = array(2 => new \core\tools\secure\math\BigInteger($this->_string_shift($private, $length), -256));
  1021. return $components;
  1022. }
  1023. }
  1024. /**
  1025. * Returns the key size
  1026. *
  1027. * More specifically, this returns the size of the modulo in bits.
  1028. *
  1029. * @access public
  1030. * @return Integer
  1031. */
  1032. public function getSize(){
  1033. return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits());
  1034. }
  1035. /**
  1036. * Start Element Handler
  1037. *
  1038. * Called by xml_set_element_handler()
  1039. *
  1040. * @access private
  1041. * @param Resource $parser
  1042. * @param String $name
  1043. * @param Array $attribs
  1044. */
  1045. private function _start_element_handler($parser, $name, $attribs){
  1046. //$name = strtoupper($name);
  1047. switch($name){
  1048. case 'MODULUS':
  1049. $this->current = &$this->components['modulus'];
  1050. break;
  1051. case 'EXPONENT':
  1052. $this->current = &$this->components['publicExponent'];
  1053. break;
  1054. case 'P':
  1055. $this->current = &$this->components['primes'][1];
  1056. break;
  1057. case 'Q':
  1058. $this->current = &$this->components['primes'][2];
  1059. break;
  1060. case 'DP':
  1061. $this->current = &$this->components['exponents'][1];
  1062. break;
  1063. case 'DQ':
  1064. $this->current = &$this->components['exponents'][2];
  1065. break;
  1066. case 'INVERSEQ':
  1067. $this->current = &$this->components['coefficients'][2];
  1068. break;
  1069. case 'D':
  1070. $this->current = &$this->components['privateExponent'];
  1071. }
  1072. $this->current = '';
  1073. }
  1074. /**
  1075. * Stop Element Handler
  1076. *
  1077. * Called by xml_set_element_handler()
  1078. *
  1079. * @access private
  1080. * @param Resource $parser
  1081. * @param String $name
  1082. */
  1083. private function _stop_element_handler($parser, $name){
  1084. if(isset($this->current)){
  1085. $this->current = new \core\tools\secure\math\BigInteger(base64_decode($this->current), 256);
  1086. unset($this->current);
  1087. }
  1088. }
  1089. /**
  1090. * Data Handler
  1091. *
  1092. * Called by xml_set_character_data_handler()
  1093. *
  1094. * @access private
  1095. * @param Resource $parser
  1096. * @param String $data
  1097. */
  1098. private function _data_handler($parser, $data){
  1099. if(!isset($this->current) || is_object($this->current)){
  1100. return;
  1101. }
  1102. $this->current.= trim($data);
  1103. }
  1104. /**
  1105. * Loads a public or private key
  1106. *
  1107. * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed)
  1108. *
  1109. * @access public
  1110. * @param String $key
  1111. * @param Integer $type optional
  1112. */
  1113. public function loadKey($key, $type = false){
  1114. if(is_object($key) && strtolower(get_class($key)) == 'crypt_rsa'){
  1115. $this->privateKeyFormat = $key->privateKeyFormat;
  1116. $this->publicKeyFormat = $key->publicKeyFormat;
  1117. $this->k = $key->k;
  1118. $this->hLen = $key->hLen;
  1119. $this->sLen = $key->sLen;
  1120. $this->mgfHLen = $key->mgfHLen;
  1121. $this->encryptionMode = $key->encryptionMode;
  1122. $this->signatureMode = $key->signatureMode;
  1123. $this->password = $key->password;
  1124. $this->configFile = $key->configFile;
  1125. $this->comment = $key->comment;
  1126. if(is_object($key->hash)){
  1127. $this->hash = new Hash($key->hash->getHash());
  1128. }
  1129. if(is_object($key->mgfHash)){
  1130. $this->mgfHash = new Hash($key->mgfHash->getHash());
  1131. }
  1132. if(is_object($key->modulus)){
  1133. $this->modulus = $key->modulus->copy();
  1134. }
  1135. if(is_object($key->exponent)){
  1136. $this->exponent = $key->exponent->copy();
  1137. }
  1138. if(is_object($key->publicExponent)){
  1139. $this->publicExponent = $key->publicExponent->copy();
  1140. }
  1141. $this->primes = array();
  1142. $this->exponents = array();
  1143. $this->coefficients = array();
  1144. foreach($this->primes as $prime){
  1145. $this->primes[] = $prime->copy();
  1146. }
  1147. foreach($this->exponents as $exponent){
  1148. $this->exponents[] = $exponent->copy();
  1149. }
  1150. foreach($this->coefficients as $coefficient){
  1151. $this->coefficients[] = $coefficient->copy();
  1152. }
  1153. return true;
  1154. }
  1155. if($type === false){
  1156. $types = array(
  1157. CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1158. CRYPT_RSA_PRIVATE_FORMAT_PKCS1,
  1159. CRYPT_RSA_PRIVATE_FORMAT_XML,
  1160. CRYPT_RSA_PRIVATE_FORMAT_PUTTY,
  1161. CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1162. );
  1163. foreach($types as $type){
  1164. $components = $this->_parseKey($key, $type);
  1165. if($components !== false){
  1166. break;
  1167. }
  1168. }
  1169. }else{
  1170. $components = $this->_parseKey($key, $type);
  1171. }
  1172. if($components === false){
  1173. return false;
  1174. }
  1175. if(isset($components['comment']) && $components['comment'] !== false){
  1176. $this->comment = $components['comment'];
  1177. }
  1178. $this->modulus = $components['modulus'];
  1179. $this->k = strlen($this->modulus->toBytes());
  1180. $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
  1181. if(isset($components['primes'])){
  1182. $this->primes = $components['primes'];
  1183. $this->exponents = $components['exponents'];
  1184. $this->coefficients = $components['coefficients'];
  1185. $this->publicExponent = $components['publicExponent'];
  1186. }else{
  1187. $this->primes = array();
  1188. $this->exponents = array();
  1189. $this->coefficients = array();
  1190. $this->publicExponent = false;
  1191. }
  1192. switch($type){
  1193. case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
  1194. case CRYPT_RSA_PUBLIC_FORMAT_RAW:
  1195. $this->setPublicKey();
  1196. break;
  1197. case CRYPT_RSA_PRIVATE_FORMAT_PKCS1:
  1198. switch(true){
  1199. case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
  1200. case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
  1201. $this->setPublicKey();
  1202. }
  1203. }
  1204. return true;
  1205. }
  1206. /**
  1207. * Sets the password
  1208. *
  1209. * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false.
  1210. * Or rather, pass in $password such that empty($password) && !is_string($password) is true.
  1211. *
  1212. * @see createKey()
  1213. * @see loadKey()
  1214. * @access public
  1215. * @param String $password
  1216. */
  1217. public function setPassword($password = false){
  1218. $this->password = $password;
  1219. }
  1220. /**
  1221. * Defines the public key
  1222. *
  1223. * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when
  1224. * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a
  1225. * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys
  1226. * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public
  1227. * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used
  1228. * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being
  1229. * public.
  1230. *
  1231. * Do note that when a new key is loaded the index will be cleared.
  1232. *
  1233. * Returns true on success, false on failure
  1234. *
  1235. * @see getPublicKey()
  1236. * @access public
  1237. * @param String $key optional
  1238. * @param Integer $type optional
  1239. * @return Boolean
  1240. */
  1241. public function setPublicKey($key = false, $type = false){
  1242. // if a public key has already been loaded return false
  1243. if(!empty($this->publicExponent)){
  1244. return false;
  1245. }
  1246. if($key === false && !empty($this->modulus)){
  1247. $this->publicExponent = $this->exponent;
  1248. return true;
  1249. }
  1250. if($type === false){
  1251. $types = array(
  1252. CRYPT_RSA_PUBLIC_FORMAT_RAW,
  1253. CRYPT_RSA_PUBLIC_FORMAT_PKCS1,
  1254. CRYPT_RSA_PUBLIC_FORMAT_XML,
  1255. CRYPT_RSA_PUBLIC_FORMAT_OPENSSH
  1256. );
  1257. foreach($types as $type){
  1258. $components = $this->_parseKey($key, $type);
  1259. if($components !== false){
  1260. break;
  1261. }
  1262. }
  1263. }else{
  1264. $components = $this->_parseKey($key, $type);
  1265. }
  1266. if($components === false){
  1267. return false;
  1268. }
  1269. if(empty($this->modulus) || !$this->modulus->equals($components['modulus'])){
  1270. $this->modulus = $components['modulus'];
  1271. $this->exponent = $this->publicExponent = $components['publicExponent'];
  1272. return true;
  1273. }
  1274. $this->publicExponent = $components['publicExponent'];
  1275. return true;
  1276. }
  1277. /**
  1278. * Defines the private key
  1279. *
  1280. * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force
  1281. * phpseclib to treat the key as a private key. This function will do that.
  1282. *
  1283. * Do note that when a new key is loaded the index will be cleared.
  1284. *
  1285. * Returns true on success, false on failure
  1286. *
  1287. * @see getPublicKey()
  1288. * @access public
  1289. * @param String $key optional
  1290. * @param Integer $type optional
  1291. * @return Boolean
  1292. */
  1293. public function setPrivateKey($key = false, $type = false){
  1294. if($key === false && !empty($this->publicExponent)){
  1295. unset($this->publicExponent);
  1296. return true;
  1297. }
  1298. $rsa = new Crypt_RSA();
  1299. if(!$rsa->loadKey($key, $type)){
  1300. return false;
  1301. }
  1302. unset($rsa->publicExponent);
  1303. // don't overwrite the old key if the new key is invalid
  1304. $this->loadKey($rsa);
  1305. return true;
  1306. }
  1307. /**
  1308. * Returns the public key
  1309. *
  1310. * The public key is only returned under two circumstances - if the private key had the public key embedded within it
  1311. * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this
  1312. * function won't return it since this library, for the most part, doesn't distinguish between public and private keys.
  1313. *
  1314. * @see getPublicKey()
  1315. * @access public
  1316. * @param String $key
  1317. * @param Integer $type optional
  1318. */
  1319. public function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8){
  1320. if(empty($this->modulus) || empty($this->publicExponent)){
  1321. return false;
  1322. }
  1323. $oldFormat = $this->publicKeyFormat;
  1324. $this->publicKeyFormat = $type;
  1325. $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent);
  1326. $this->publicKeyFormat = $oldFormat;
  1327. return $temp;
  1328. }
  1329. /**
  1330. * Returns the private key
  1331. *
  1332. * The private key is only returned if the currently loaded key contains the constituent prime numbers.
  1333. *
  1334. * @see getPublicKey()
  1335. * @access public
  1336. * @param String $key
  1337. * @param Integer $type optional
  1338. */
  1339. public function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1){
  1340. if(empty($this->primes)){
  1341. return false;
  1342. }
  1343. $oldFormat = $this->privateKeyFormat;
  1344. $this->privateKeyFormat = $type;
  1345. $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients);
  1346. $this->privateKeyFormat = $oldFormat;
  1347. return $temp;
  1348. }
  1349. /**
  1350. * Returns a minimalistic private key
  1351. *
  1352. * Returns the private key without the prime number constituants. Structurally identical to a public key that
  1353. * hasn't been set as the public key
  1354. *
  1355. * @see getPrivateKey()
  1356. * @access private
  1357. * @param String $key
  1358. * @param Integer $type optional
  1359. */
  1360. private function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8){
  1361. if(empty($this->modulus) || empty($this->exponent)){
  1362. return false;
  1363. }
  1364. $oldFormat = $this->publicKeyFormat;
  1365. $this->publicKeyFormat = $mode;
  1366. $temp = $this->_convertPublicKey($this->modulus, $this->exponent);
  1367. $this->publicKeyFormat = $oldFormat;
  1368. return $temp;
  1369. }
  1370. /**
  1371. * __toString() magic method
  1372. *
  1373. * @access public
  1374. */
  1375. public function __toString(){
  1376. $key = $this->getPrivateKey($this->privateKeyFormat);
  1377. if($key !== false){
  1378. return $key;
  1379. }
  1380. $key = $this->_getPrivatePublicKey($this->publicKeyFormat);
  1381. return $key !== false ? $key : '';
  1382. }
  1383. /**
  1384. * __clone() magic method
  1385. *
  1386. * @access public
  1387. */
  1388. public function __clone(){
  1389. $key = new RSA();
  1390. $key->loadKey($this);
  1391. return $key;
  1392. }
  1393. /**
  1394. * Generates the smallest and largest numbers requiring $bits bits
  1395. *
  1396. * @access private
  1397. * @param Integer $bits
  1398. * @return Array
  1399. */
  1400. private function _generateMinMax($bits){
  1401. $bytes = $bits >> 3;
  1402. $min = str_repeat(chr(0), $bytes);
  1403. $max = str_repeat(chr(0xFF), $bytes);
  1404. $msb = $bits & 7;
  1405. if($msb){
  1406. $min = chr(1 << ($msb - 1)) . $min;
  1407. $max = chr((1 << $msb) - 1) . $max;
  1408. }else{
  1409. $min[0] = chr(0x80);
  1410. }
  1411. return array(
  1412. 'min' => new \core\tools\secure\math\BigInteger($min, 256),
  1413. 'max' => new \core\tools\secure\math\BigInteger($max, 256)
  1414. );
  1415. }
  1416. /**
  1417. * DER-decode the length
  1418. *
  1419. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1420. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1421. *
  1422. * @access private
  1423. * @param String $string
  1424. * @return Integer
  1425. */
  1426. private function _decodeLength(&$string){
  1427. $length = ord($this->_string_shift($string));
  1428. if($length & 0x80){ // definite length, long form
  1429. $length&= 0x7F;
  1430. $temp = $this->_string_shift($string, $length);
  1431. list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4));
  1432. }
  1433. return $length;
  1434. }
  1435. /**
  1436. * DER-encode the length
  1437. *
  1438. * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
  1439. * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
  1440. *
  1441. * @access private
  1442. * @param Integer $length
  1443. * @return String
  1444. */
  1445. private function _encodeLength($length){
  1446. if($length <= 0x7F){
  1447. return chr($length);
  1448. }
  1449. $temp = ltrim(pack('N', $length), chr(0));
  1450. return pack('Ca*', 0x80 | strlen($temp), $temp);
  1451. }
  1452. /**
  1453. * String Shift
  1454. *
  1455. * Inspired by array_shift
  1456. *
  1457. * @param String $string
  1458. * @param optional Integer $index
  1459. * @return String
  1460. * @access private
  1461. */
  1462. private function _string_shift(&$string, $index = 1){
  1463. $substr = substr($string, 0, $index);
  1464. $string = substr($string, $index);
  1465. return $substr;
  1466. }
  1467. /**
  1468. * Determines the private key format
  1469. *
  1470. * @see createKey()
  1471. * @access public
  1472. * @param Integer $format
  1473. */
  1474. public function setPrivateKeyFormat($format){
  1475. $this->privateKeyFormat = $format;
  1476. }
  1477. /**
  1478. * Determines the public key format
  1479. *
  1480. * @see createKey()
  1481. * @access public
  1482. * @param Integer $format
  1483. */
  1484. public function setPublicKeyFormat($format){
  1485. $this->publicKeyFormat = $format;
  1486. }
  1487. /**
  1488. * Determines which hashing function should be used
  1489. *
  1490. * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and
  1491. * decryption. If $hash isn't supported, sha1 is used.
  1492. *
  1493. * @access public
  1494. * @param String $hash
  1495. */
  1496. public function setHash($hash){
  1497. // Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1498. switch($hash){
  1499. case 'md2':
  1500. case 'md5':
  1501. case 'sha1':
  1502. case 'sha256':
  1503. case 'sha384':
  1504. case 'sha512':
  1505. $this->hash = new Hash($hash);
  1506. $this->hashName = $hash;
  1507. break;
  1508. default:
  1509. $this->hash = new Hash('sha1');
  1510. $this->hashName = 'sha1';
  1511. }
  1512. $this->hLen = $this->hash->getLength();
  1513. }
  1514. /**
  1515. * Determines which hashing function should be used for the mask generation function
  1516. *
  1517. * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's
  1518. * best if Hash and MGFHash are set to the same thing this is not a requirement.
  1519. *
  1520. * @access public
  1521. * @param String $hash
  1522. */
  1523. public function setMGFHash($hash){
  1524. // Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example.
  1525. switch($hash){
  1526. case 'md2':
  1527. case 'md5':
  1528. case 'sha1':
  1529. case 'sha256':
  1530. case 'sha384':
  1531. case 'sha512':
  1532. $this->mgfHash = new Hash($hash);
  1533. break;
  1534. default:
  1535. $this->mgfHash = new Hash('sha1');
  1536. }
  1537. $this->mgfHLen = $this->mgfHash->getLength();
  1538. }
  1539. /**
  1540. * Determines the salt length
  1541. *
  1542. * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}:
  1543. *
  1544. * Typical salt lengths in octets are hLen (the length of the output
  1545. * of the hash function Hash) and 0.
  1546. *
  1547. * @access public
  1548. * @param Integer $format
  1549. */
  1550. public function setSaltLength($sLen){
  1551. $this->sLen = $sLen;
  1552. }
  1553. /**
  1554. * Integer-to-Octet-String primitive
  1555. *
  1556. * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}.
  1557. *
  1558. * @access private
  1559. * @param \core\tools\secure\math\BigInteger $x
  1560. * @param Integer $xLen
  1561. * @return String
  1562. */
  1563. private function _i2osp($x, $xLen){
  1564. $x = $x->toBytes();
  1565. if(strlen($x) > $xLen){
  1566. user_error('Integer too large');
  1567. return false;
  1568. }
  1569. return str_pad($x, $xLen, chr(0), STR_PAD_LEFT);
  1570. }
  1571. /**
  1572. * Octet-String-to-Integer primitive
  1573. *
  1574. * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}.
  1575. *
  1576. * @access private
  1577. * @param String $x
  1578. * @return \core\tools\secure\math\BigInteger
  1579. */
  1580. private function _os2ip($x){
  1581. return new \core\tools\secure\math\BigInteger($x, 256);
  1582. }
  1583. /**
  1584. * Exponentiate with or without Chinese Remainder Theorem
  1585. *
  1586. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}.
  1587. *
  1588. * @access private
  1589. * @param \core\tools\secure\math\BigInteger $x
  1590. * @return \core\tools\secure\math\BigInteger
  1591. */
  1592. private function _exponentiate($x){
  1593. if(empty($this->primes) || empty($this->coefficients) || empty($this->exponents)){
  1594. return $x->modPow($this->exponent, $this->modulus);
  1595. }
  1596. $num_primes = count($this->primes);
  1597. if(defined('CRYPT_RSA_DISABLE_BLINDING')){
  1598. $m_i = array(
  1599. 1 => $x->modPow($this->exponents[1], $this->primes[1]),
  1600. 2 => $x->modPow($this->exponents[2], $this->primes[2])
  1601. );
  1602. $h = $m_i[1]->subtract($m_i[2]);
  1603. $h = $h->multiply($this->coefficients[2]);
  1604. list(, $h) = $h->divide($this->primes[1]);
  1605. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1606. $r = $this->primes[1];
  1607. for($i = 3; $i <= $num_primes; $i++){
  1608. $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1609. $r = $r->multiply($this->primes[$i - 1]);
  1610. $h = $m_i->subtract($m);
  1611. $h = $h->multiply($this->coefficients[$i]);
  1612. list(, $h) = $h->divide($this->primes[$i]);
  1613. $m = $m->add($r->multiply($h));
  1614. }
  1615. }else{
  1616. $smallest = $this->primes[1];
  1617. for($i = 2; $i <= $num_primes; $i++){
  1618. if($smallest->compare($this->primes[$i]) > 0){
  1619. $smallest = $this->primes[$i];
  1620. }
  1621. }
  1622. $one = new \core\tools\secure\math\BigInteger(1);
  1623. $r = $one->random($one, $smallest->subtract($one));
  1624. $m_i = array(
  1625. 1 => $this->_blind($x, $r, 1),
  1626. 2 => $this->_blind($x, $r, 2)
  1627. );
  1628. $h = $m_i[1]->subtract($m_i[2]);
  1629. $h = $h->multiply($this->coefficients[2]);
  1630. list(, $h) = $h->divide($this->primes[1]);
  1631. $m = $m_i[2]->add($h->multiply($this->primes[2]));
  1632. $r = $this->primes[1];
  1633. for($i = 3; $i <= $num_primes; $i++){
  1634. $m_i = $this->_blind($x, $r, $i);
  1635. $r = $r->multiply($this->primes[$i - 1]);
  1636. $h = $m_i->subtract($m);
  1637. $h = $h->multiply($this->coefficients[$i]);
  1638. list(, $h) = $h->divide($this->primes[$i]);
  1639. $m = $m->add($r->multiply($h));
  1640. }
  1641. }
  1642. return $m;
  1643. }
  1644. /**
  1645. * Performs RSA Blinding
  1646. *
  1647. * Protects against timing attacks by employing RSA Blinding.
  1648. * Returns $x->modPow($this->exponents[$i], $this->primes[$i])
  1649. *
  1650. * @access private
  1651. * @param \core\tools\secure\math\BigInteger $x
  1652. * @param \core\tools\secure\math\BigInteger $r
  1653. * @param Integer $i
  1654. * @return \core\tools\secure\math\BigInteger
  1655. */
  1656. private function _blind($x, $r, $i){
  1657. $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i]));
  1658. $x = $x->modPow($this->exponents[$i], $this->primes[$i]);
  1659. $r = $r->modInverse($this->primes[$i]);
  1660. $x = $x->multiply($r);
  1661. list(, $x) = $x->divide($this->primes[$i]);
  1662. return $x;
  1663. }
  1664. /**
  1665. * Performs blinded RSA equality testing
  1666. *
  1667. * Protects against a particular type of timing attack described.
  1668. *
  1669. * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)}
  1670. *
  1671. * Thanks for the heads up singpolyma!
  1672. *
  1673. * @access private
  1674. * @param String $x
  1675. * @param String $y
  1676. * @return Boolean
  1677. */
  1678. private function _equals($x, $y){
  1679. if(strlen($x) != strlen($y)){
  1680. return false;
  1681. }
  1682. $result = 0;
  1683. for($i = 0; $i < strlen($x); $i++){
  1684. $result |= ord($x[$i]) ^ ord($y[$i]);
  1685. }
  1686. return $result == 0;
  1687. }
  1688. /**
  1689. * RSAEP
  1690. *
  1691. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}.
  1692. *
  1693. * @access private
  1694. * @param \core\tools\secure\math\BigInteger $m
  1695. * @return \core\tools\secure\math\BigInteger
  1696. */
  1697. private function _rsaep($m){
  1698. if($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0){
  1699. user_error('Message representative out of range');
  1700. return false;
  1701. }
  1702. return $this->_exponentiate($m);
  1703. }
  1704. /**
  1705. * RSADP
  1706. *
  1707. * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}.
  1708. *
  1709. * @access private
  1710. * @param \core\tools\secure\math\BigInteger $c
  1711. * @return \core\tools\secure\math\BigInteger
  1712. */
  1713. private function _rsadp($c){
  1714. if($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0){
  1715. user_error('Ciphertext representative out of range');
  1716. return false;
  1717. }
  1718. return $this->_exponentiate($c);
  1719. }
  1720. /**
  1721. * RSASP1
  1722. *
  1723. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}.
  1724. *
  1725. * @access private
  1726. * @param \core\tools\secure\math\BigInteger $m
  1727. * @return \core\tools\secure\math\BigInteger
  1728. */
  1729. private function _rsasp1($m){
  1730. if($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0){
  1731. user_error('Message representative out of range');
  1732. return false;
  1733. }
  1734. return $this->_exponentiate($m);
  1735. }
  1736. /**
  1737. * RSAVP1
  1738. *
  1739. * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}.
  1740. *
  1741. * @access private
  1742. * @param \core\tools\secure\math\BigInteger $s
  1743. * @return \core\tools\secure\math\BigInteger
  1744. */
  1745. private function _rsavp1($s){
  1746. if($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0){
  1747. user_error('Signature representative out of range');
  1748. return false;
  1749. }
  1750. return $this->_exponentiate($s);
  1751. }
  1752. /**
  1753. * MGF1
  1754. *
  1755. * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}.
  1756. *
  1757. * @access private
  1758. * @param String $mgfSeed
  1759. * @param Integer $mgfLen
  1760. * @return String
  1761. */
  1762. private function _mgf1($mgfSeed, $maskLen){
  1763. // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output.
  1764. $t = '';
  1765. $count = ceil($maskLen / $this->mgfHLen);
  1766. for($i = 0; $i < $count; $i++){
  1767. $c = pack('N', $i);
  1768. $t.= $this->mgfHash->hash($mgfSeed . $c);
  1769. }
  1770. return substr($t, 0, $maskLen);
  1771. }
  1772. /**
  1773. * RSAES-OAEP-ENCRYPT
  1774. *
  1775. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and
  1776. * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}.
  1777. *
  1778. * @access private
  1779. * @param String $m
  1780. * @param String $l
  1781. * @return String
  1782. */
  1783. private function _rsaes_oaep_encrypt($m, $l = ''){
  1784. $mLen = strlen($m);
  1785. // Length checking
  1786. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1787. // be output.
  1788. if($mLen > $this->k - 2 * $this->hLen - 2){
  1789. user_error('Message too long');
  1790. return false;
  1791. }
  1792. // EME-OAEP encoding
  1793. $lHash = $this->hash->hash($l);
  1794. $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2);
  1795. $db = $lHash . $ps . chr(1) . $m;
  1796. $seed = crypt_random_string($this->hLen);
  1797. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1798. $maskedDB = $db ^ $dbMask;
  1799. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1800. $maskedSeed = $seed ^ $seedMask;
  1801. $em = chr(0) . $maskedSeed . $maskedDB;
  1802. // RSA encryption
  1803. $m = $this->_os2ip($em);
  1804. $c = $this->_rsaep($m);
  1805. $c = $this->_i2osp($c, $this->k);
  1806. // Output the ciphertext C
  1807. return $c;
  1808. }
  1809. /**
  1810. * RSAES-OAEP-DECRYPT
  1811. *
  1812. * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error
  1813. * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2:
  1814. *
  1815. * Note. Care must be taken to ensure that an opponent cannot
  1816. * distinguish the different error conditions in Step 3.g, whether by
  1817. * error message or timing, or, more generally, learn partial
  1818. * information about the encoded message EM. Otherwise an opponent may
  1819. * be able to obtain useful information about the decryption of the
  1820. * ciphertext C, leading to a chosen-ciphertext attack such as the one
  1821. * observed by Manger [36].
  1822. *
  1823. * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}:
  1824. *
  1825. * Both the encryption and the decryption operations of RSAES-OAEP take
  1826. * the value of a label L as input. In this version of PKCS #1, L is
  1827. * the empty string; other uses of the label are outside the scope of
  1828. * this document.
  1829. *
  1830. * @access private
  1831. * @param String $c
  1832. * @param String $l
  1833. * @return String
  1834. */
  1835. private function _rsaes_oaep_decrypt($c, $l = ''){
  1836. // Length checking
  1837. // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1838. // be output.
  1839. if(strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2){
  1840. user_error('Decryption error');
  1841. return false;
  1842. }
  1843. // RSA decryption
  1844. $c = $this->_os2ip($c);
  1845. $m = $this->_rsadp($c);
  1846. if($m === false){
  1847. user_error('Decryption error');
  1848. return false;
  1849. }
  1850. $em = $this->_i2osp($m, $this->k);
  1851. // EME-OAEP decoding
  1852. $lHash = $this->hash->hash($l);
  1853. $y = ord($em[0]);
  1854. $maskedSeed = substr($em, 1, $this->hLen);
  1855. $maskedDB = substr($em, $this->hLen + 1);
  1856. $seedMask = $this->_mgf1($maskedDB, $this->hLen);
  1857. $seed = $maskedSeed ^ $seedMask;
  1858. $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1);
  1859. $db = $maskedDB ^ $dbMask;
  1860. $lHash2 = substr($db, 0, $this->hLen);
  1861. $m = substr($db, $this->hLen);
  1862. if($lHash != $lHash2){
  1863. user_error('Decryption error');
  1864. return false;
  1865. }
  1866. $m = ltrim($m, chr(0));
  1867. if(ord($m[0]) != 1){
  1868. user_error('Decryption error');
  1869. return false;
  1870. }
  1871. // Output the message M
  1872. return substr($m, 1);
  1873. }
  1874. /**
  1875. * RSAES-PKCS1-V1_5-ENCRYPT
  1876. *
  1877. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}.
  1878. *
  1879. * @access private
  1880. * @param String $m
  1881. * @return String
  1882. */
  1883. private function _rsaes_pkcs1_v1_5_encrypt($m){
  1884. $mLen = strlen($m);
  1885. // Length checking
  1886. if($mLen > $this->k - 11){
  1887. user_error('Message too long');
  1888. return false;
  1889. }
  1890. // EME-PKCS1-v1_5 encoding
  1891. $psLen = $this->k - $mLen - 3;
  1892. $ps = '';
  1893. while(strlen($ps) != $psLen){
  1894. $temp = crypt_random_string($psLen - strlen($ps));
  1895. $temp = str_replace("\x00", '', $temp);
  1896. $ps.= $temp;
  1897. }
  1898. $type = 2;
  1899. // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done
  1900. if(defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)){
  1901. $type = 1;
  1902. // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF"
  1903. $ps = str_repeat("\xFF", $psLen);
  1904. }
  1905. $em = chr(0) . chr($type) . $ps . chr(0) . $m;
  1906. // RSA encryption
  1907. $m = $this->_os2ip($em);
  1908. $c = $this->_rsaep($m);
  1909. $c = $this->_i2osp($c, $this->k);
  1910. // Output the ciphertext C
  1911. return $c;
  1912. }
  1913. /**
  1914. * RSAES-PKCS1-V1_5-DECRYPT
  1915. *
  1916. * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
  1917. *
  1918. * For compatibility purposes, this function departs slightly from the description given in RFC3447.
  1919. * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
  1920. * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
  1921. * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed
  1922. * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the
  1923. * second byte is 2 or less. If it is, we'll accept the decrypted string as valid.
  1924. *
  1925. * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt
  1926. * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but
  1927. * not private key encrypted ciphertext's.
  1928. *
  1929. * @access private
  1930. * @param String $c
  1931. * @return String
  1932. */
  1933. private function _rsaes_pkcs1_v1_5_decrypt($c){
  1934. // Length checking
  1935. if(strlen($c) != $this->k){ // or if k < 11
  1936. user_error('Decryption error');
  1937. return false;
  1938. }
  1939. // RSA decryption
  1940. $c = $this->_os2ip($c);
  1941. $m = $this->_rsadp($c);
  1942. if($m === false){
  1943. user_error('Decryption error');
  1944. return false;
  1945. }
  1946. $em = $this->_i2osp($m, $this->k);
  1947. // EME-PKCS1-v1_5 decoding
  1948. if(ord($em[0]) != 0 || ord($em[1]) > 2){
  1949. user_error('Decryption error');
  1950. return false;
  1951. }
  1952. $ps = substr($em, 2, strpos($em, chr(0), 2) - 2);
  1953. $m = substr($em, strlen($ps) + 3);
  1954. if(strlen($ps) < 8){
  1955. user_error('Decryption error');
  1956. return false;
  1957. }
  1958. // Output M
  1959. return $m;
  1960. }
  1961. /**
  1962. * EMSA-PSS-ENCODE
  1963. *
  1964. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}.
  1965. *
  1966. * @access private
  1967. * @param String $m
  1968. * @param Integer $emBits
  1969. */
  1970. private function _emsa_pss_encode($m, $emBits){
  1971. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  1972. // be output.
  1973. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8)
  1974. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  1975. $mHash = $this->hash->hash($m);
  1976. if($emLen < $this->hLen + $sLen + 2){
  1977. user_error('Encoding error');
  1978. return false;
  1979. }
  1980. $salt = crypt_random_string($sLen);
  1981. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  1982. $h = $this->hash->hash($m2);
  1983. $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2);
  1984. $db = $ps . chr(1) . $salt;
  1985. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  1986. $maskedDB = $db ^ $dbMask;
  1987. $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0];
  1988. $em = $maskedDB . $h . chr(0xBC);
  1989. return $em;
  1990. }
  1991. /**
  1992. * EMSA-PSS-VERIFY
  1993. *
  1994. * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}.
  1995. *
  1996. * @access private
  1997. * @param String $m
  1998. * @param String $em
  1999. * @param Integer $emBits
  2000. * @return String
  2001. */
  2002. private function _emsa_pss_verify($m, $em, $emBits){
  2003. // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error
  2004. // be output.
  2005. $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8);
  2006. $sLen = $this->sLen == false ? $this->hLen : $this->sLen;
  2007. $mHash = $this->hash->hash($m);
  2008. if($emLen < $this->hLen + $sLen + 2){
  2009. return false;
  2010. }
  2011. if($em[strlen($em) - 1] != chr(0xBC)){
  2012. return false;
  2013. }
  2014. $maskedDB = substr($em, 0, -$this->hLen - 1);
  2015. $h = substr($em, -$this->hLen - 1, $this->hLen);
  2016. $temp = chr(0xFF << ($emBits & 7));
  2017. if((~$maskedDB[0] & $temp) != $temp){
  2018. return false;
  2019. }
  2020. $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1);
  2021. $db = $maskedDB ^ $dbMask;
  2022. $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0];
  2023. $temp = $emLen - $this->hLen - $sLen - 2;
  2024. if(substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1){
  2025. return false;
  2026. }
  2027. $salt = substr($db, $temp + 1); // should be $sLen long
  2028. $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt;
  2029. $h2 = $this->hash->hash($m2);
  2030. return $this->_equals($h, $h2);
  2031. }
  2032. /**
  2033. * RSASSA-PSS-SIGN
  2034. *
  2035. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}.
  2036. *
  2037. * @access private
  2038. * @param String $m
  2039. * @return String
  2040. */
  2041. private function _rsassa_pss_sign($m){
  2042. // EMSA-PSS encoding
  2043. $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1);
  2044. // RSA signature
  2045. $m = $this->_os2ip($em);
  2046. $s = $this->_rsasp1($m);
  2047. $s = $this->_i2osp($s, $this->k);
  2048. // Output the signature S
  2049. return $s;
  2050. }
  2051. /**
  2052. * RSASSA-PSS-VERIFY
  2053. *
  2054. * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}.
  2055. *
  2056. * @access private
  2057. * @param String $m
  2058. * @param String $s
  2059. * @return String
  2060. */
  2061. private function _rsassa_pss_verify($m, $s){
  2062. // Length checking
  2063. if(strlen($s) != $this->k){
  2064. user_error('Invalid signature');
  2065. return false;
  2066. }
  2067. // RSA verification
  2068. $modBits = 8 * $this->k;
  2069. $s2 = $this->_os2ip($s);
  2070. $m2 = $this->_rsavp1($s2);
  2071. if($m2 === false){
  2072. user_error('Invalid signature');
  2073. return false;
  2074. }
  2075. $em = $this->_i2osp($m2, $modBits >> 3);
  2076. if($em === false){
  2077. user_error('Invalid signature');
  2078. return false;
  2079. }
  2080. // EMSA-PSS verification
  2081. return $this->_emsa_pss_verify($m, $em, $modBits - 1);
  2082. }
  2083. /**
  2084. * EMSA-PKCS1-V1_5-ENCODE
  2085. *
  2086. * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}.
  2087. *
  2088. * @access private
  2089. * @param String $m
  2090. * @param Integer $emLen
  2091. * @return String
  2092. */
  2093. private function _emsa_pkcs1_v1_5_encode($m, $emLen){
  2094. $h = $this->hash->hash($m);
  2095. if($h === false){
  2096. return false;
  2097. }
  2098. // see http://tools.ietf.org/html/rfc3447#page-43
  2099. switch($this->hashName){
  2100. case 'md2':
  2101. $t = pack('H*', '3020300c06082a864886f70d020205000410');
  2102. break;
  2103. case 'md5':
  2104. $t = pack('H*', '3020300c06082a864886f70d020505000410');
  2105. break;
  2106. case 'sha1':
  2107. $t = pack('H*', '3021300906052b0e03021a05000414');
  2108. break;
  2109. case 'sha256':
  2110. $t = pack('H*', '3031300d060960864801650304020105000420');
  2111. break;
  2112. case 'sha384':
  2113. $t = pack('H*', '3041300d060960864801650304020205000430');
  2114. break;
  2115. case 'sha512':
  2116. $t = pack('H*', '3051300d060960864801650304020305000440');
  2117. }
  2118. $t.= $h;
  2119. $tLen = strlen($t);
  2120. if($emLen < $tLen + 11){
  2121. user_error('Intended encoded message length too short');
  2122. return false;
  2123. }
  2124. $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3);
  2125. $em = "\0\1$ps\0$t";
  2126. return $em;
  2127. }
  2128. /**
  2129. * RSASSA-PKCS1-V1_5-SIGN
  2130. *
  2131. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}.
  2132. *
  2133. * @access private
  2134. * @param String $m
  2135. * @return String
  2136. */
  2137. private function _rsassa_pkcs1_v1_5_sign($m){
  2138. // EMSA-PKCS1-v1_5 encoding
  2139. $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2140. if($em === false){
  2141. user_error('RSA modulus too short');
  2142. return false;
  2143. }
  2144. // RSA signature
  2145. $m = $this->_os2ip($em);
  2146. $s = $this->_rsasp1($m);
  2147. $s = $this->_i2osp($s, $this->k);
  2148. // Output the signature S
  2149. return $s;
  2150. }
  2151. /**
  2152. * RSASSA-PKCS1-V1_5-VERIFY
  2153. *
  2154. * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}.
  2155. *
  2156. * @access private
  2157. * @param String $m
  2158. * @return String
  2159. */
  2160. private function _rsassa_pkcs1_v1_5_verify($m, $s){
  2161. // Length checking
  2162. if(strlen($s) != $this->k){
  2163. user_error('Invalid signature');
  2164. return false;
  2165. }
  2166. // RSA verification
  2167. $s = $this->_os2ip($s);
  2168. $m2 = $this->_rsavp1($s);
  2169. if($m2 === false){
  2170. user_error('Invalid signature');
  2171. return false;
  2172. }
  2173. $em = $this->_i2osp($m2, $this->k);
  2174. if($em === false){
  2175. user_error('Invalid signature');
  2176. return false;
  2177. }
  2178. // EMSA-PKCS1-v1_5 encoding
  2179. $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k);
  2180. if($em2 === false){
  2181. user_error('RSA modulus too short');
  2182. return false;
  2183. }
  2184. // Compare
  2185. return $this->_equals($em, $em2);
  2186. }
  2187. /**
  2188. * Set Encryption Mode
  2189. *
  2190. * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1.
  2191. *
  2192. * @access public
  2193. * @param Integer $mode
  2194. */
  2195. public function setEncryptionMode($mode){
  2196. $this->encryptionMode = $mode;
  2197. }
  2198. /**
  2199. * Set Signature Mode
  2200. *
  2201. * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1
  2202. *
  2203. * @access public
  2204. * @param Integer $mode
  2205. */
  2206. public function setSignatureMode($mode){
  2207. $this->signatureMode = $mode;
  2208. }
  2209. /**
  2210. * Set public key comment.
  2211. *
  2212. * @access public
  2213. * @param String $comment
  2214. */
  2215. public function setComment($comment){
  2216. $this->comment = $comment;
  2217. }
  2218. /**
  2219. * Get public key comment.
  2220. *
  2221. * @access public
  2222. * @return String
  2223. */
  2224. public function getComment(){
  2225. return $this->comment;
  2226. }
  2227. /**
  2228. * Encryption
  2229. *
  2230. * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be.
  2231. * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will
  2232. * be concatenated together.
  2233. *
  2234. * @see decrypt()
  2235. * @access public
  2236. * @param String $plaintext
  2237. * @return String
  2238. */
  2239. public function encrypt($plaintext){
  2240. switch($this->encryptionMode){
  2241. case CRYPT_RSA_ENCRYPTION_PKCS1:
  2242. $length = $this->k - 11;
  2243. if($length <= 0){
  2244. return false;
  2245. }
  2246. $plaintext = str_split($plaintext, $length);
  2247. $ciphertext = '';
  2248. foreach($plaintext as $m){
  2249. $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m);
  2250. }
  2251. return $ciphertext;
  2252. //case CRYPT_RSA_ENCRYPTION_OAEP:
  2253. default:
  2254. $length = $this->k - 2 * $this->hLen - 2;
  2255. if($length <= 0){
  2256. return false;
  2257. }
  2258. $plaintext = str_split($plaintext, $length);
  2259. $ciphertext = '';
  2260. foreach($plaintext as $m){
  2261. $ciphertext.= $this->_rsaes_oaep_encrypt($m);
  2262. }
  2263. return $ciphertext;
  2264. }
  2265. }
  2266. /**
  2267. * Decryption
  2268. *
  2269. * @see encrypt()
  2270. * @access public
  2271. * @param String $plaintext
  2272. * @return String
  2273. */
  2274. public function decrypt($ciphertext){
  2275. if($this->k <= 0){
  2276. return false;
  2277. }
  2278. $ciphertext = str_split($ciphertext, $this->k);
  2279. $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT);
  2280. $plaintext = '';
  2281. switch($this->encryptionMode){
  2282. case CRYPT_RSA_ENCRYPTION_PKCS1:
  2283. $decrypt = '_rsaes_pkcs1_v1_5_decrypt';
  2284. break;
  2285. //case CRYPT_RSA_ENCRYPTION_OAEP:
  2286. default:
  2287. $decrypt = '_rsaes_oaep_decrypt';
  2288. }
  2289. foreach($ciphertext as $c){
  2290. $temp = $this->$decrypt($c);
  2291. if($temp === false){
  2292. return false;
  2293. }
  2294. $plaintext.= $temp;
  2295. }
  2296. return $plaintext;
  2297. }
  2298. /**
  2299. * Create a signature
  2300. *
  2301. * @see verify()
  2302. * @access public
  2303. * @param String $message
  2304. * @return String
  2305. */
  2306. public function sign($message){
  2307. if(empty($this->modulus) || empty($this->exponent)){
  2308. return false;
  2309. }
  2310. switch($this->signatureMode){
  2311. case CRYPT_RSA_SIGNATURE_PKCS1:
  2312. return $this->_rsassa_pkcs1_v1_5_sign($message);
  2313. //case CRYPT_RSA_SIGNATURE_PSS:
  2314. default:
  2315. return $this->_rsassa_pss_sign($message);
  2316. }
  2317. }
  2318. /**
  2319. * Verifies a signature
  2320. *
  2321. * @see sign()
  2322. * @access public
  2323. * @param String $message
  2324. * @param String $signature
  2325. * @return Boolean
  2326. */
  2327. public function verify($message, $signature){
  2328. if(empty($this->modulus) || empty($this->exponent)){
  2329. return false;
  2330. }
  2331. switch($this->signatureMode){
  2332. case CRYPT_RSA_SIGNATURE_PKCS1:
  2333. return $this->_rsassa_pkcs1_v1_5_verify($message, $signature);
  2334. //case CRYPT_RSA_SIGNATURE_PSS:
  2335. default:
  2336. return $this->_rsassa_pss_verify($message, $signature);
  2337. }
  2338. }
  2339. /**
  2340. * Extract raw BER from Base64 encoding
  2341. *
  2342. * @access private
  2343. * @param String $str
  2344. * @return String
  2345. */
  2346. private function _extractBER($str){
  2347. /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them
  2348. * above and beyond the ceritificate.
  2349. * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line:
  2350. *
  2351. * Bag Attributes
  2352. * localKeyID: 01 00 00 00
  2353. * subject=/O=organization/OU=org unit/CN=common name
  2354. * issuer=/O=organization/CN=common name
  2355. */
  2356. $temp = preg_replace('#.*?^-+[^-]+-+#ms', '', $str, 1);
  2357. // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff
  2358. $temp = preg_replace('#-+[^-]+-+#', '', $temp);
  2359. // remove new lines
  2360. $temp = str_replace(array("\r", "\n", ' '), '', $temp);
  2361. $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false;
  2362. return $temp != false ? $temp : $str;
  2363. }
  2364. }