RSA.php 113 KB

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