Base.php 94 KB

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