RSA.php 103 KB

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