RSA.php 90 KB

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