Base.php 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660
  1. <?php
  2. /**
  3. * Base Class for all Crypt_* cipher classes
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * Internally for phpseclib developers:
  8. * If you plan to add a new cipher class, please note following rules:
  9. *
  10. * - The new Crypt_* cipher class should extend Crypt_Base
  11. *
  12. * - Following methods are then required to be overridden/overloaded:
  13. *
  14. * - _encryptBlock()
  15. *
  16. * - _decryptBlock()
  17. *
  18. * - _setupKey()
  19. *
  20. * - All other methods are optional to be overridden/overloaded
  21. *
  22. * - Look at the source code of the current ciphers how they extend Crypt_Base
  23. * and take one of them as a start up for the new cipher class.
  24. *
  25. * - Please read all the other comments/notes/hints here also for each class var/method
  26. *
  27. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  28. * of this software and associated documentation files (the "Software"), to deal
  29. * in the Software without restriction, including without limitation the rights
  30. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  31. * copies of the Software, and to permit persons to whom the Software is
  32. * furnished to do so, subject to the following conditions:
  33. *
  34. * The above copyright notice and this permission notice shall be included in
  35. * all copies or substantial portions of the Software.
  36. *
  37. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  38. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  39. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  40. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  41. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  42. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  43. * THE SOFTWARE.
  44. *
  45. * @category Crypt
  46. * @package Crypt_Base
  47. * @author Jim Wigginton <terrafrost@php.net>
  48. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  49. * @copyright 2007 Jim Wigginton
  50. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  51. * @link http://phpseclib.sourceforge.net
  52. */
  53. /**#@+
  54. * @access public
  55. * @see self::encrypt()
  56. * @see self::decrypt()
  57. */
  58. /**
  59. * Encrypt / decrypt using the Counter mode.
  60. *
  61. * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
  62. *
  63. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
  64. */
  65. define('CRYPT_MODE_CTR', -1);
  66. /**
  67. * Encrypt / decrypt using the Electronic Code Book mode.
  68. *
  69. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
  70. */
  71. define('CRYPT_MODE_ECB', 1);
  72. /**
  73. * Encrypt / decrypt using the Code Book Chaining mode.
  74. *
  75. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
  76. */
  77. define('CRYPT_MODE_CBC', 2);
  78. /**
  79. * Encrypt / decrypt using the Cipher Feedback mode.
  80. *
  81. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
  82. */
  83. define('CRYPT_MODE_CFB', 3);
  84. /**
  85. * Encrypt / decrypt using the Output Feedback mode.
  86. *
  87. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
  88. */
  89. define('CRYPT_MODE_OFB', 4);
  90. /**
  91. * Encrypt / decrypt using streaming mode.
  92. */
  93. define('CRYPT_MODE_STREAM', 5);
  94. /**#@-*/
  95. /**#@+
  96. * @access private
  97. * @see self::Crypt_Base()
  98. * @internal These constants are for internal use only
  99. */
  100. /**
  101. * Base value for the internal implementation $engine switch
  102. */
  103. define('CRYPT_ENGINE_INTERNAL', 1);
  104. /**
  105. * Base value for the mcrypt implementation $engine switch
  106. */
  107. define('CRYPT_ENGINE_MCRYPT', 2);
  108. /**
  109. * Base value for the OpenSSL implementation $engine switch
  110. */
  111. define('CRYPT_ENGINE_OPENSSL', 3);
  112. /**#@-*/
  113. /**
  114. * Base Class for all Crypt_* cipher classes
  115. *
  116. * @package Crypt_Base
  117. * @author Jim Wigginton <terrafrost@php.net>
  118. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  119. * @access public
  120. */
  121. class Crypt_Base
  122. {
  123. /**
  124. * The Encryption Mode
  125. *
  126. * @see self::Crypt_Base()
  127. * @var int
  128. * @access private
  129. */
  130. var $mode;
  131. /**
  132. * The Block Length of the block cipher
  133. *
  134. * @var int
  135. * @access private
  136. */
  137. var $block_size = 16;
  138. /**
  139. * The Key
  140. *
  141. * @see self::setKey()
  142. * @var string
  143. * @access private
  144. */
  145. var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  146. /**
  147. * The Initialization Vector
  148. *
  149. * @see self::setIV()
  150. * @var string
  151. * @access private
  152. */
  153. var $iv;
  154. /**
  155. * A "sliding" Initialization Vector
  156. *
  157. * @see self::enableContinuousBuffer()
  158. * @see self::_clearBuffers()
  159. * @var string
  160. * @access private
  161. */
  162. var $encryptIV;
  163. /**
  164. * A "sliding" Initialization Vector
  165. *
  166. * @see self::enableContinuousBuffer()
  167. * @see self::_clearBuffers()
  168. * @var string
  169. * @access private
  170. */
  171. var $decryptIV;
  172. /**
  173. * Continuous Buffer status
  174. *
  175. * @see self::enableContinuousBuffer()
  176. * @var bool
  177. * @access private
  178. */
  179. var $continuousBuffer = false;
  180. /**
  181. * Encryption buffer for CTR, OFB and CFB modes
  182. *
  183. * @see self::encrypt()
  184. * @see self::_clearBuffers()
  185. * @var array
  186. * @access private
  187. */
  188. var $enbuffer;
  189. /**
  190. * Decryption buffer for CTR, OFB and CFB modes
  191. *
  192. * @see self::decrypt()
  193. * @see self::_clearBuffers()
  194. * @var array
  195. * @access private
  196. */
  197. var $debuffer;
  198. /**
  199. * mcrypt resource for encryption
  200. *
  201. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  202. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  203. *
  204. * @see self::encrypt()
  205. * @var resource
  206. * @access private
  207. */
  208. var $enmcrypt;
  209. /**
  210. * mcrypt resource for decryption
  211. *
  212. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  213. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  214. *
  215. * @see self::decrypt()
  216. * @var resource
  217. * @access private
  218. */
  219. var $demcrypt;
  220. /**
  221. * Does the enmcrypt resource need to be (re)initialized?
  222. *
  223. * @see Crypt_Twofish::setKey()
  224. * @see Crypt_Twofish::setIV()
  225. * @var bool
  226. * @access private
  227. */
  228. var $enchanged = true;
  229. /**
  230. * Does the demcrypt resource need to be (re)initialized?
  231. *
  232. * @see Crypt_Twofish::setKey()
  233. * @see Crypt_Twofish::setIV()
  234. * @var bool
  235. * @access private
  236. */
  237. var $dechanged = true;
  238. /**
  239. * mcrypt resource for CFB mode
  240. *
  241. * mcrypt's CFB mode, in (and only in) buffered context,
  242. * is broken, so phpseclib implements the CFB mode by it self,
  243. * even when the mcrypt php extension is available.
  244. *
  245. * In order to do the CFB-mode work (fast) phpseclib
  246. * use a separate ECB-mode mcrypt resource.
  247. *
  248. * @link http://phpseclib.sourceforge.net/cfb-demo.phps
  249. * @see self::encrypt()
  250. * @see self::decrypt()
  251. * @see self::_setupMcrypt()
  252. * @var resource
  253. * @access private
  254. */
  255. var $ecb;
  256. /**
  257. * Optimizing value while CFB-encrypting
  258. *
  259. * Only relevant if $continuousBuffer enabled
  260. * and $engine == CRYPT_ENGINE_MCRYPT
  261. *
  262. * It's faster to re-init $enmcrypt if
  263. * $buffer bytes > $cfb_init_len than
  264. * using the $ecb resource furthermore.
  265. *
  266. * This value depends of the chosen cipher
  267. * and the time it would be needed for it's
  268. * initialization [by mcrypt_generic_init()]
  269. * which, typically, depends on the complexity
  270. * on its internaly Key-expanding algorithm.
  271. *
  272. * @see self::encrypt()
  273. * @var int
  274. * @access private
  275. */
  276. var $cfb_init_len = 600;
  277. /**
  278. * Does internal cipher state need to be (re)initialized?
  279. *
  280. * @see self::setKey()
  281. * @see self::setIV()
  282. * @see self::disableContinuousBuffer()
  283. * @var bool
  284. * @access private
  285. */
  286. var $changed = true;
  287. /**
  288. * Padding status
  289. *
  290. * @see self::enablePadding()
  291. * @var bool
  292. * @access private
  293. */
  294. var $padding = true;
  295. /**
  296. * Is the mode one that is paddable?
  297. *
  298. * @see self::Crypt_Base()
  299. * @var bool
  300. * @access private
  301. */
  302. var $paddable = false;
  303. /**
  304. * Holds which crypt engine internaly should be use,
  305. * which will be determined automatically on __construct()
  306. *
  307. * Currently available $engines are:
  308. * - CRYPT_ENGINE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
  309. * - CRYPT_ENGINE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
  310. * - CRYPT_ENGINE_INTERNAL (slower, pure php-engine, no php-extension required)
  311. *
  312. * @see self::_setEngine()
  313. * @see self::encrypt()
  314. * @see self::decrypt()
  315. * @var int
  316. * @access private
  317. */
  318. var $engine;
  319. /**
  320. * Holds the preferred crypt engine
  321. *
  322. * @see self::_setEngine()
  323. * @see self::setPreferredEngine()
  324. * @var int
  325. * @access private
  326. */
  327. var $preferredEngine;
  328. /**
  329. * The mcrypt specific name of the cipher
  330. *
  331. * Only used if $engine == CRYPT_ENGINE_MCRYPT
  332. *
  333. * @link http://www.php.net/mcrypt_module_open
  334. * @link http://www.php.net/mcrypt_list_algorithms
  335. * @see self::_setupMcrypt()
  336. * @var string
  337. * @access private
  338. */
  339. var $cipher_name_mcrypt;
  340. /**
  341. * The openssl specific name of the cipher
  342. *
  343. * Only used if $engine == CRYPT_ENGINE_OPENSSL
  344. *
  345. * @link http://www.php.net/openssl-get-cipher-methods
  346. * @var string
  347. * @access private
  348. */
  349. var $cipher_name_openssl;
  350. /**
  351. * The openssl specific name of the cipher in ECB mode
  352. *
  353. * If OpenSSL does not support the mode we're trying to use (CTR)
  354. * it can still be emulated with ECB mode.
  355. *
  356. * @link http://www.php.net/openssl-get-cipher-methods
  357. * @var string
  358. * @access private
  359. */
  360. var $cipher_name_openssl_ecb;
  361. /**
  362. * The default salt used by setPassword()
  363. *
  364. * @see self::setPassword()
  365. * @var string
  366. * @access private
  367. */
  368. var $password_default_salt = 'phpseclib/salt';
  369. /**
  370. * The namespace used by the cipher for its constants.
  371. *
  372. * ie: AES.php is using CRYPT_AES_MODE_* for its constants
  373. * so $const_namespace is AES
  374. *
  375. * DES.php is using CRYPT_DES_MODE_* for its constants
  376. * so $const_namespace is DES... and so on
  377. *
  378. * All CRYPT_<$const_namespace>_MODE_* are aliases of
  379. * the generic CRYPT_MODE_* constants, so both could be used
  380. * for each cipher.
  381. *
  382. * Example:
  383. * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
  384. * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
  385. *
  386. * @see self::Crypt_Base()
  387. * @var string
  388. * @access private
  389. */
  390. var $const_namespace;
  391. /**
  392. * The name of the performance-optimized callback function
  393. *
  394. * Used by encrypt() / decrypt()
  395. * only if $engine == CRYPT_ENGINE_INTERNAL
  396. *
  397. * @see self::encrypt()
  398. * @see self::decrypt()
  399. * @see self::_setupInlineCrypt()
  400. * @see self::$use_inline_crypt
  401. * @var Callback
  402. * @access private
  403. */
  404. var $inline_crypt;
  405. /**
  406. * Holds whether performance-optimized $inline_crypt() can/should be used.
  407. *
  408. * @see self::encrypt()
  409. * @see self::decrypt()
  410. * @see self::inline_crypt
  411. * @var mixed
  412. * @access private
  413. */
  414. var $use_inline_crypt;
  415. /**
  416. * If OpenSSL can be used in ECB but not in CTR we can emulate CTR
  417. *
  418. * @see self::_openssl_ctr_process()
  419. * @var bool
  420. * @access private
  421. */
  422. var $openssl_emulate_ctr = false;
  423. /**
  424. * Determines what options are passed to openssl_encrypt/decrypt
  425. *
  426. * @see self::isValidEngine()
  427. * @var mixed
  428. * @access private
  429. */
  430. var $openssl_options;
  431. /**
  432. * Has the key length explicitly been set or should it be derived from the key, itself?
  433. *
  434. * @see self::setKeyLength()
  435. * @var bool
  436. * @access private
  437. */
  438. var $explicit_key_length = false;
  439. /**
  440. * Don't truncate / null pad key
  441. *
  442. * @see self::_clearBuffers()
  443. * @var bool
  444. * @access private
  445. */
  446. var $skip_key_adjustment = false;
  447. /**
  448. * Default Constructor.
  449. *
  450. * Determines whether or not the mcrypt extension should be used.
  451. *
  452. * $mode could be:
  453. *
  454. * - CRYPT_MODE_ECB
  455. *
  456. * - CRYPT_MODE_CBC
  457. *
  458. * - CRYPT_MODE_CTR
  459. *
  460. * - CRYPT_MODE_CFB
  461. *
  462. * - CRYPT_MODE_OFB
  463. *
  464. * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
  465. *
  466. * If not explicitly set, CRYPT_MODE_CBC will be used.
  467. *
  468. * @param int $mode
  469. * @access public
  470. */
  471. function __construct($mode = CRYPT_MODE_CBC)
  472. {
  473. // $mode dependent settings
  474. switch ($mode) {
  475. case CRYPT_MODE_ECB:
  476. $this->paddable = true;
  477. $this->mode = CRYPT_MODE_ECB;
  478. break;
  479. case CRYPT_MODE_CTR:
  480. case CRYPT_MODE_CFB:
  481. case CRYPT_MODE_OFB:
  482. case CRYPT_MODE_STREAM:
  483. $this->mode = $mode;
  484. break;
  485. case CRYPT_MODE_CBC:
  486. default:
  487. $this->paddable = true;
  488. $this->mode = CRYPT_MODE_CBC;
  489. }
  490. $this->_setEngine();
  491. // Determining whether inline crypting can be used by the cipher
  492. if ($this->use_inline_crypt !== false) {
  493. $this->use_inline_crypt = version_compare(PHP_VERSION, '5.3.0') >= 0 || function_exists('create_function');
  494. }
  495. }
  496. /**
  497. * PHP4 compatible Default Constructor.
  498. *
  499. * @see self::__construct()
  500. * @param int $mode
  501. * @access public
  502. */
  503. function Crypt_Base($mode = CRYPT_MODE_CBC)
  504. {
  505. $this->__construct($mode);
  506. }
  507. /**
  508. * Sets the initialization vector. (optional)
  509. *
  510. * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explicitly set, it'll be assumed
  511. * to be all zero's.
  512. *
  513. * @access public
  514. * @param string $iv
  515. * @internal Can be overwritten by a sub class, but does not have to be
  516. */
  517. function setIV($iv)
  518. {
  519. if ($this->mode == CRYPT_MODE_ECB) {
  520. return;
  521. }
  522. $this->iv = $iv;
  523. $this->changed = true;
  524. }
  525. /**
  526. * Sets the key length.
  527. *
  528. * Keys with explicitly set lengths need to be treated accordingly
  529. *
  530. * @access public
  531. * @param int $length
  532. */
  533. function setKeyLength($length)
  534. {
  535. $this->explicit_key_length = true;
  536. $this->changed = true;
  537. $this->_setEngine();
  538. }
  539. /**
  540. * Returns the current key length in bits
  541. *
  542. * @access public
  543. * @return int
  544. */
  545. function getKeyLength()
  546. {
  547. return $this->key_length << 3;
  548. }
  549. /**
  550. * Returns the current block length in bits
  551. *
  552. * @access public
  553. * @return int
  554. */
  555. function getBlockLength()
  556. {
  557. return $this->block_size << 3;
  558. }
  559. /**
  560. * Sets the key.
  561. *
  562. * The min/max length(s) of the key depends on the cipher which is used.
  563. * If the key not fits the length(s) of the cipher it will paded with null bytes
  564. * up to the closest valid key length. If the key is more than max length,
  565. * we trim the excess bits.
  566. *
  567. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  568. *
  569. * @access public
  570. * @param string $key
  571. * @internal Could, but not must, extend by the child Crypt_* class
  572. */
  573. function setKey($key)
  574. {
  575. if (!$this->explicit_key_length) {
  576. $this->setKeyLength(strlen($key) << 3);
  577. $this->explicit_key_length = false;
  578. }
  579. $this->key = $key;
  580. $this->changed = true;
  581. $this->_setEngine();
  582. }
  583. /**
  584. * Sets the password.
  585. *
  586. * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
  587. * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1:
  588. * $hash, $salt, $count, $dkLen
  589. *
  590. * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
  591. *
  592. * @see Crypt/Hash.php
  593. * @param string $password
  594. * @param string $method
  595. * @return bool
  596. * @access public
  597. * @internal Could, but not must, extend by the child Crypt_* class
  598. */
  599. function setPassword($password, $method = 'pbkdf2')
  600. {
  601. $key = '';
  602. switch ($method) {
  603. default: // 'pbkdf2' or 'pbkdf1'
  604. $func_args = func_get_args();
  605. // Hash function
  606. $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
  607. // WPA and WPA2 use the SSID as the salt
  608. $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
  609. // RFC2898#section-4.2 uses 1,000 iterations by default
  610. // WPA and WPA2 use 4,096.
  611. $count = isset($func_args[4]) ? $func_args[4] : 1000;
  612. // Keylength
  613. if (isset($func_args[5]) && $func_args[5] > 0) {
  614. $dkLen = $func_args[5];
  615. } else {
  616. $dkLen = $method == 'pbkdf1' ? 2 * $this->key_length : $this->key_length;
  617. }
  618. switch (true) {
  619. case $method == 'pbkdf1':
  620. if (!class_exists('Crypt_Hash')) {
  621. include_once 'Crypt/Hash.php';
  622. }
  623. $hashObj = new Crypt_Hash();
  624. $hashObj->setHash($hash);
  625. if ($dkLen > $hashObj->getLength()) {
  626. user_error('Derived key too long');
  627. return false;
  628. }
  629. $t = $password . $salt;
  630. for ($i = 0; $i < $count; ++$i) {
  631. $t = $hashObj->hash($t);
  632. }
  633. $key = substr($t, 0, $dkLen);
  634. $this->setKey(substr($key, 0, $dkLen >> 1));
  635. $this->setIV(substr($key, $dkLen >> 1));
  636. return true;
  637. // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
  638. case !function_exists('hash_pbkdf2'):
  639. case !function_exists('hash_algos'):
  640. case !in_array($hash, hash_algos()):
  641. if (!class_exists('Crypt_Hash')) {
  642. include_once 'Crypt/Hash.php';
  643. }
  644. $i = 1;
  645. $hmac = new Crypt_Hash();
  646. $hmac->setHash($hash);
  647. $hmac->setKey($password);
  648. while (strlen($key) < $dkLen) {
  649. $f = $u = $hmac->hash($salt . pack('N', $i++));
  650. for ($j = 2; $j <= $count; ++$j) {
  651. $u = $hmac->hash($u);
  652. $f^= $u;
  653. }
  654. $key.= $f;
  655. }
  656. $key = substr($key, 0, $dkLen);
  657. break;
  658. default:
  659. $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
  660. }
  661. }
  662. $this->setKey($key);
  663. return true;
  664. }
  665. /**
  666. * Encrypts a message.
  667. *
  668. * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
  669. * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
  670. * necessary are discussed in the following
  671. * URL:
  672. *
  673. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  674. *
  675. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  676. * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
  677. * length.
  678. *
  679. * @see self::decrypt()
  680. * @access public
  681. * @param string $plaintext
  682. * @return string $ciphertext
  683. * @internal Could, but not must, extend by the child Crypt_* class
  684. */
  685. function encrypt($plaintext)
  686. {
  687. if ($this->paddable) {
  688. $plaintext = $this->_pad($plaintext);
  689. }
  690. if ($this->engine === CRYPT_ENGINE_OPENSSL) {
  691. if ($this->changed) {
  692. $this->_clearBuffers();
  693. $this->changed = false;
  694. }
  695. switch ($this->mode) {
  696. case CRYPT_MODE_STREAM:
  697. return openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options);
  698. case CRYPT_MODE_ECB:
  699. $result = @openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options);
  700. return !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result;
  701. case CRYPT_MODE_CBC:
  702. $result = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->encryptIV);
  703. if (!defined('OPENSSL_RAW_DATA')) {
  704. $result = substr($result, 0, -$this->block_size);
  705. }
  706. if ($this->continuousBuffer) {
  707. $this->encryptIV = substr($result, -$this->block_size);
  708. }
  709. return $result;
  710. case CRYPT_MODE_CTR:
  711. return $this->_openssl_ctr_process($plaintext, $this->encryptIV, $this->enbuffer);
  712. case CRYPT_MODE_CFB:
  713. // cfb loosely routines inspired by openssl's:
  714. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  715. $ciphertext = '';
  716. if ($this->continuousBuffer) {
  717. $iv = &$this->encryptIV;
  718. $pos = &$this->enbuffer['pos'];
  719. } else {
  720. $iv = $this->encryptIV;
  721. $pos = 0;
  722. }
  723. $len = strlen($plaintext);
  724. $i = 0;
  725. if ($pos) {
  726. $orig_pos = $pos;
  727. $max = $this->block_size - $pos;
  728. if ($len >= $max) {
  729. $i = $max;
  730. $len-= $max;
  731. $pos = 0;
  732. } else {
  733. $i = $len;
  734. $pos+= $len;
  735. $len = 0;
  736. }
  737. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  738. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  739. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  740. $plaintext = substr($plaintext, $i);
  741. }
  742. $overflow = $len % $this->block_size;
  743. if ($overflow) {
  744. $ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv);
  745. $iv = $this->_string_pop($ciphertext, $this->block_size);
  746. $size = $len - $overflow;
  747. $block = $iv ^ substr($plaintext, -$overflow);
  748. $iv = substr_replace($iv, $block, 0, $overflow);
  749. $ciphertext.= $block;
  750. $pos = $overflow;
  751. } elseif ($len) {
  752. $ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv);
  753. $iv = substr($ciphertext, -$this->block_size);
  754. }
  755. return $ciphertext;
  756. case CRYPT_MODE_OFB:
  757. return $this->_openssl_ofb_process($plaintext, $this->encryptIV, $this->enbuffer);
  758. }
  759. }
  760. if ($this->engine === CRYPT_ENGINE_MCRYPT) {
  761. if ($this->changed) {
  762. $this->_setupMcrypt();
  763. $this->changed = false;
  764. }
  765. if ($this->enchanged) {
  766. @mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  767. $this->enchanged = false;
  768. }
  769. // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  770. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  771. // rewritten CFB implementation the above outputs the same thing twice.
  772. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  773. $block_size = $this->block_size;
  774. $iv = &$this->encryptIV;
  775. $pos = &$this->enbuffer['pos'];
  776. $len = strlen($plaintext);
  777. $ciphertext = '';
  778. $i = 0;
  779. if ($pos) {
  780. $orig_pos = $pos;
  781. $max = $block_size - $pos;
  782. if ($len >= $max) {
  783. $i = $max;
  784. $len-= $max;
  785. $pos = 0;
  786. } else {
  787. $i = $len;
  788. $pos+= $len;
  789. $len = 0;
  790. }
  791. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  792. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  793. $this->enbuffer['enmcrypt_init'] = true;
  794. }
  795. if ($len >= $block_size) {
  796. if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
  797. if ($this->enbuffer['enmcrypt_init'] === true) {
  798. @mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  799. $this->enbuffer['enmcrypt_init'] = false;
  800. }
  801. $ciphertext.= @mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
  802. $iv = substr($ciphertext, -$block_size);
  803. $len%= $block_size;
  804. } else {
  805. while ($len >= $block_size) {
  806. $iv = @mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
  807. $ciphertext.= $iv;
  808. $len-= $block_size;
  809. $i+= $block_size;
  810. }
  811. }
  812. }
  813. if ($len) {
  814. $iv = @mcrypt_generic($this->ecb, $iv);
  815. $block = $iv ^ substr($plaintext, -$len);
  816. $iv = substr_replace($iv, $block, 0, $len);
  817. $ciphertext.= $block;
  818. $pos = $len;
  819. }
  820. return $ciphertext;
  821. }
  822. $ciphertext = @mcrypt_generic($this->enmcrypt, $plaintext);
  823. if (!$this->continuousBuffer) {
  824. @mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  825. }
  826. return $ciphertext;
  827. }
  828. if ($this->changed) {
  829. $this->_setup();
  830. $this->changed = false;
  831. }
  832. if ($this->use_inline_crypt) {
  833. $inline = $this->inline_crypt;
  834. return $inline('encrypt', $this, $plaintext);
  835. }
  836. $buffer = &$this->enbuffer;
  837. $block_size = $this->block_size;
  838. $ciphertext = '';
  839. switch ($this->mode) {
  840. case CRYPT_MODE_ECB:
  841. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  842. $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
  843. }
  844. break;
  845. case CRYPT_MODE_CBC:
  846. $xor = $this->encryptIV;
  847. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  848. $block = substr($plaintext, $i, $block_size);
  849. $block = $this->_encryptBlock($block ^ $xor);
  850. $xor = $block;
  851. $ciphertext.= $block;
  852. }
  853. if ($this->continuousBuffer) {
  854. $this->encryptIV = $xor;
  855. }
  856. break;
  857. case CRYPT_MODE_CTR:
  858. $xor = $this->encryptIV;
  859. if (strlen($buffer['ciphertext'])) {
  860. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  861. $block = substr($plaintext, $i, $block_size);
  862. if (strlen($block) > strlen($buffer['ciphertext'])) {
  863. $buffer['ciphertext'].= $this->_encryptBlock($xor);
  864. }
  865. $this->_increment_str($xor);
  866. $key = $this->_string_shift($buffer['ciphertext'], $block_size);
  867. $ciphertext.= $block ^ $key;
  868. }
  869. } else {
  870. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  871. $block = substr($plaintext, $i, $block_size);
  872. $key = $this->_encryptBlock($xor);
  873. $this->_increment_str($xor);
  874. $ciphertext.= $block ^ $key;
  875. }
  876. }
  877. if ($this->continuousBuffer) {
  878. $this->encryptIV = $xor;
  879. if ($start = strlen($plaintext) % $block_size) {
  880. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  881. }
  882. }
  883. break;
  884. case CRYPT_MODE_CFB:
  885. // cfb loosely routines inspired by openssl's:
  886. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  887. if ($this->continuousBuffer) {
  888. $iv = &$this->encryptIV;
  889. $pos = &$buffer['pos'];
  890. } else {
  891. $iv = $this->encryptIV;
  892. $pos = 0;
  893. }
  894. $len = strlen($plaintext);
  895. $i = 0;
  896. if ($pos) {
  897. $orig_pos = $pos;
  898. $max = $block_size - $pos;
  899. if ($len >= $max) {
  900. $i = $max;
  901. $len-= $max;
  902. $pos = 0;
  903. } else {
  904. $i = $len;
  905. $pos+= $len;
  906. $len = 0;
  907. }
  908. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  909. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  910. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  911. }
  912. while ($len >= $block_size) {
  913. $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
  914. $ciphertext.= $iv;
  915. $len-= $block_size;
  916. $i+= $block_size;
  917. }
  918. if ($len) {
  919. $iv = $this->_encryptBlock($iv);
  920. $block = $iv ^ substr($plaintext, $i);
  921. $iv = substr_replace($iv, $block, 0, $len);
  922. $ciphertext.= $block;
  923. $pos = $len;
  924. }
  925. break;
  926. case CRYPT_MODE_OFB:
  927. $xor = $this->encryptIV;
  928. if (strlen($buffer['xor'])) {
  929. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  930. $block = substr($plaintext, $i, $block_size);
  931. if (strlen($block) > strlen($buffer['xor'])) {
  932. $xor = $this->_encryptBlock($xor);
  933. $buffer['xor'].= $xor;
  934. }
  935. $key = $this->_string_shift($buffer['xor'], $block_size);
  936. $ciphertext.= $block ^ $key;
  937. }
  938. } else {
  939. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  940. $xor = $this->_encryptBlock($xor);
  941. $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
  942. }
  943. $key = $xor;
  944. }
  945. if ($this->continuousBuffer) {
  946. $this->encryptIV = $xor;
  947. if ($start = strlen($plaintext) % $block_size) {
  948. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  949. }
  950. }
  951. break;
  952. case CRYPT_MODE_STREAM:
  953. $ciphertext = $this->_encryptBlock($plaintext);
  954. break;
  955. }
  956. return $ciphertext;
  957. }
  958. /**
  959. * Decrypts a message.
  960. *
  961. * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
  962. * it is.
  963. *
  964. * @see self::encrypt()
  965. * @access public
  966. * @param string $ciphertext
  967. * @return string $plaintext
  968. * @internal Could, but not must, extend by the child Crypt_* class
  969. */
  970. function decrypt($ciphertext)
  971. {
  972. if ($this->paddable) {
  973. // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
  974. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  975. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($this->block_size - strlen($ciphertext) % $this->block_size) % $this->block_size, chr(0));
  976. }
  977. if ($this->engine === CRYPT_ENGINE_OPENSSL) {
  978. if ($this->changed) {
  979. $this->_clearBuffers();
  980. $this->changed = false;
  981. }
  982. switch ($this->mode) {
  983. case CRYPT_MODE_STREAM:
  984. $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options);
  985. break;
  986. case CRYPT_MODE_ECB:
  987. if (!defined('OPENSSL_RAW_DATA')) {
  988. $ciphertext.= @openssl_encrypt('', $this->cipher_name_openssl_ecb, $this->key, true);
  989. }
  990. $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options);
  991. break;
  992. case CRYPT_MODE_CBC:
  993. if (!defined('OPENSSL_RAW_DATA')) {
  994. $padding = str_repeat(chr($this->block_size), $this->block_size) ^ substr($ciphertext, -$this->block_size);
  995. $ciphertext.= substr(@openssl_encrypt($padding, $this->cipher_name_openssl_ecb, $this->key, true), 0, $this->block_size);
  996. $offset = 2 * $this->block_size;
  997. } else {
  998. $offset = $this->block_size;
  999. }
  1000. $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->decryptIV);
  1001. if ($this->continuousBuffer) {
  1002. $this->decryptIV = substr($ciphertext, -$offset, $this->block_size);
  1003. }
  1004. break;
  1005. case CRYPT_MODE_CTR:
  1006. $plaintext = $this->_openssl_ctr_process($ciphertext, $this->decryptIV, $this->debuffer);
  1007. break;
  1008. case CRYPT_MODE_CFB:
  1009. // cfb loosely routines inspired by openssl's:
  1010. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  1011. $plaintext = '';
  1012. if ($this->continuousBuffer) {
  1013. $iv = &$this->decryptIV;
  1014. $pos = &$this->buffer['pos'];
  1015. } else {
  1016. $iv = $this->decryptIV;
  1017. $pos = 0;
  1018. }
  1019. $len = strlen($ciphertext);
  1020. $i = 0;
  1021. if ($pos) {
  1022. $orig_pos = $pos;
  1023. $max = $this->block_size - $pos;
  1024. if ($len >= $max) {
  1025. $i = $max;
  1026. $len-= $max;
  1027. $pos = 0;
  1028. } else {
  1029. $i = $len;
  1030. $pos+= $len;
  1031. $len = 0;
  1032. }
  1033. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $this->blocksize
  1034. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  1035. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  1036. $ciphertext = substr($ciphertext, $i);
  1037. }
  1038. $overflow = $len % $this->block_size;
  1039. if ($overflow) {
  1040. $plaintext.= openssl_decrypt(substr($ciphertext, 0, -$overflow), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv);
  1041. if ($len - $overflow) {
  1042. $iv = substr($ciphertext, -$overflow - $this->block_size, -$overflow);
  1043. }
  1044. $iv = openssl_encrypt(str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv);
  1045. $plaintext.= $iv ^ substr($ciphertext, -$overflow);
  1046. $iv = substr_replace($iv, substr($ciphertext, -$overflow), 0, $overflow);
  1047. $pos = $overflow;
  1048. } elseif ($len) {
  1049. $plaintext.= openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv);
  1050. $iv = substr($ciphertext, -$this->block_size);
  1051. }
  1052. break;
  1053. case CRYPT_MODE_OFB:
  1054. $plaintext = $this->_openssl_ofb_process($ciphertext, $this->decryptIV, $this->debuffer);
  1055. }
  1056. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  1057. }
  1058. if ($this->engine === CRYPT_ENGINE_MCRYPT) {
  1059. $block_size = $this->block_size;
  1060. if ($this->changed) {
  1061. $this->_setupMcrypt();
  1062. $this->changed = false;
  1063. }
  1064. if ($this->dechanged) {
  1065. @mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  1066. $this->dechanged = false;
  1067. }
  1068. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  1069. $iv = &$this->decryptIV;
  1070. $pos = &$this->debuffer['pos'];
  1071. $len = strlen($ciphertext);
  1072. $plaintext = '';
  1073. $i = 0;
  1074. if ($pos) {
  1075. $orig_pos = $pos;
  1076. $max = $block_size - $pos;
  1077. if ($len >= $max) {
  1078. $i = $max;
  1079. $len-= $max;
  1080. $pos = 0;
  1081. } else {
  1082. $i = $len;
  1083. $pos+= $len;
  1084. $len = 0;
  1085. }
  1086. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  1087. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  1088. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  1089. }
  1090. if ($len >= $block_size) {
  1091. $cb = substr($ciphertext, $i, $len - $len % $block_size);
  1092. $plaintext.= @mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  1093. $iv = substr($cb, -$block_size);
  1094. $len%= $block_size;
  1095. }
  1096. if ($len) {
  1097. $iv = @mcrypt_generic($this->ecb, $iv);
  1098. $plaintext.= $iv ^ substr($ciphertext, -$len);
  1099. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  1100. $pos = $len;
  1101. }
  1102. return $plaintext;
  1103. }
  1104. $plaintext = @mdecrypt_generic($this->demcrypt, $ciphertext);
  1105. if (!$this->continuousBuffer) {
  1106. @mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  1107. }
  1108. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  1109. }
  1110. if ($this->changed) {
  1111. $this->_setup();
  1112. $this->changed = false;
  1113. }
  1114. if ($this->use_inline_crypt) {
  1115. $inline = $this->inline_crypt;
  1116. return $inline('decrypt', $this, $ciphertext);
  1117. }
  1118. $block_size = $this->block_size;
  1119. $buffer = &$this->debuffer;
  1120. $plaintext = '';
  1121. switch ($this->mode) {
  1122. case CRYPT_MODE_ECB:
  1123. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1124. $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
  1125. }
  1126. break;
  1127. case CRYPT_MODE_CBC:
  1128. $xor = $this->decryptIV;
  1129. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1130. $block = substr($ciphertext, $i, $block_size);
  1131. $plaintext.= $this->_decryptBlock($block) ^ $xor;
  1132. $xor = $block;
  1133. }
  1134. if ($this->continuousBuffer) {
  1135. $this->decryptIV = $xor;
  1136. }
  1137. break;
  1138. case CRYPT_MODE_CTR:
  1139. $xor = $this->decryptIV;
  1140. if (strlen($buffer['ciphertext'])) {
  1141. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1142. $block = substr($ciphertext, $i, $block_size);
  1143. if (strlen($block) > strlen($buffer['ciphertext'])) {
  1144. $buffer['ciphertext'].= $this->_encryptBlock($xor);
  1145. $this->_increment_str($xor);
  1146. }
  1147. $key = $this->_string_shift($buffer['ciphertext'], $block_size);
  1148. $plaintext.= $block ^ $key;
  1149. }
  1150. } else {
  1151. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1152. $block = substr($ciphertext, $i, $block_size);
  1153. $key = $this->_encryptBlock($xor);
  1154. $this->_increment_str($xor);
  1155. $plaintext.= $block ^ $key;
  1156. }
  1157. }
  1158. if ($this->continuousBuffer) {
  1159. $this->decryptIV = $xor;
  1160. if ($start = strlen($ciphertext) % $block_size) {
  1161. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  1162. }
  1163. }
  1164. break;
  1165. case CRYPT_MODE_CFB:
  1166. if ($this->continuousBuffer) {
  1167. $iv = &$this->decryptIV;
  1168. $pos = &$buffer['pos'];
  1169. } else {
  1170. $iv = $this->decryptIV;
  1171. $pos = 0;
  1172. }
  1173. $len = strlen($ciphertext);
  1174. $i = 0;
  1175. if ($pos) {
  1176. $orig_pos = $pos;
  1177. $max = $block_size - $pos;
  1178. if ($len >= $max) {
  1179. $i = $max;
  1180. $len-= $max;
  1181. $pos = 0;
  1182. } else {
  1183. $i = $len;
  1184. $pos+= $len;
  1185. $len = 0;
  1186. }
  1187. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  1188. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  1189. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  1190. }
  1191. while ($len >= $block_size) {
  1192. $iv = $this->_encryptBlock($iv);
  1193. $cb = substr($ciphertext, $i, $block_size);
  1194. $plaintext.= $iv ^ $cb;
  1195. $iv = $cb;
  1196. $len-= $block_size;
  1197. $i+= $block_size;
  1198. }
  1199. if ($len) {
  1200. $iv = $this->_encryptBlock($iv);
  1201. $plaintext.= $iv ^ substr($ciphertext, $i);
  1202. $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
  1203. $pos = $len;
  1204. }
  1205. break;
  1206. case CRYPT_MODE_OFB:
  1207. $xor = $this->decryptIV;
  1208. if (strlen($buffer['xor'])) {
  1209. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1210. $block = substr($ciphertext, $i, $block_size);
  1211. if (strlen($block) > strlen($buffer['xor'])) {
  1212. $xor = $this->_encryptBlock($xor);
  1213. $buffer['xor'].= $xor;
  1214. }
  1215. $key = $this->_string_shift($buffer['xor'], $block_size);
  1216. $plaintext.= $block ^ $key;
  1217. }
  1218. } else {
  1219. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  1220. $xor = $this->_encryptBlock($xor);
  1221. $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
  1222. }
  1223. $key = $xor;
  1224. }
  1225. if ($this->continuousBuffer) {
  1226. $this->decryptIV = $xor;
  1227. if ($start = strlen($ciphertext) % $block_size) {
  1228. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  1229. }
  1230. }
  1231. break;
  1232. case CRYPT_MODE_STREAM:
  1233. $plaintext = $this->_decryptBlock($ciphertext);
  1234. break;
  1235. }
  1236. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  1237. }
  1238. /**
  1239. * OpenSSL CTR Processor
  1240. *
  1241. * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream
  1242. * for CTR is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt()
  1243. * and Crypt_Base::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this
  1244. * function will emulate CTR with ECB when necessary.
  1245. *
  1246. * @see self::encrypt()
  1247. * @see self::decrypt()
  1248. * @param string $plaintext
  1249. * @param string $encryptIV
  1250. * @param array $buffer
  1251. * @return string
  1252. * @access private
  1253. */
  1254. function _openssl_ctr_process($plaintext, &$encryptIV, &$buffer)
  1255. {
  1256. $ciphertext = '';
  1257. $block_size = $this->block_size;
  1258. $key = $this->key;
  1259. if ($this->openssl_emulate_ctr) {
  1260. $xor = $encryptIV;
  1261. if (strlen($buffer['ciphertext'])) {
  1262. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  1263. $block = substr($plaintext, $i, $block_size);
  1264. if (strlen($block) > strlen($buffer['ciphertext'])) {
  1265. $result = @openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, $this->openssl_options);
  1266. $result = !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result;
  1267. $buffer['ciphertext'].= $result;
  1268. }
  1269. $this->_increment_str($xor);
  1270. $otp = $this->_string_shift($buffer['ciphertext'], $block_size);
  1271. $ciphertext.= $block ^ $otp;
  1272. }
  1273. } else {
  1274. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  1275. $block = substr($plaintext, $i, $block_size);
  1276. $otp = @openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, $this->openssl_options);
  1277. $otp = !defined('OPENSSL_RAW_DATA') ? substr($otp, 0, -$this->block_size) : $otp;
  1278. $this->_increment_str($xor);
  1279. $ciphertext.= $block ^ $otp;
  1280. }
  1281. }
  1282. if ($this->continuousBuffer) {
  1283. $encryptIV = $xor;
  1284. if ($start = strlen($plaintext) % $block_size) {
  1285. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  1286. }
  1287. }
  1288. return $ciphertext;
  1289. }
  1290. if (strlen($buffer['ciphertext'])) {
  1291. $ciphertext = $plaintext ^ $this->_string_shift($buffer['ciphertext'], strlen($plaintext));
  1292. $plaintext = substr($plaintext, strlen($ciphertext));
  1293. if (!strlen($plaintext)) {
  1294. return $ciphertext;
  1295. }
  1296. }
  1297. $overflow = strlen($plaintext) % $block_size;
  1298. if ($overflow) {
  1299. $plaintext2 = $this->_string_pop($plaintext, $overflow); // ie. trim $plaintext to a multiple of $block_size and put rest of $plaintext in $plaintext2
  1300. $encrypted = openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV);
  1301. $temp = $this->_string_pop($encrypted, $block_size);
  1302. $ciphertext.= $encrypted . ($plaintext2 ^ $temp);
  1303. if ($this->continuousBuffer) {
  1304. $buffer['ciphertext'] = substr($temp, $overflow);
  1305. $encryptIV = $temp;
  1306. }
  1307. } elseif (!strlen($buffer['ciphertext'])) {
  1308. $ciphertext.= openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV);
  1309. $temp = $this->_string_pop($ciphertext, $block_size);
  1310. if ($this->continuousBuffer) {
  1311. $encryptIV = $temp;
  1312. }
  1313. }
  1314. if ($this->continuousBuffer) {
  1315. if (!defined('OPENSSL_RAW_DATA')) {
  1316. $encryptIV.= @openssl_encrypt('', $this->cipher_name_openssl_ecb, $key, $this->openssl_options);
  1317. }
  1318. $encryptIV = openssl_decrypt($encryptIV, $this->cipher_name_openssl_ecb, $key, $this->openssl_options);
  1319. if ($overflow) {
  1320. $this->_increment_str($encryptIV);
  1321. }
  1322. }
  1323. return $ciphertext;
  1324. }
  1325. /**
  1326. * OpenSSL OFB Processor
  1327. *
  1328. * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream
  1329. * for OFB is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt()
  1330. * and Crypt_Base::decrypt().
  1331. *
  1332. * @see self::encrypt()
  1333. * @see self::decrypt()
  1334. * @param string $plaintext
  1335. * @param string $encryptIV
  1336. * @param array $buffer
  1337. * @return string
  1338. * @access private
  1339. */
  1340. function _openssl_ofb_process($plaintext, &$encryptIV, &$buffer)
  1341. {
  1342. if (strlen($buffer['xor'])) {
  1343. $ciphertext = $plaintext ^ $buffer['xor'];
  1344. $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext));
  1345. $plaintext = substr($plaintext, strlen($ciphertext));
  1346. } else {
  1347. $ciphertext = '';
  1348. }
  1349. $block_size = $this->block_size;
  1350. $len = strlen($plaintext);
  1351. $key = $this->key;
  1352. $overflow = $len % $block_size;
  1353. if (strlen($plaintext)) {
  1354. if ($overflow) {
  1355. $ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV);
  1356. $xor = $this->_string_pop($ciphertext, $block_size);
  1357. if ($this->continuousBuffer) {
  1358. $encryptIV = $xor;
  1359. }
  1360. $ciphertext.= $this->_string_shift($xor, $overflow) ^ substr($plaintext, -$overflow);
  1361. if ($this->continuousBuffer) {
  1362. $buffer['xor'] = $xor;
  1363. }
  1364. } else {
  1365. $ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV);
  1366. if ($this->continuousBuffer) {
  1367. $encryptIV = substr($ciphertext, -$block_size) ^ substr($plaintext, -$block_size);
  1368. }
  1369. }
  1370. }
  1371. return $ciphertext;
  1372. }
  1373. /**
  1374. * phpseclib <-> OpenSSL Mode Mapper
  1375. *
  1376. * May need to be overwritten by classes extending this one in some cases
  1377. *
  1378. * @return int
  1379. * @access private
  1380. */
  1381. function _openssl_translate_mode()
  1382. {
  1383. switch ($this->mode) {
  1384. case CRYPT_MODE_ECB:
  1385. return 'ecb';
  1386. case CRYPT_MODE_CBC:
  1387. return 'cbc';
  1388. case CRYPT_MODE_CTR:
  1389. return 'ctr';
  1390. case CRYPT_MODE_CFB:
  1391. return 'cfb';
  1392. case CRYPT_MODE_OFB:
  1393. return 'ofb';
  1394. }
  1395. }
  1396. /**
  1397. * Pad "packets".
  1398. *
  1399. * Block ciphers working by encrypting between their specified [$this->]block_size at a time
  1400. * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
  1401. * pad the input so that it is of the proper length.
  1402. *
  1403. * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
  1404. * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
  1405. * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
  1406. * transmitted separately)
  1407. *
  1408. * @see self::disablePadding()
  1409. * @access public
  1410. */
  1411. function enablePadding()
  1412. {
  1413. $this->padding = true;
  1414. }
  1415. /**
  1416. * Do not pad packets.
  1417. *
  1418. * @see self::enablePadding()
  1419. * @access public
  1420. */
  1421. function disablePadding()
  1422. {
  1423. $this->padding = false;
  1424. }
  1425. /**
  1426. * Treat consecutive "packets" as if they are a continuous buffer.
  1427. *
  1428. * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  1429. * will yield different outputs:
  1430. *
  1431. * <code>
  1432. * echo $rijndael->encrypt(substr($plaintext, 0, 16));
  1433. * echo $rijndael->encrypt(substr($plaintext, 16, 16));
  1434. * </code>
  1435. * <code>
  1436. * echo $rijndael->encrypt($plaintext);
  1437. * </code>
  1438. *
  1439. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  1440. * another, as demonstrated with the following:
  1441. *
  1442. * <code>
  1443. * $rijndael->encrypt(substr($plaintext, 0, 16));
  1444. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1445. * </code>
  1446. * <code>
  1447. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1448. * </code>
  1449. *
  1450. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  1451. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  1452. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  1453. *
  1454. * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
  1455. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  1456. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  1457. * however, they are also less intuitive and more likely to cause you problems.
  1458. *
  1459. * @see self::disableContinuousBuffer()
  1460. * @access public
  1461. * @internal Could, but not must, extend by the child Crypt_* class
  1462. */
  1463. function enableContinuousBuffer()
  1464. {
  1465. if ($this->mode == CRYPT_MODE_ECB) {
  1466. return;
  1467. }
  1468. $this->continuousBuffer = true;
  1469. $this->_setEngine();
  1470. }
  1471. /**
  1472. * Treat consecutive packets as if they are a discontinuous buffer.
  1473. *
  1474. * The default behavior.
  1475. *
  1476. * @see self::enableContinuousBuffer()
  1477. * @access public
  1478. * @internal Could, but not must, extend by the child Crypt_* class
  1479. */
  1480. function disableContinuousBuffer()
  1481. {
  1482. if ($this->mode == CRYPT_MODE_ECB) {
  1483. return;
  1484. }
  1485. if (!$this->continuousBuffer) {
  1486. return;
  1487. }
  1488. $this->continuousBuffer = false;
  1489. $this->changed = true;
  1490. $this->_setEngine();
  1491. }
  1492. /**
  1493. * Test for engine validity
  1494. *
  1495. * @see self::Crypt_Base()
  1496. * @param int $engine
  1497. * @access public
  1498. * @return bool
  1499. */
  1500. function isValidEngine($engine)
  1501. {
  1502. switch ($engine) {
  1503. case CRYPT_ENGINE_OPENSSL:
  1504. if ($this->mode == CRYPT_MODE_STREAM && $this->continuousBuffer) {
  1505. return false;
  1506. }
  1507. $this->openssl_emulate_ctr = false;
  1508. $result = $this->cipher_name_openssl &&
  1509. extension_loaded('openssl') &&
  1510. // PHP 5.3.0 - 5.3.2 did not let you set IV's
  1511. version_compare(PHP_VERSION, '5.3.3', '>=');
  1512. if (!$result) {
  1513. return false;
  1514. }
  1515. // prior to PHP 5.4.0 OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING were not defined. instead of expecting an integer
  1516. // $options openssl_encrypt expected a boolean $raw_data.
  1517. if (!defined('OPENSSL_RAW_DATA')) {
  1518. $this->openssl_options = true;
  1519. } else {
  1520. $this->openssl_options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING;
  1521. }
  1522. $methods = openssl_get_cipher_methods();
  1523. if (in_array($this->cipher_name_openssl, $methods)) {
  1524. return true;
  1525. }
  1526. // not all of openssl's symmetric cipher's support ctr. for those
  1527. // that don't we'll emulate it
  1528. switch ($this->mode) {
  1529. case CRYPT_MODE_CTR:
  1530. if (in_array($this->cipher_name_openssl_ecb, $methods)) {
  1531. $this->openssl_emulate_ctr = true;
  1532. return true;
  1533. }
  1534. }
  1535. return false;
  1536. case CRYPT_ENGINE_MCRYPT:
  1537. return $this->cipher_name_mcrypt &&
  1538. extension_loaded('mcrypt') &&
  1539. in_array($this->cipher_name_mcrypt, @mcrypt_list_algorithms());
  1540. case CRYPT_ENGINE_INTERNAL:
  1541. return true;
  1542. }
  1543. return false;
  1544. }
  1545. /**
  1546. * Sets the preferred crypt engine
  1547. *
  1548. * Currently, $engine could be:
  1549. *
  1550. * - CRYPT_ENGINE_OPENSSL [very fast]
  1551. *
  1552. * - CRYPT_ENGINE_MCRYPT [fast]
  1553. *
  1554. * - CRYPT_ENGINE_INTERNAL [slow]
  1555. *
  1556. * If the preferred crypt engine is not available the fastest available one will be used
  1557. *
  1558. * @see self::Crypt_Base()
  1559. * @param int $engine
  1560. * @access public
  1561. */
  1562. function setPreferredEngine($engine)
  1563. {
  1564. switch ($engine) {
  1565. //case CRYPT_ENGINE_OPENSSL:
  1566. case CRYPT_ENGINE_MCRYPT:
  1567. case CRYPT_ENGINE_INTERNAL:
  1568. $this->preferredEngine = $engine;
  1569. break;
  1570. default:
  1571. $this->preferredEngine = CRYPT_ENGINE_OPENSSL;
  1572. }
  1573. $this->_setEngine();
  1574. }
  1575. /**
  1576. * Returns the engine currently being utilized
  1577. *
  1578. * @see self::_setEngine()
  1579. * @access public
  1580. */
  1581. function getEngine()
  1582. {
  1583. return $this->engine;
  1584. }
  1585. /**
  1586. * Sets the engine as appropriate
  1587. *
  1588. * @see self::Crypt_Base()
  1589. * @access private
  1590. */
  1591. function _setEngine()
  1592. {
  1593. $this->engine = null;
  1594. $candidateEngines = array(
  1595. $this->preferredEngine,
  1596. CRYPT_ENGINE_OPENSSL,
  1597. CRYPT_ENGINE_MCRYPT
  1598. );
  1599. foreach ($candidateEngines as $engine) {
  1600. if ($this->isValidEngine($engine)) {
  1601. $this->engine = $engine;
  1602. break;
  1603. }
  1604. }
  1605. if (!$this->engine) {
  1606. $this->engine = CRYPT_ENGINE_INTERNAL;
  1607. }
  1608. if ($this->engine != CRYPT_ENGINE_MCRYPT && $this->enmcrypt) {
  1609. // Closing the current mcrypt resource(s). _mcryptSetup() will, if needed,
  1610. // (re)open them with the module named in $this->cipher_name_mcrypt
  1611. @mcrypt_module_close($this->enmcrypt);
  1612. @mcrypt_module_close($this->demcrypt);
  1613. $this->enmcrypt = null;
  1614. $this->demcrypt = null;
  1615. if ($this->ecb) {
  1616. @mcrypt_module_close($this->ecb);
  1617. $this->ecb = null;
  1618. }
  1619. }
  1620. $this->changed = true;
  1621. }
  1622. /**
  1623. * Encrypts a block
  1624. *
  1625. * @access private
  1626. * @param string $in
  1627. * @return string
  1628. * @internal Must be extended by the child Crypt_* class
  1629. */
  1630. function _encryptBlock($in)
  1631. {
  1632. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1633. }
  1634. /**
  1635. * Decrypts a block
  1636. *
  1637. * @access private
  1638. * @param string $in
  1639. * @return string
  1640. * @internal Must be extended by the child Crypt_* class
  1641. */
  1642. function _decryptBlock($in)
  1643. {
  1644. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1645. }
  1646. /**
  1647. * Setup the key (expansion)
  1648. *
  1649. * Only used if $engine == CRYPT_ENGINE_INTERNAL
  1650. *
  1651. * @see self::_setup()
  1652. * @access private
  1653. * @internal Must be extended by the child Crypt_* class
  1654. */
  1655. function _setupKey()
  1656. {
  1657. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1658. }
  1659. /**
  1660. * Setup the CRYPT_ENGINE_INTERNAL $engine
  1661. *
  1662. * (re)init, if necessary, the internal cipher $engine and flush all $buffers
  1663. * Used (only) if $engine == CRYPT_ENGINE_INTERNAL
  1664. *
  1665. * _setup() will be called each time if $changed === true
  1666. * typically this happens when using one or more of following public methods:
  1667. *
  1668. * - setKey()
  1669. *
  1670. * - setIV()
  1671. *
  1672. * - disableContinuousBuffer()
  1673. *
  1674. * - First run of encrypt() / decrypt() with no init-settings
  1675. *
  1676. * @see self::setKey()
  1677. * @see self::setIV()
  1678. * @see self::disableContinuousBuffer()
  1679. * @access private
  1680. * @internal _setup() is always called before en/decryption.
  1681. * @internal Could, but not must, extend by the child Crypt_* class
  1682. */
  1683. function _setup()
  1684. {
  1685. $this->_clearBuffers();
  1686. $this->_setupKey();
  1687. if ($this->use_inline_crypt) {
  1688. $this->_setupInlineCrypt();
  1689. }
  1690. }
  1691. /**
  1692. * Setup the CRYPT_ENGINE_MCRYPT $engine
  1693. *
  1694. * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
  1695. * Used (only) if $engine = CRYPT_ENGINE_MCRYPT
  1696. *
  1697. * _setupMcrypt() will be called each time if $changed === true
  1698. * typically this happens when using one or more of following public methods:
  1699. *
  1700. * - setKey()
  1701. *
  1702. * - setIV()
  1703. *
  1704. * - disableContinuousBuffer()
  1705. *
  1706. * - First run of encrypt() / decrypt()
  1707. *
  1708. * @see self::setKey()
  1709. * @see self::setIV()
  1710. * @see self::disableContinuousBuffer()
  1711. * @access private
  1712. * @internal Could, but not must, extend by the child Crypt_* class
  1713. */
  1714. function _setupMcrypt()
  1715. {
  1716. $this->_clearBuffers();
  1717. $this->enchanged = $this->dechanged = true;
  1718. if (!isset($this->enmcrypt)) {
  1719. static $mcrypt_modes = array(
  1720. CRYPT_MODE_CTR => 'ctr',
  1721. CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
  1722. CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
  1723. CRYPT_MODE_CFB => 'ncfb',
  1724. CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
  1725. CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
  1726. );
  1727. $this->demcrypt = @mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1728. $this->enmcrypt = @mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1729. // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
  1730. // to workaround mcrypt's broken ncfb implementation in buffered mode
  1731. // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  1732. if ($this->mode == CRYPT_MODE_CFB) {
  1733. $this->ecb = @mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
  1734. }
  1735. } // else should mcrypt_generic_deinit be called?
  1736. if ($this->mode == CRYPT_MODE_CFB) {
  1737. @mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
  1738. }
  1739. }
  1740. /**
  1741. * Pads a string
  1742. *
  1743. * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
  1744. * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
  1745. * chr($this->block_size - (strlen($text) % $this->block_size)
  1746. *
  1747. * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
  1748. * and padding will, hence forth, be enabled.
  1749. *
  1750. * @see self::_unpad()
  1751. * @param string $text
  1752. * @access private
  1753. * @return string
  1754. */
  1755. function _pad($text)
  1756. {
  1757. $length = strlen($text);
  1758. if (!$this->padding) {
  1759. if ($length % $this->block_size == 0) {
  1760. return $text;
  1761. } else {
  1762. user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
  1763. $this->padding = true;
  1764. }
  1765. }
  1766. $pad = $this->block_size - ($length % $this->block_size);
  1767. return str_pad($text, $length + $pad, chr($pad));
  1768. }
  1769. /**
  1770. * Unpads a string.
  1771. *
  1772. * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
  1773. * and false will be returned.
  1774. *
  1775. * @see self::_pad()
  1776. * @param string $text
  1777. * @access private
  1778. * @return string
  1779. */
  1780. function _unpad($text)
  1781. {
  1782. if (!$this->padding) {
  1783. return $text;
  1784. }
  1785. $length = ord($text[strlen($text) - 1]);
  1786. if (!$length || $length > $this->block_size) {
  1787. return false;
  1788. }
  1789. return substr($text, 0, -$length);
  1790. }
  1791. /**
  1792. * Clears internal buffers
  1793. *
  1794. * Clearing/resetting the internal buffers is done everytime
  1795. * after disableContinuousBuffer() or on cipher $engine (re)init
  1796. * ie after setKey() or setIV()
  1797. *
  1798. * @access public
  1799. * @internal Could, but not must, extend by the child Crypt_* class
  1800. */
  1801. function _clearBuffers()
  1802. {
  1803. $this->enbuffer = $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
  1804. // mcrypt's handling of invalid's $iv:
  1805. // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
  1806. $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
  1807. if (!$this->skip_key_adjustment) {
  1808. $this->key = str_pad(substr($this->key, 0, $this->key_length), $this->key_length, "\0");
  1809. }
  1810. }
  1811. /**
  1812. * String Shift
  1813. *
  1814. * Inspired by array_shift
  1815. *
  1816. * @param string $string
  1817. * @param int $index
  1818. * @access private
  1819. * @return string
  1820. */
  1821. function _string_shift(&$string, $index = 1)
  1822. {
  1823. $substr = substr($string, 0, $index);
  1824. $string = substr($string, $index);
  1825. return $substr;
  1826. }
  1827. /**
  1828. * String Pop
  1829. *
  1830. * Inspired by array_pop
  1831. *
  1832. * @param string $string
  1833. * @param int $index
  1834. * @access private
  1835. * @return string
  1836. */
  1837. function _string_pop(&$string, $index = 1)
  1838. {
  1839. $substr = substr($string, -$index);
  1840. $string = substr($string, 0, -$index);
  1841. return $substr;
  1842. }
  1843. /**
  1844. * Increment the current string
  1845. *
  1846. * @see self::decrypt()
  1847. * @see self::encrypt()
  1848. * @param string $var
  1849. * @access private
  1850. */
  1851. function _increment_str(&$var)
  1852. {
  1853. for ($i = 4; $i <= strlen($var); $i+= 4) {
  1854. $temp = substr($var, -$i, 4);
  1855. switch ($temp) {
  1856. case "\xFF\xFF\xFF\xFF":
  1857. $var = substr_replace($var, "\x00\x00\x00\x00", -$i, 4);
  1858. break;
  1859. case "\x7F\xFF\xFF\xFF":
  1860. $var = substr_replace($var, "\x80\x00\x00\x00", -$i, 4);
  1861. return;
  1862. default:
  1863. $temp = unpack('Nnum', $temp);
  1864. $var = substr_replace($var, pack('N', $temp['num'] + 1), -$i, 4);
  1865. return;
  1866. }
  1867. }
  1868. $remainder = strlen($var) % 4;
  1869. if ($remainder == 0) {
  1870. return;
  1871. }
  1872. $temp = unpack('Nnum', str_pad(substr($var, 0, $remainder), 4, "\0", STR_PAD_LEFT));
  1873. $temp = substr(pack('N', $temp['num'] + 1), -$remainder);
  1874. $var = substr_replace($var, $temp, 0, $remainder);
  1875. }
  1876. /**
  1877. * Setup the performance-optimized function for de/encrypt()
  1878. *
  1879. * Stores the created (or existing) callback function-name
  1880. * in $this->inline_crypt
  1881. *
  1882. * Internally for phpseclib developers:
  1883. *
  1884. * _setupInlineCrypt() would be called only if:
  1885. *
  1886. * - $engine == CRYPT_ENGINE_INTERNAL and
  1887. *
  1888. * - $use_inline_crypt === true
  1889. *
  1890. * - each time on _setup(), after(!) _setupKey()
  1891. *
  1892. *
  1893. * This ensures that _setupInlineCrypt() has always a
  1894. * full ready2go initializated internal cipher $engine state
  1895. * where, for example, the keys allready expanded,
  1896. * keys/block_size calculated and such.
  1897. *
  1898. * It is, each time if called, the responsibility of _setupInlineCrypt():
  1899. *
  1900. * - to set $this->inline_crypt to a valid and fully working callback function
  1901. * as a (faster) replacement for encrypt() / decrypt()
  1902. *
  1903. * - NOT to create unlimited callback functions (for memory reasons!)
  1904. * no matter how often _setupInlineCrypt() would be called. At some
  1905. * point of amount they must be generic re-useable.
  1906. *
  1907. * - the code of _setupInlineCrypt() it self,
  1908. * and the generated callback code,
  1909. * must be, in following order:
  1910. * - 100% safe
  1911. * - 100% compatible to encrypt()/decrypt()
  1912. * - using only php5+ features/lang-constructs/php-extensions if
  1913. * compatibility (down to php4) or fallback is provided
  1914. * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
  1915. * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
  1916. * the reason for the existence of _setupInlineCrypt() :-)]
  1917. * - memory-nice
  1918. * - short (as good as possible)
  1919. *
  1920. * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
  1921. * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
  1922. * - The following variable names are reserved:
  1923. * - $_* (all variable names prefixed with an underscore)
  1924. * - $self (object reference to it self. Do not use $this, but $self instead)
  1925. * - $in (the content of $in has to en/decrypt by the generated code)
  1926. * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
  1927. *
  1928. *
  1929. * @see self::_setup()
  1930. * @see self::_createInlineCryptFunction()
  1931. * @see self::encrypt()
  1932. * @see self::decrypt()
  1933. * @access private
  1934. * @internal If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
  1935. */
  1936. function _setupInlineCrypt()
  1937. {
  1938. // If, for any reason, an extending Crypt_Base() Crypt_* class
  1939. // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
  1940. // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
  1941. // in the constructor at object instance-time
  1942. // or, if it's runtime-specific, at runtime
  1943. $this->use_inline_crypt = false;
  1944. }
  1945. /**
  1946. * Creates the performance-optimized function for en/decrypt()
  1947. *
  1948. * Internally for phpseclib developers:
  1949. *
  1950. * _createInlineCryptFunction():
  1951. *
  1952. * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
  1953. * with the current [$this->]mode of operation code
  1954. *
  1955. * - create the $inline function, which called by encrypt() / decrypt()
  1956. * as its replacement to speed up the en/decryption operations.
  1957. *
  1958. * - return the name of the created $inline callback function
  1959. *
  1960. * - used to speed up en/decryption
  1961. *
  1962. *
  1963. *
  1964. * The main reason why can speed up things [up to 50%] this way are:
  1965. *
  1966. * - using variables more effective then regular.
  1967. * (ie no use of expensive arrays but integers $k_0, $k_1 ...
  1968. * or even, for example, the pure $key[] values hardcoded)
  1969. *
  1970. * - avoiding 1000's of function calls of ie _encryptBlock()
  1971. * but inlining the crypt operations.
  1972. * in the mode of operation for() loop.
  1973. *
  1974. * - full loop unroll the (sometimes key-dependent) rounds
  1975. * avoiding this way ++$i counters and runtime-if's etc...
  1976. *
  1977. * The basic code architectur of the generated $inline en/decrypt()
  1978. * lambda function, in pseudo php, is:
  1979. *
  1980. * <code>
  1981. * +----------------------------------------------------------------------------------------------+
  1982. * | callback $inline = create_function: |
  1983. * | lambda_function_0001_crypt_ECB($action, $text) |
  1984. * | { |
  1985. * | INSERT PHP CODE OF: |
  1986. * | $cipher_code['init_crypt']; // general init code. |
  1987. * | // ie: $sbox'es declarations used for |
  1988. * | // encrypt and decrypt'ing. |
  1989. * | |
  1990. * | switch ($action) { |
  1991. * | case 'encrypt': |
  1992. * | INSERT PHP CODE OF: |
  1993. * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
  1994. * | ie: specified $key or $box |
  1995. * | declarations for encrypt'ing. |
  1996. * | |
  1997. * | foreach ($ciphertext) { |
  1998. * | $in = $block_size of $ciphertext; |
  1999. * | |
  2000. * | INSERT PHP CODE OF: |
  2001. * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
  2002. * | // strlen($in) == $this->block_size |
  2003. * | // here comes the cipher algorithm in action |
  2004. * | // for encryption. |
  2005. * | // $cipher_code['encrypt_block'] has to |
  2006. * | // encrypt the content of the $in variable |
  2007. * | |
  2008. * | $plaintext .= $in; |
  2009. * | } |
  2010. * | return $plaintext; |
  2011. * | |
  2012. * | case 'decrypt': |
  2013. * | INSERT PHP CODE OF: |
  2014. * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
  2015. * | ie: specified $key or $box |
  2016. * | declarations for decrypt'ing. |
  2017. * | foreach ($plaintext) { |
  2018. * | $in = $block_size of $plaintext; |
  2019. * | |
  2020. * | INSERT PHP CODE OF: |
  2021. * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
  2022. * | // strlen($in) == $this->block_size |
  2023. * | // here comes the cipher algorithm in action |
  2024. * | // for decryption. |
  2025. * | // $cipher_code['decrypt_block'] has to |
  2026. * | // decrypt the content of the $in variable |
  2027. * | $ciphertext .= $in; |
  2028. * | } |
  2029. * | return $ciphertext; |
  2030. * | } |
  2031. * | } |
  2032. * +----------------------------------------------------------------------------------------------+
  2033. * </code>
  2034. *
  2035. * See also the Crypt_*::_setupInlineCrypt()'s for
  2036. * productive inline $cipher_code's how they works.
  2037. *
  2038. * Structure of:
  2039. * <code>
  2040. * $cipher_code = array(
  2041. * 'init_crypt' => (string) '', // optional
  2042. * 'init_encrypt' => (string) '', // optional
  2043. * 'init_decrypt' => (string) '', // optional
  2044. * 'encrypt_block' => (string) '', // required
  2045. * 'decrypt_block' => (string) '' // required
  2046. * );
  2047. * </code>
  2048. *
  2049. * @see self::_setupInlineCrypt()
  2050. * @see self::encrypt()
  2051. * @see self::decrypt()
  2052. * @param array $cipher_code
  2053. * @access private
  2054. * @return string (the name of the created callback function)
  2055. */
  2056. function _createInlineCryptFunction($cipher_code)
  2057. {
  2058. $block_size = $this->block_size;
  2059. // optional
  2060. $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
  2061. $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
  2062. $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
  2063. // required
  2064. $encrypt_block = $cipher_code['encrypt_block'];
  2065. $decrypt_block = $cipher_code['decrypt_block'];
  2066. // Generating mode of operation inline code,
  2067. // merged with the $cipher_code algorithm
  2068. // for encrypt- and decryption.
  2069. switch ($this->mode) {
  2070. case CRYPT_MODE_ECB:
  2071. $encrypt = $init_encrypt . '
  2072. $_ciphertext = "";
  2073. $_plaintext_len = strlen($_text);
  2074. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2075. $in = substr($_text, $_i, '.$block_size.');
  2076. '.$encrypt_block.'
  2077. $_ciphertext.= $in;
  2078. }
  2079. return $_ciphertext;
  2080. ';
  2081. $decrypt = $init_decrypt . '
  2082. $_plaintext = "";
  2083. $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
  2084. $_ciphertext_len = strlen($_text);
  2085. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2086. $in = substr($_text, $_i, '.$block_size.');
  2087. '.$decrypt_block.'
  2088. $_plaintext.= $in;
  2089. }
  2090. return $self->_unpad($_plaintext);
  2091. ';
  2092. break;
  2093. case CRYPT_MODE_CTR:
  2094. $encrypt = $init_encrypt . '
  2095. $_ciphertext = "";
  2096. $_plaintext_len = strlen($_text);
  2097. $_xor = $self->encryptIV;
  2098. $_buffer = &$self->enbuffer;
  2099. if (strlen($_buffer["ciphertext"])) {
  2100. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2101. $_block = substr($_text, $_i, '.$block_size.');
  2102. if (strlen($_block) > strlen($_buffer["ciphertext"])) {
  2103. $in = $_xor;
  2104. '.$encrypt_block.'
  2105. $self->_increment_str($_xor);
  2106. $_buffer["ciphertext"].= $in;
  2107. }
  2108. $_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.');
  2109. $_ciphertext.= $_block ^ $_key;
  2110. }
  2111. } else {
  2112. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2113. $_block = substr($_text, $_i, '.$block_size.');
  2114. $in = $_xor;
  2115. '.$encrypt_block.'
  2116. $self->_increment_str($_xor);
  2117. $_key = $in;
  2118. $_ciphertext.= $_block ^ $_key;
  2119. }
  2120. }
  2121. if ($self->continuousBuffer) {
  2122. $self->encryptIV = $_xor;
  2123. if ($_start = $_plaintext_len % '.$block_size.') {
  2124. $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
  2125. }
  2126. }
  2127. return $_ciphertext;
  2128. ';
  2129. $decrypt = $init_encrypt . '
  2130. $_plaintext = "";
  2131. $_ciphertext_len = strlen($_text);
  2132. $_xor = $self->decryptIV;
  2133. $_buffer = &$self->debuffer;
  2134. if (strlen($_buffer["ciphertext"])) {
  2135. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2136. $_block = substr($_text, $_i, '.$block_size.');
  2137. if (strlen($_block) > strlen($_buffer["ciphertext"])) {
  2138. $in = $_xor;
  2139. '.$encrypt_block.'
  2140. $self->_increment_str($_xor);
  2141. $_buffer["ciphertext"].= $in;
  2142. }
  2143. $_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.');
  2144. $_plaintext.= $_block ^ $_key;
  2145. }
  2146. } else {
  2147. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2148. $_block = substr($_text, $_i, '.$block_size.');
  2149. $in = $_xor;
  2150. '.$encrypt_block.'
  2151. $self->_increment_str($_xor);
  2152. $_key = $in;
  2153. $_plaintext.= $_block ^ $_key;
  2154. }
  2155. }
  2156. if ($self->continuousBuffer) {
  2157. $self->decryptIV = $_xor;
  2158. if ($_start = $_ciphertext_len % '.$block_size.') {
  2159. $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
  2160. }
  2161. }
  2162. return $_plaintext;
  2163. ';
  2164. break;
  2165. case CRYPT_MODE_CFB:
  2166. $encrypt = $init_encrypt . '
  2167. $_ciphertext = "";
  2168. $_buffer = &$self->enbuffer;
  2169. if ($self->continuousBuffer) {
  2170. $_iv = &$self->encryptIV;
  2171. $_pos = &$_buffer["pos"];
  2172. } else {
  2173. $_iv = $self->encryptIV;
  2174. $_pos = 0;
  2175. }
  2176. $_len = strlen($_text);
  2177. $_i = 0;
  2178. if ($_pos) {
  2179. $_orig_pos = $_pos;
  2180. $_max = '.$block_size.' - $_pos;
  2181. if ($_len >= $_max) {
  2182. $_i = $_max;
  2183. $_len-= $_max;
  2184. $_pos = 0;
  2185. } else {
  2186. $_i = $_len;
  2187. $_pos+= $_len;
  2188. $_len = 0;
  2189. }
  2190. $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
  2191. $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
  2192. }
  2193. while ($_len >= '.$block_size.') {
  2194. $in = $_iv;
  2195. '.$encrypt_block.';
  2196. $_iv = $in ^ substr($_text, $_i, '.$block_size.');
  2197. $_ciphertext.= $_iv;
  2198. $_len-= '.$block_size.';
  2199. $_i+= '.$block_size.';
  2200. }
  2201. if ($_len) {
  2202. $in = $_iv;
  2203. '.$encrypt_block.'
  2204. $_iv = $in;
  2205. $_block = $_iv ^ substr($_text, $_i);
  2206. $_iv = substr_replace($_iv, $_block, 0, $_len);
  2207. $_ciphertext.= $_block;
  2208. $_pos = $_len;
  2209. }
  2210. return $_ciphertext;
  2211. ';
  2212. $decrypt = $init_encrypt . '
  2213. $_plaintext = "";
  2214. $_buffer = &$self->debuffer;
  2215. if ($self->continuousBuffer) {
  2216. $_iv = &$self->decryptIV;
  2217. $_pos = &$_buffer["pos"];
  2218. } else {
  2219. $_iv = $self->decryptIV;
  2220. $_pos = 0;
  2221. }
  2222. $_len = strlen($_text);
  2223. $_i = 0;
  2224. if ($_pos) {
  2225. $_orig_pos = $_pos;
  2226. $_max = '.$block_size.' - $_pos;
  2227. if ($_len >= $_max) {
  2228. $_i = $_max;
  2229. $_len-= $_max;
  2230. $_pos = 0;
  2231. } else {
  2232. $_i = $_len;
  2233. $_pos+= $_len;
  2234. $_len = 0;
  2235. }
  2236. $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
  2237. $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
  2238. }
  2239. while ($_len >= '.$block_size.') {
  2240. $in = $_iv;
  2241. '.$encrypt_block.'
  2242. $_iv = $in;
  2243. $cb = substr($_text, $_i, '.$block_size.');
  2244. $_plaintext.= $_iv ^ $cb;
  2245. $_iv = $cb;
  2246. $_len-= '.$block_size.';
  2247. $_i+= '.$block_size.';
  2248. }
  2249. if ($_len) {
  2250. $in = $_iv;
  2251. '.$encrypt_block.'
  2252. $_iv = $in;
  2253. $_plaintext.= $_iv ^ substr($_text, $_i);
  2254. $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
  2255. $_pos = $_len;
  2256. }
  2257. return $_plaintext;
  2258. ';
  2259. break;
  2260. case CRYPT_MODE_OFB:
  2261. $encrypt = $init_encrypt . '
  2262. $_ciphertext = "";
  2263. $_plaintext_len = strlen($_text);
  2264. $_xor = $self->encryptIV;
  2265. $_buffer = &$self->enbuffer;
  2266. if (strlen($_buffer["xor"])) {
  2267. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2268. $_block = substr($_text, $_i, '.$block_size.');
  2269. if (strlen($_block) > strlen($_buffer["xor"])) {
  2270. $in = $_xor;
  2271. '.$encrypt_block.'
  2272. $_xor = $in;
  2273. $_buffer["xor"].= $_xor;
  2274. }
  2275. $_key = $self->_string_shift($_buffer["xor"], '.$block_size.');
  2276. $_ciphertext.= $_block ^ $_key;
  2277. }
  2278. } else {
  2279. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2280. $in = $_xor;
  2281. '.$encrypt_block.'
  2282. $_xor = $in;
  2283. $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
  2284. }
  2285. $_key = $_xor;
  2286. }
  2287. if ($self->continuousBuffer) {
  2288. $self->encryptIV = $_xor;
  2289. if ($_start = $_plaintext_len % '.$block_size.') {
  2290. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  2291. }
  2292. }
  2293. return $_ciphertext;
  2294. ';
  2295. $decrypt = $init_encrypt . '
  2296. $_plaintext = "";
  2297. $_ciphertext_len = strlen($_text);
  2298. $_xor = $self->decryptIV;
  2299. $_buffer = &$self->debuffer;
  2300. if (strlen($_buffer["xor"])) {
  2301. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2302. $_block = substr($_text, $_i, '.$block_size.');
  2303. if (strlen($_block) > strlen($_buffer["xor"])) {
  2304. $in = $_xor;
  2305. '.$encrypt_block.'
  2306. $_xor = $in;
  2307. $_buffer["xor"].= $_xor;
  2308. }
  2309. $_key = $self->_string_shift($_buffer["xor"], '.$block_size.');
  2310. $_plaintext.= $_block ^ $_key;
  2311. }
  2312. } else {
  2313. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2314. $in = $_xor;
  2315. '.$encrypt_block.'
  2316. $_xor = $in;
  2317. $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
  2318. }
  2319. $_key = $_xor;
  2320. }
  2321. if ($self->continuousBuffer) {
  2322. $self->decryptIV = $_xor;
  2323. if ($_start = $_ciphertext_len % '.$block_size.') {
  2324. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  2325. }
  2326. }
  2327. return $_plaintext;
  2328. ';
  2329. break;
  2330. case CRYPT_MODE_STREAM:
  2331. $encrypt = $init_encrypt . '
  2332. $_ciphertext = "";
  2333. '.$encrypt_block.'
  2334. return $_ciphertext;
  2335. ';
  2336. $decrypt = $init_decrypt . '
  2337. $_plaintext = "";
  2338. '.$decrypt_block.'
  2339. return $_plaintext;
  2340. ';
  2341. break;
  2342. // case CRYPT_MODE_CBC:
  2343. default:
  2344. $encrypt = $init_encrypt . '
  2345. $_ciphertext = "";
  2346. $_plaintext_len = strlen($_text);
  2347. $in = $self->encryptIV;
  2348. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  2349. $in = substr($_text, $_i, '.$block_size.') ^ $in;
  2350. '.$encrypt_block.'
  2351. $_ciphertext.= $in;
  2352. }
  2353. if ($self->continuousBuffer) {
  2354. $self->encryptIV = $in;
  2355. }
  2356. return $_ciphertext;
  2357. ';
  2358. $decrypt = $init_decrypt . '
  2359. $_plaintext = "";
  2360. $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
  2361. $_ciphertext_len = strlen($_text);
  2362. $_iv = $self->decryptIV;
  2363. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  2364. $in = $_block = substr($_text, $_i, '.$block_size.');
  2365. '.$decrypt_block.'
  2366. $_plaintext.= $in ^ $_iv;
  2367. $_iv = $_block;
  2368. }
  2369. if ($self->continuousBuffer) {
  2370. $self->decryptIV = $_iv;
  2371. }
  2372. return $self->_unpad($_plaintext);
  2373. ';
  2374. break;
  2375. }
  2376. // Create the $inline function and return its name as string. Ready to run!
  2377. if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
  2378. eval('$func = function ($_action, &$self, $_text) { ' . $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' } };');
  2379. return $func;
  2380. }
  2381. return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
  2382. }
  2383. /**
  2384. * Holds the lambda_functions table (classwide)
  2385. *
  2386. * Each name of the lambda function, created from
  2387. * _setupInlineCrypt() && _createInlineCryptFunction()
  2388. * is stored, classwide (!), here for reusing.
  2389. *
  2390. * The string-based index of $function is a classwide
  2391. * unique value representing, at least, the $mode of
  2392. * operation (or more... depends of the optimizing level)
  2393. * for which $mode the lambda function was created.
  2394. *
  2395. * @access private
  2396. * @return array &$functions
  2397. */
  2398. function &_getLambdaFunctions()
  2399. {
  2400. static $functions = array();
  2401. return $functions;
  2402. }
  2403. /**
  2404. * Generates a digest from $bytes
  2405. *
  2406. * @see self::_setupInlineCrypt()
  2407. * @access private
  2408. * @param $bytes
  2409. * @return string
  2410. */
  2411. function _hashInlineCryptFunction($bytes)
  2412. {
  2413. if (!defined('CRYPT_BASE_WHIRLPOOL_AVAILABLE')) {
  2414. define('CRYPT_BASE_WHIRLPOOL_AVAILABLE', (bool)(extension_loaded('hash') && in_array('whirlpool', hash_algos())));
  2415. }
  2416. $result = '';
  2417. $hash = $bytes;
  2418. switch (true) {
  2419. case CRYPT_BASE_WHIRLPOOL_AVAILABLE:
  2420. foreach (str_split($bytes, 64) as $t) {
  2421. $hash = hash('whirlpool', $hash, true);
  2422. $result .= $t ^ $hash;
  2423. }
  2424. return $result . hash('whirlpool', $hash, true);
  2425. default:
  2426. $len = strlen($bytes);
  2427. for ($i = 0; $i < $len; $i+=20) {
  2428. $t = substr($bytes, $i, 20);
  2429. $hash = pack('H*', sha1($hash));
  2430. $result .= $t ^ $hash;
  2431. }
  2432. return $result . pack('H*', sha1($hash));
  2433. }
  2434. }
  2435. /**
  2436. * Convert float to int
  2437. *
  2438. * On 32-bit Linux installs running PHP < 5.3 converting floats to ints doesn't always work
  2439. *
  2440. * @access private
  2441. * @param string $x
  2442. * @return int
  2443. */
  2444. function safe_intval($x)
  2445. {
  2446. switch (true) {
  2447. case is_int($x):
  2448. // PHP 5.3, per http://php.net/releases/5_3_0.php, introduced "more consistent float rounding"
  2449. case version_compare(PHP_VERSION, '5.3.0') >= 0 && (php_uname('m') & "\xDF\xDF\xDF") != 'ARM':
  2450. // PHP_OS & "\xDF\xDF\xDF" == strtoupper(substr(PHP_OS, 0, 3)), but a lot faster
  2451. case (PHP_OS & "\xDF\xDF\xDF") === 'WIN':
  2452. return $x;
  2453. }
  2454. return (fmod($x, 0x80000000) & 0x7FFFFFFF) |
  2455. ((fmod(floor($x / 0x80000000), 2) & 1) << 31);
  2456. }
  2457. /**
  2458. * eval()'able string for in-line float to int
  2459. *
  2460. * @access private
  2461. * @return string
  2462. */
  2463. function safe_intval_inline()
  2464. {
  2465. // on 32-bit linux systems with PHP < 5.3 float to integer conversion is bad
  2466. switch (true) {
  2467. case defined('PHP_INT_SIZE') && PHP_INT_SIZE == 8:
  2468. case version_compare(PHP_VERSION, '5.3.0') >= 0 && (php_uname('m') & "\xDF\xDF\xDF") != 'ARM':
  2469. case (PHP_OS & "\xDF\xDF\xDF") === 'WIN':
  2470. return '%s';
  2471. break;
  2472. default:
  2473. $safeint = '(is_int($temp = %s) ? $temp : (fmod($temp, 0x80000000) & 0x7FFFFFFF) | ';
  2474. return $safeint . '((fmod(floor($temp / 0x80000000), 2) & 1) << 31))';
  2475. }
  2476. }
  2477. }