Crypt_RSA.php 93 KB

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