RSA.php 91 KB

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