Base.php 96 KB

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