Base.php 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Base Class for all Crypt_* cipher classes
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * Internally for phpseclib developers:
  9. * If you plan to add a new cipher class, please note following rules:
  10. *
  11. * - The new Crypt_* cipher class should extend Crypt_Base
  12. *
  13. * - Following methods are then required to be overridden/overloaded:
  14. *
  15. * - _encryptBlock()
  16. *
  17. * - _decryptBlock()
  18. *
  19. * - _setupKey()
  20. *
  21. * - All other methods are optional to be overridden/overloaded
  22. *
  23. * - Look at the source code of the current ciphers how they extend Crypt_Base
  24. * and take one of them as a start up for the new cipher class.
  25. *
  26. * - Please read all the other comments/notes/hints here also for each class var/method
  27. *
  28. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  29. * of this software and associated documentation files (the "Software"), to deal
  30. * in the Software without restriction, including without limitation the rights
  31. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  32. * copies of the Software, and to permit persons to whom the Software is
  33. * furnished to do so, subject to the following conditions:
  34. *
  35. * The above copyright notice and this permission notice shall be included in
  36. * all copies or substantial portions of the Software.
  37. *
  38. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  39. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  40. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  41. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  42. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  43. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  44. * THE SOFTWARE.
  45. *
  46. * @category Crypt
  47. * @package Crypt_Base
  48. * @author Jim Wigginton <terrafrost@php.net>
  49. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  50. * @copyright MMVII Jim Wigginton
  51. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  52. * @version 1.0.1
  53. * @link http://phpseclib.sourceforge.net
  54. */
  55. /**#@+
  56. * @access public
  57. * @see Crypt_Base::encrypt()
  58. * @see Crypt_Base::decrypt()
  59. */
  60. /**
  61. * Encrypt / decrypt using the Counter mode.
  62. *
  63. * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
  64. *
  65. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
  66. */
  67. define('CRYPT_MODE_CTR', -1);
  68. /**
  69. * Encrypt / decrypt using the Electronic Code Book mode.
  70. *
  71. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
  72. */
  73. define('CRYPT_MODE_ECB', 1);
  74. /**
  75. * Encrypt / decrypt using the Code Book Chaining mode.
  76. *
  77. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
  78. */
  79. define('CRYPT_MODE_CBC', 2);
  80. /**
  81. * Encrypt / decrypt using the Cipher Feedback mode.
  82. *
  83. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
  84. */
  85. define('CRYPT_MODE_CFB', 3);
  86. /**
  87. * Encrypt / decrypt using the Output Feedback mode.
  88. *
  89. * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
  90. */
  91. define('CRYPT_MODE_OFB', 4);
  92. /**
  93. * Encrypt / decrypt using streaming mode.
  94. *
  95. */
  96. define('CRYPT_MODE_STREAM', 5);
  97. /**#@-*/
  98. /**#@+
  99. * @access private
  100. * @see Crypt_Base::Crypt_Base()
  101. */
  102. /**
  103. * Base value for the internal implementation $engine switch
  104. */
  105. define('CRYPT_MODE_INTERNAL', 1);
  106. /**
  107. * Base value for the mcrypt implementation $engine switch
  108. */
  109. define('CRYPT_MODE_MCRYPT', 2);
  110. /**#@-*/
  111. /**
  112. * Base Class for all Crypt_* cipher classes
  113. *
  114. * @author Jim Wigginton <terrafrost@php.net>
  115. * @author Hans-Juergen Petrich <petrich@tronic-media.com>
  116. * @version 1.0.0
  117. * @access public
  118. * @package Crypt_Base
  119. */
  120. class Crypt_Base {
  121. /**
  122. * The Encryption Mode
  123. *
  124. * @see Crypt_Base::Crypt_Base()
  125. * @var Integer
  126. * @access private
  127. */
  128. var $mode;
  129. /**
  130. * The Block Length of the block cipher
  131. *
  132. * @var Integer
  133. * @access private
  134. */
  135. var $block_size = 16;
  136. /**
  137. * The Key
  138. *
  139. * @see Crypt_Base::setKey()
  140. * @var String
  141. * @access private
  142. */
  143. var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  144. /**
  145. * The Initialization Vector
  146. *
  147. * @see Crypt_Base::setIV()
  148. * @var String
  149. * @access private
  150. */
  151. var $iv;
  152. /**
  153. * A "sliding" Initialization Vector
  154. *
  155. * @see Crypt_Base::enableContinuousBuffer()
  156. * @see Crypt_Base::_clearBuffers()
  157. * @var String
  158. * @access private
  159. */
  160. var $encryptIV;
  161. /**
  162. * A "sliding" Initialization Vector
  163. *
  164. * @see Crypt_Base::enableContinuousBuffer()
  165. * @see Crypt_Base::_clearBuffers()
  166. * @var String
  167. * @access private
  168. */
  169. var $decryptIV;
  170. /**
  171. * Continuous Buffer status
  172. *
  173. * @see Crypt_Base::enableContinuousBuffer()
  174. * @var Boolean
  175. * @access private
  176. */
  177. var $continuousBuffer = false;
  178. /**
  179. * Encryption buffer for CTR, OFB and CFB modes
  180. *
  181. * @see Crypt_Base::encrypt()
  182. * @see Crypt_Base::_clearBuffers()
  183. * @var Array
  184. * @access private
  185. */
  186. var $enbuffer;
  187. /**
  188. * Decryption buffer for CTR, OFB and CFB modes
  189. *
  190. * @see Crypt_Base::decrypt()
  191. * @see Crypt_Base::_clearBuffers()
  192. * @var Array
  193. * @access private
  194. */
  195. var $debuffer;
  196. /**
  197. * mcrypt resource for encryption
  198. *
  199. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  200. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  201. *
  202. * @see Crypt_Base::encrypt()
  203. * @var Resource
  204. * @access private
  205. */
  206. var $enmcrypt;
  207. /**
  208. * mcrypt resource for decryption
  209. *
  210. * The mcrypt resource can be recreated every time something needs to be created or it can be created just once.
  211. * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode.
  212. *
  213. * @see Crypt_Base::decrypt()
  214. * @var Resource
  215. * @access private
  216. */
  217. var $demcrypt;
  218. /**
  219. * Does the enmcrypt resource need to be (re)initialized?
  220. *
  221. * @see Crypt_Twofish::setKey()
  222. * @see Crypt_Twofish::setIV()
  223. * @var Boolean
  224. * @access private
  225. */
  226. var $enchanged = true;
  227. /**
  228. * Does the demcrypt resource need to be (re)initialized?
  229. *
  230. * @see Crypt_Twofish::setKey()
  231. * @see Crypt_Twofish::setIV()
  232. * @var Boolean
  233. * @access private
  234. */
  235. var $dechanged = true;
  236. /**
  237. * mcrypt resource for CFB mode
  238. *
  239. * mcrypt's CFB mode, in (and only in) buffered context,
  240. * is broken, so phpseclib implements the CFB mode by it self,
  241. * even when the mcrypt php extension is available.
  242. *
  243. * In order to do the CFB-mode work (fast) phpseclib
  244. * use a separate ECB-mode mcrypt resource.
  245. *
  246. * @link http://phpseclib.sourceforge.net/cfb-demo.phps
  247. * @see Crypt_Base::encrypt()
  248. * @see Crypt_Base::decrypt()
  249. * @see Crypt_Base::_setupMcrypt()
  250. * @var Resource
  251. * @access private
  252. */
  253. var $ecb;
  254. /**
  255. * Optimizing value while CFB-encrypting
  256. *
  257. * Only relevant if $continuousBuffer enabled
  258. * and $engine == CRYPT_MODE_MCRYPT
  259. *
  260. * It's faster to re-init $enmcrypt if
  261. * $buffer bytes > $cfb_init_len than
  262. * using the $ecb resource furthermore.
  263. *
  264. * This value depends of the choosen cipher
  265. * and the time it would be needed for it's
  266. * initialization [by mcrypt_generic_init()]
  267. * which, typically, depends on the complexity
  268. * on its internaly Key-expanding algorithm.
  269. *
  270. * @see Crypt_Base::encrypt()
  271. * @var Integer
  272. * @access private
  273. */
  274. var $cfb_init_len = 600;
  275. /**
  276. * Does internal cipher state need to be (re)initialized?
  277. *
  278. * @see setKey()
  279. * @see setIV()
  280. * @see disableContinuousBuffer()
  281. * @var Boolean
  282. * @access private
  283. */
  284. var $changed = true;
  285. /**
  286. * Padding status
  287. *
  288. * @see Crypt_Base::enablePadding()
  289. * @var Boolean
  290. * @access private
  291. */
  292. var $padding = true;
  293. /**
  294. * Is the mode one that is paddable?
  295. *
  296. * @see Crypt_Base::Crypt_Base()
  297. * @var Boolean
  298. * @access private
  299. */
  300. var $paddable = false;
  301. /**
  302. * Holds which crypt engine internaly should be use,
  303. * which will be determined automatically on __construct()
  304. *
  305. * Currently available $engines are:
  306. * - CRYPT_MODE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required)
  307. * - CRYPT_MODE_INTERNAL (slower, pure php-engine, no php-extension required)
  308. *
  309. * In the pipeline... maybe. But currently not available:
  310. * - CRYPT_MODE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required)
  311. *
  312. * If possible, CRYPT_MODE_MCRYPT will be used for each cipher.
  313. * Otherwise CRYPT_MODE_INTERNAL
  314. *
  315. * @see Crypt_Base::encrypt()
  316. * @see Crypt_Base::decrypt()
  317. * @var Integer
  318. * @access private
  319. */
  320. var $engine;
  321. /**
  322. * The mcrypt specific name of the cipher
  323. *
  324. * Only used if $engine == CRYPT_MODE_MCRYPT
  325. *
  326. * @link http://www.php.net/mcrypt_module_open
  327. * @link http://www.php.net/mcrypt_list_algorithms
  328. * @see Crypt_Base::_setupMcrypt()
  329. * @var String
  330. * @access private
  331. */
  332. var $cipher_name_mcrypt;
  333. /**
  334. * The default password key_size used by setPassword()
  335. *
  336. * @see Crypt_Base::setPassword()
  337. * @var Integer
  338. * @access private
  339. */
  340. var $password_key_size = 32;
  341. /**
  342. * The default salt used by setPassword()
  343. *
  344. * @see Crypt_Base::setPassword()
  345. * @var String
  346. * @access private
  347. */
  348. var $password_default_salt = 'phpseclib/salt';
  349. /**
  350. * The namespace used by the cipher for its constants.
  351. *
  352. * ie: AES.php is using CRYPT_AES_MODE_* for its constants
  353. * so $const_namespace is AES
  354. *
  355. * DES.php is using CRYPT_DES_MODE_* for its constants
  356. * so $const_namespace is DES... and so on
  357. *
  358. * All CRYPT_<$const_namespace>_MODE_* are aliases of
  359. * the generic CRYPT_MODE_* constants, so both could be used
  360. * for each cipher.
  361. *
  362. * Example:
  363. * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode
  364. * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical
  365. *
  366. * @see Crypt_Base::Crypt_Base()
  367. * @var String
  368. * @access private
  369. */
  370. var $const_namespace;
  371. /**
  372. * The name of the performance-optimized callback function
  373. *
  374. * Used by encrypt() / decrypt()
  375. * only if $engine == CRYPT_MODE_INTERNAL
  376. *
  377. * @see Crypt_Base::encrypt()
  378. * @see Crypt_Base::decrypt()
  379. * @see Crypt_Base::_setupInlineCrypt()
  380. * @see Crypt_Base::$use_inline_crypt
  381. * @var Callback
  382. * @access private
  383. */
  384. var $inline_crypt;
  385. /**
  386. * Holds whether performance-optimized $inline_crypt() can/should be used.
  387. *
  388. * @see Crypt_Base::encrypt()
  389. * @see Crypt_Base::decrypt()
  390. * @see Crypt_Base::inline_crypt
  391. * @var mixed
  392. * @access private
  393. */
  394. var $use_inline_crypt;
  395. /**
  396. * Default Constructor.
  397. *
  398. * Determines whether or not the mcrypt extension should be used.
  399. *
  400. * $mode could be:
  401. *
  402. * - CRYPT_MODE_ECB
  403. *
  404. * - CRYPT_MODE_CBC
  405. *
  406. * - CRYPT_MODE_CTR
  407. *
  408. * - CRYPT_MODE_CFB
  409. *
  410. * - CRYPT_MODE_OFB
  411. *
  412. * (or the alias constants of the choosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...)
  413. *
  414. * If not explictly set, CRYPT_MODE_CBC will be used.
  415. *
  416. * @param optional Integer $mode
  417. * @access public
  418. */
  419. function Crypt_Base($mode = CRYPT_MODE_CBC)
  420. {
  421. $const_crypt_mode = 'CRYPT_' . $this->const_namespace . '_MODE';
  422. // Determining the availibility of mcrypt support for the cipher
  423. if (!defined($const_crypt_mode)) {
  424. switch (true) {
  425. case extension_loaded('mcrypt') && in_array($this->cipher_name_mcrypt, mcrypt_list_algorithms()):
  426. define($const_crypt_mode, CRYPT_MODE_MCRYPT);
  427. break;
  428. default:
  429. define($const_crypt_mode, CRYPT_MODE_INTERNAL);
  430. }
  431. }
  432. // Determining which internal $engine should be used.
  433. // The fastes possible first.
  434. switch (true) {
  435. case empty($this->cipher_name_mcrypt): // The cipher module has no mcrypt-engine support at all so we force CRYPT_MODE_INTERNAL
  436. $this->engine = CRYPT_MODE_INTERNAL;
  437. break;
  438. case constant($const_crypt_mode) == CRYPT_MODE_MCRYPT:
  439. $this->engine = CRYPT_MODE_MCRYPT;
  440. break;
  441. default:
  442. $this->engine = CRYPT_MODE_INTERNAL;
  443. }
  444. // $mode dependent settings
  445. switch ($mode) {
  446. case CRYPT_MODE_ECB:
  447. $this->paddable = true;
  448. $this->mode = $mode;
  449. break;
  450. case CRYPT_MODE_CTR:
  451. case CRYPT_MODE_CFB:
  452. case CRYPT_MODE_OFB:
  453. case CRYPT_MODE_STREAM:
  454. $this->mode = $mode;
  455. break;
  456. case CRYPT_MODE_CBC:
  457. default:
  458. $this->paddable = true;
  459. $this->mode = CRYPT_MODE_CBC;
  460. }
  461. // Determining whether inline crypting can be used by the cipher
  462. if ($this->use_inline_crypt !== false && function_exists('create_function')) {
  463. $this->use_inline_crypt = true;
  464. }
  465. }
  466. /**
  467. * Sets the initialization vector. (optional)
  468. *
  469. * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explictly set, it'll be assumed
  470. * to be all zero's.
  471. *
  472. * Note: Could, but not must, extend by the child Crypt_* class
  473. *
  474. * @access public
  475. * @param String $iv
  476. */
  477. function setIV($iv)
  478. {
  479. if ($this->mode == CRYPT_MODE_ECB) {
  480. return;
  481. }
  482. $this->iv = $iv;
  483. $this->changed = true;
  484. }
  485. /**
  486. * Sets the key.
  487. *
  488. * The min/max length(s) of the key depends on the cipher which is used.
  489. * If the key not fits the length(s) of the cipher it will paded with null bytes
  490. * up to the closest valid key length. If the key is more than max length,
  491. * we trim the excess bits.
  492. *
  493. * If the key is not explicitly set, it'll be assumed to be all null bytes.
  494. *
  495. * Note: Could, but not must, extend by the child Crypt_* class
  496. *
  497. * @access public
  498. * @param String $key
  499. */
  500. function setKey($key)
  501. {
  502. $this->key = $key;
  503. $this->changed = true;
  504. }
  505. /**
  506. * Sets the password.
  507. *
  508. * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows:
  509. * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2}:
  510. * $hash, $salt, $count, $dkLen
  511. *
  512. * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php
  513. *
  514. * Note: Could, but not must, extend by the child Crypt_* class
  515. *
  516. * @see Crypt/Hash.php
  517. * @param String $password
  518. * @param optional String $method
  519. * @access public
  520. */
  521. function setPassword($password, $method = 'pbkdf2')
  522. {
  523. $key = '';
  524. switch ($method) {
  525. default: // 'pbkdf2'
  526. $func_args = func_get_args();
  527. // Hash function
  528. $hash = isset($func_args[2]) ? $func_args[2] : 'sha1';
  529. // WPA and WPA2 use the SSID as the salt
  530. $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt;
  531. // RFC2898#section-4.2 uses 1,000 iterations by default
  532. // WPA and WPA2 use 4,096.
  533. $count = isset($func_args[4]) ? $func_args[4] : 1000;
  534. // Keylength
  535. $dkLen = isset($func_args[5]) ? $func_args[5] : $this->password_key_size;
  536. // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable
  537. switch (true) {
  538. case !function_exists('hash_pbkdf2'):
  539. case !function_exists('hash_algos'):
  540. case !in_array($hash, hash_algos()):
  541. if (!class_exists('Crypt_Hash')) {
  542. require_once('Crypt/Hash.php');
  543. }
  544. $i = 1;
  545. while (strlen($key) < $dkLen) {
  546. $hmac = new Crypt_Hash();
  547. $hmac->setHash($hash);
  548. $hmac->setKey($password);
  549. $f = $u = $hmac->hash($salt . pack('N', $i++));
  550. for ($j = 2; $j <= $count; ++$j) {
  551. $u = $hmac->hash($u);
  552. $f^= $u;
  553. }
  554. $key.= $f;
  555. }
  556. $key = substr($key, 0, $dkLen);
  557. break;
  558. default:
  559. $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true);
  560. }
  561. }
  562. $this->setKey($key);
  563. }
  564. /**
  565. * Encrypts a message.
  566. *
  567. * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher
  568. * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's
  569. * necessary are discussed in the following
  570. * URL:
  571. *
  572. * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html}
  573. *
  574. * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does.
  575. * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that
  576. * length.
  577. *
  578. * Note: Could, but not must, extend by the child Crypt_* class
  579. *
  580. * @see Crypt_Base::decrypt()
  581. * @access public
  582. * @param String $plaintext
  583. * @return String $cipertext
  584. */
  585. function encrypt($plaintext)
  586. {
  587. if ($this->engine == CRYPT_MODE_MCRYPT) {
  588. if ($this->changed) {
  589. $this->_setupMcrypt();
  590. $this->changed = false;
  591. }
  592. if ($this->enchanged) {
  593. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  594. $this->enchanged = false;
  595. }
  596. // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  597. // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's
  598. // rewritten CFB implementation the above outputs the same thing twice.
  599. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  600. $block_size = $this->block_size;
  601. $iv = &$this->encryptIV;
  602. $pos = &$this->enbuffer['pos'];
  603. $len = strlen($plaintext);
  604. $ciphertext = '';
  605. $i = 0;
  606. if ($pos) {
  607. $orig_pos = $pos;
  608. $max = $block_size - $pos;
  609. if ($len >= $max) {
  610. $i = $max;
  611. $len-= $max;
  612. $pos = 0;
  613. } else {
  614. $i = $len;
  615. $pos+= $len;
  616. $len = 0;
  617. }
  618. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  619. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  620. $this->enbuffer['enmcrypt_init'] = true;
  621. }
  622. if ($len >= $block_size) {
  623. if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) {
  624. if ($this->enbuffer['enmcrypt_init'] === true) {
  625. mcrypt_generic_init($this->enmcrypt, $this->key, $iv);
  626. $this->enbuffer['enmcrypt_init'] = false;
  627. }
  628. $ciphertext.= mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size));
  629. $iv = substr($ciphertext, -$block_size);
  630. $len%= $block_size;
  631. } else {
  632. while ($len >= $block_size) {
  633. $iv = mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size);
  634. $ciphertext.= $iv;
  635. $len-= $block_size;
  636. $i+= $block_size;
  637. }
  638. }
  639. }
  640. if ($len) {
  641. $iv = mcrypt_generic($this->ecb, $iv);
  642. $block = $iv ^ substr($plaintext, -$len);
  643. $iv = substr_replace($iv, $block, 0, $len);
  644. $ciphertext.= $block;
  645. $pos = $len;
  646. }
  647. return $ciphertext;
  648. }
  649. if ($this->paddable) {
  650. $plaintext = $this->_pad($plaintext);
  651. }
  652. $ciphertext = mcrypt_generic($this->enmcrypt, $plaintext);
  653. if (!$this->continuousBuffer) {
  654. mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV);
  655. }
  656. return $ciphertext;
  657. }
  658. if ($this->changed) {
  659. $this->_setup();
  660. $this->changed = false;
  661. }
  662. if ($this->use_inline_crypt) {
  663. $inline = $this->inline_crypt;
  664. return $inline('encrypt', $this, $plaintext);
  665. }
  666. if ($this->paddable) {
  667. $plaintext = $this->_pad($plaintext);
  668. }
  669. $buffer = &$this->enbuffer;
  670. $block_size = $this->block_size;
  671. $ciphertext = '';
  672. switch ($this->mode) {
  673. case CRYPT_MODE_ECB:
  674. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  675. $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size));
  676. }
  677. break;
  678. case CRYPT_MODE_CBC:
  679. $xor = $this->encryptIV;
  680. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  681. $block = substr($plaintext, $i, $block_size);
  682. $block = $this->_encryptBlock($block ^ $xor);
  683. $xor = $block;
  684. $ciphertext.= $block;
  685. }
  686. if ($this->continuousBuffer) {
  687. $this->encryptIV = $xor;
  688. }
  689. break;
  690. case CRYPT_MODE_CTR:
  691. $xor = $this->encryptIV;
  692. if (strlen($buffer['encrypted'])) {
  693. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  694. $block = substr($plaintext, $i, $block_size);
  695. if (strlen($block) > strlen($buffer['encrypted'])) {
  696. $buffer['encrypted'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  697. }
  698. $key = $this->_stringShift($buffer['encrypted'], $block_size);
  699. $ciphertext.= $block ^ $key;
  700. }
  701. } else {
  702. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  703. $block = substr($plaintext, $i, $block_size);
  704. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  705. $ciphertext.= $block ^ $key;
  706. }
  707. }
  708. if ($this->continuousBuffer) {
  709. $this->encryptIV = $xor;
  710. if ($start = strlen($plaintext) % $block_size) {
  711. $buffer['encrypted'] = substr($key, $start) . $buffer['encrypted'];
  712. }
  713. }
  714. break;
  715. case CRYPT_MODE_CFB:
  716. // cfb loosely routines inspired by openssl's:
  717. // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1}
  718. if ($this->continuousBuffer) {
  719. $iv = &$this->encryptIV;
  720. $pos = &$buffer['pos'];
  721. } else {
  722. $iv = $this->encryptIV;
  723. $pos = 0;
  724. }
  725. $len = strlen($plaintext);
  726. $i = 0;
  727. if ($pos) {
  728. $orig_pos = $pos;
  729. $max = $block_size - $pos;
  730. if ($len >= $max) {
  731. $i = $max;
  732. $len-= $max;
  733. $pos = 0;
  734. } else {
  735. $i = $len;
  736. $pos+= $len;
  737. $len = 0;
  738. }
  739. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  740. $ciphertext = substr($iv, $orig_pos) ^ $plaintext;
  741. $iv = substr_replace($iv, $ciphertext, $orig_pos, $i);
  742. }
  743. while ($len >= $block_size) {
  744. $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size);
  745. $ciphertext.= $iv;
  746. $len-= $block_size;
  747. $i+= $block_size;
  748. }
  749. if ($len) {
  750. $iv = $this->_encryptBlock($iv);
  751. $block = $iv ^ substr($plaintext, $i);
  752. $iv = substr_replace($iv, $block, 0, $len);
  753. $ciphertext.= $block;
  754. $pos = $len;
  755. }
  756. break;
  757. case CRYPT_MODE_OFB:
  758. $xor = $this->encryptIV;
  759. if (strlen($buffer['xor'])) {
  760. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  761. $block = substr($plaintext, $i, $block_size);
  762. if (strlen($block) > strlen($buffer['xor'])) {
  763. $xor = $this->_encryptBlock($xor);
  764. $buffer['xor'].= $xor;
  765. }
  766. $key = $this->_stringShift($buffer['xor'], $block_size);
  767. $ciphertext.= $block ^ $key;
  768. }
  769. } else {
  770. for ($i = 0; $i < strlen($plaintext); $i+=$block_size) {
  771. $xor = $this->_encryptBlock($xor);
  772. $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor;
  773. }
  774. $key = $xor;
  775. }
  776. if ($this->continuousBuffer) {
  777. $this->encryptIV = $xor;
  778. if ($start = strlen($plaintext) % $block_size) {
  779. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  780. }
  781. }
  782. break;
  783. case CRYPT_MODE_STREAM:
  784. $ciphertext = $this->_encryptBlock($plaintext);
  785. break;
  786. }
  787. return $ciphertext;
  788. }
  789. /**
  790. * Decrypts a message.
  791. *
  792. * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until
  793. * it is.
  794. *
  795. * Note: Could, but not must, extend by the child Crypt_* class
  796. *
  797. * @see Crypt_Base::encrypt()
  798. * @access public
  799. * @param String $ciphertext
  800. * @return String $plaintext
  801. */
  802. function decrypt($ciphertext)
  803. {
  804. if ($this->engine == CRYPT_MODE_MCRYPT) {
  805. $block_size = $this->block_size;
  806. if ($this->changed) {
  807. $this->_setupMcrypt();
  808. $this->changed = false;
  809. }
  810. if ($this->dechanged) {
  811. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  812. $this->dechanged = false;
  813. }
  814. if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) {
  815. $iv = &$this->decryptIV;
  816. $pos = &$this->debuffer['pos'];
  817. $len = strlen($ciphertext);
  818. $plaintext = '';
  819. $i = 0;
  820. if ($pos) {
  821. $orig_pos = $pos;
  822. $max = $block_size - $pos;
  823. if ($len >= $max) {
  824. $i = $max;
  825. $len-= $max;
  826. $pos = 0;
  827. } else {
  828. $i = $len;
  829. $pos+= $len;
  830. $len = 0;
  831. }
  832. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  833. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  834. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  835. }
  836. if ($len >= $block_size) {
  837. $cb = substr($ciphertext, $i, $len - $len % $block_size);
  838. $plaintext.= mcrypt_generic($this->ecb, $iv . $cb) ^ $cb;
  839. $iv = substr($cb, -$block_size);
  840. $len%= $block_size;
  841. }
  842. if ($len) {
  843. $iv = mcrypt_generic($this->ecb, $iv);
  844. $plaintext.= $iv ^ substr($ciphertext, -$len);
  845. $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len);
  846. $pos = $len;
  847. }
  848. return $plaintext;
  849. }
  850. if ($this->paddable) {
  851. // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}:
  852. // "The data is padded with "\0" to make sure the length of the data is n * blocksize."
  853. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  854. }
  855. $plaintext = mdecrypt_generic($this->demcrypt, $ciphertext);
  856. if (!$this->continuousBuffer) {
  857. mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV);
  858. }
  859. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  860. }
  861. if ($this->changed) {
  862. $this->_setup();
  863. $this->changed = false;
  864. }
  865. if ($this->use_inline_crypt) {
  866. $inline = $this->inline_crypt;
  867. return $inline('decrypt', $this, $ciphertext);
  868. }
  869. $block_size = $this->block_size;
  870. if ($this->paddable) {
  871. // we pad with chr(0) since that's what mcrypt_generic does [...]
  872. $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($block_size - strlen($ciphertext) % $block_size) % $block_size, chr(0));
  873. }
  874. $buffer = &$this->debuffer;
  875. $plaintext = '';
  876. switch ($this->mode) {
  877. case CRYPT_MODE_ECB:
  878. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  879. $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size));
  880. }
  881. break;
  882. case CRYPT_MODE_CBC:
  883. $xor = $this->decryptIV;
  884. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  885. $block = substr($ciphertext, $i, $block_size);
  886. $plaintext.= $this->_decryptBlock($block) ^ $xor;
  887. $xor = $block;
  888. }
  889. if ($this->continuousBuffer) {
  890. $this->decryptIV = $xor;
  891. }
  892. break;
  893. case CRYPT_MODE_CTR:
  894. $xor = $this->decryptIV;
  895. if (strlen($buffer['ciphertext'])) {
  896. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  897. $block = substr($ciphertext, $i, $block_size);
  898. if (strlen($block) > strlen($buffer['ciphertext'])) {
  899. $buffer['ciphertext'].= $this->_encryptBlock($this->_generateXor($xor, $block_size));
  900. }
  901. $key = $this->_stringShift($buffer['ciphertext'], $block_size);
  902. $plaintext.= $block ^ $key;
  903. }
  904. } else {
  905. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  906. $block = substr($ciphertext, $i, $block_size);
  907. $key = $this->_encryptBlock($this->_generateXor($xor, $block_size));
  908. $plaintext.= $block ^ $key;
  909. }
  910. }
  911. if ($this->continuousBuffer) {
  912. $this->decryptIV = $xor;
  913. if ($start = strlen($ciphertext) % $block_size) {
  914. $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext'];
  915. }
  916. }
  917. break;
  918. case CRYPT_MODE_CFB:
  919. if ($this->continuousBuffer) {
  920. $iv = &$this->decryptIV;
  921. $pos = &$buffer['pos'];
  922. } else {
  923. $iv = $this->decryptIV;
  924. $pos = 0;
  925. }
  926. $len = strlen($ciphertext);
  927. $i = 0;
  928. if ($pos) {
  929. $orig_pos = $pos;
  930. $max = $block_size - $pos;
  931. if ($len >= $max) {
  932. $i = $max;
  933. $len-= $max;
  934. $pos = 0;
  935. } else {
  936. $i = $len;
  937. $pos+= $len;
  938. $len = 0;
  939. }
  940. // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize
  941. $plaintext = substr($iv, $orig_pos) ^ $ciphertext;
  942. $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i);
  943. }
  944. while ($len >= $block_size) {
  945. $iv = $this->_encryptBlock($iv);
  946. $cb = substr($ciphertext, $i, $block_size);
  947. $plaintext.= $iv ^ $cb;
  948. $iv = $cb;
  949. $len-= $block_size;
  950. $i+= $block_size;
  951. }
  952. if ($len) {
  953. $iv = $this->_encryptBlock($iv);
  954. $plaintext.= $iv ^ substr($ciphertext, $i);
  955. $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len);
  956. $pos = $len;
  957. }
  958. break;
  959. case CRYPT_MODE_OFB:
  960. $xor = $this->decryptIV;
  961. if (strlen($buffer['xor'])) {
  962. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  963. $block = substr($ciphertext, $i, $block_size);
  964. if (strlen($block) > strlen($buffer['xor'])) {
  965. $xor = $this->_encryptBlock($xor);
  966. $buffer['xor'].= $xor;
  967. }
  968. $key = $this->_stringShift($buffer['xor'], $block_size);
  969. $plaintext.= $block ^ $key;
  970. }
  971. } else {
  972. for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) {
  973. $xor = $this->_encryptBlock($xor);
  974. $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor;
  975. }
  976. $key = $xor;
  977. }
  978. if ($this->continuousBuffer) {
  979. $this->decryptIV = $xor;
  980. if ($start = strlen($ciphertext) % $block_size) {
  981. $buffer['xor'] = substr($key, $start) . $buffer['xor'];
  982. }
  983. }
  984. break;
  985. case CRYPT_MODE_STREAM:
  986. $plaintext = $this->_decryptBlock($ciphertext);
  987. break;
  988. }
  989. return $this->paddable ? $this->_unpad($plaintext) : $plaintext;
  990. }
  991. /**
  992. * Pad "packets".
  993. *
  994. * Block ciphers working by encrypting between their specified [$this->]block_size at a time
  995. * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to
  996. * pad the input so that it is of the proper length.
  997. *
  998. * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH,
  999. * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping
  1000. * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is
  1001. * transmitted separately)
  1002. *
  1003. * @see Crypt_Base::disablePadding()
  1004. * @access public
  1005. */
  1006. function enablePadding()
  1007. {
  1008. $this->padding = true;
  1009. }
  1010. /**
  1011. * Do not pad packets.
  1012. *
  1013. * @see Crypt_Base::enablePadding()
  1014. * @access public
  1015. */
  1016. function disablePadding()
  1017. {
  1018. $this->padding = false;
  1019. }
  1020. /**
  1021. * Treat consecutive "packets" as if they are a continuous buffer.
  1022. *
  1023. * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets
  1024. * will yield different outputs:
  1025. *
  1026. * <code>
  1027. * echo $rijndael->encrypt(substr($plaintext, 0, 16));
  1028. * echo $rijndael->encrypt(substr($plaintext, 16, 16));
  1029. * </code>
  1030. * <code>
  1031. * echo $rijndael->encrypt($plaintext);
  1032. * </code>
  1033. *
  1034. * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates
  1035. * another, as demonstrated with the following:
  1036. *
  1037. * <code>
  1038. * $rijndael->encrypt(substr($plaintext, 0, 16));
  1039. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1040. * </code>
  1041. * <code>
  1042. * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16)));
  1043. * </code>
  1044. *
  1045. * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different
  1046. * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
  1047. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
  1048. *
  1049. * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each
  1050. * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
  1051. * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
  1052. * however, they are also less intuitive and more likely to cause you problems.
  1053. *
  1054. * Note: Could, but not must, extend by the child Crypt_* class
  1055. *
  1056. * @see Crypt_Base::disableContinuousBuffer()
  1057. * @access public
  1058. */
  1059. function enableContinuousBuffer()
  1060. {
  1061. if ($this->mode == CRYPT_MODE_ECB) {
  1062. return;
  1063. }
  1064. $this->continuousBuffer = true;
  1065. }
  1066. /**
  1067. * Treat consecutive packets as if they are a discontinuous buffer.
  1068. *
  1069. * The default behavior.
  1070. *
  1071. * Note: Could, but not must, extend by the child Crypt_* class
  1072. *
  1073. * @see Crypt_Base::enableContinuousBuffer()
  1074. * @access public
  1075. */
  1076. function disableContinuousBuffer()
  1077. {
  1078. if ($this->mode == CRYPT_MODE_ECB) {
  1079. return;
  1080. }
  1081. if (!$this->continuousBuffer) {
  1082. return;
  1083. }
  1084. $this->continuousBuffer = false;
  1085. $this->changed = true;
  1086. }
  1087. /**
  1088. * Encrypts a block
  1089. *
  1090. * Note: Must extend by the child Crypt_* class
  1091. *
  1092. * @access private
  1093. * @param String $in
  1094. * @return String
  1095. */
  1096. function _encryptBlock($in)
  1097. {
  1098. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1099. }
  1100. /**
  1101. * Decrypts a block
  1102. *
  1103. * Note: Must extend by the child Crypt_* class
  1104. *
  1105. * @access private
  1106. * @param String $in
  1107. * @return String
  1108. */
  1109. function _decryptBlock($in)
  1110. {
  1111. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1112. }
  1113. /**
  1114. * Setup the key (expansion)
  1115. *
  1116. * Only used if $engine == CRYPT_MODE_INTERNAL
  1117. *
  1118. * Note: Must extend by the child Crypt_* class
  1119. *
  1120. * @see Crypt_Base::_setup()
  1121. * @access private
  1122. */
  1123. function _setupKey()
  1124. {
  1125. user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR);
  1126. }
  1127. /**
  1128. * Setup the CRYPT_MODE_INTERNAL $engine
  1129. *
  1130. * (re)init, if necessary, the internal cipher $engine and flush all $buffers
  1131. * Used (only) if $engine == CRYPT_MODE_INTERNAL
  1132. *
  1133. * _setup() will be called each time if $changed === true
  1134. * typically this happens when using one or more of following public methods:
  1135. *
  1136. * - setKey()
  1137. *
  1138. * - setIV()
  1139. *
  1140. * - disableContinuousBuffer()
  1141. *
  1142. * - First run of encrypt() / decrypt() with no init-settings
  1143. *
  1144. * Internally: _setup() is called always before(!) en/decryption.
  1145. *
  1146. * Note: Could, but not must, extend by the child Crypt_* class
  1147. *
  1148. * @see setKey()
  1149. * @see setIV()
  1150. * @see disableContinuousBuffer()
  1151. * @access private
  1152. */
  1153. function _setup()
  1154. {
  1155. $this->_clearBuffers();
  1156. $this->_setupKey();
  1157. if ($this->use_inline_crypt) {
  1158. $this->_setupInlineCrypt();
  1159. }
  1160. }
  1161. /**
  1162. * Setup the CRYPT_MODE_MCRYPT $engine
  1163. *
  1164. * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers
  1165. * Used (only) if $engine = CRYPT_MODE_MCRYPT
  1166. *
  1167. * _setupMcrypt() will be called each time if $changed === true
  1168. * typically this happens when using one or more of following public methods:
  1169. *
  1170. * - setKey()
  1171. *
  1172. * - setIV()
  1173. *
  1174. * - disableContinuousBuffer()
  1175. *
  1176. * - First run of encrypt() / decrypt()
  1177. *
  1178. *
  1179. * Note: Could, but not must, extend by the child Crypt_* class
  1180. *
  1181. * @see setKey()
  1182. * @see setIV()
  1183. * @see disableContinuousBuffer()
  1184. * @access private
  1185. */
  1186. function _setupMcrypt()
  1187. {
  1188. $this->_clearBuffers();
  1189. $this->enchanged = $this->dechanged = true;
  1190. if (!isset($this->enmcrypt)) {
  1191. static $mcrypt_modes = array(
  1192. CRYPT_MODE_CTR => 'ctr',
  1193. CRYPT_MODE_ECB => MCRYPT_MODE_ECB,
  1194. CRYPT_MODE_CBC => MCRYPT_MODE_CBC,
  1195. CRYPT_MODE_CFB => 'ncfb',
  1196. CRYPT_MODE_OFB => MCRYPT_MODE_NOFB,
  1197. CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM,
  1198. );
  1199. $this->demcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1200. $this->enmcrypt = mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], '');
  1201. // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer()
  1202. // to workaround mcrypt's broken ncfb implementation in buffered mode
  1203. // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps}
  1204. if ($this->mode == CRYPT_MODE_CFB) {
  1205. $this->ecb = mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, '');
  1206. }
  1207. } // else should mcrypt_generic_deinit be called?
  1208. if ($this->mode == CRYPT_MODE_CFB) {
  1209. mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size));
  1210. }
  1211. }
  1212. /**
  1213. * Pads a string
  1214. *
  1215. * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize.
  1216. * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to
  1217. * chr($this->block_size - (strlen($text) % $this->block_size)
  1218. *
  1219. * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless
  1220. * and padding will, hence forth, be enabled.
  1221. *
  1222. * @see Crypt_Base::_unpad()
  1223. * @param String $text
  1224. * @access private
  1225. * @return String
  1226. */
  1227. function _pad($text)
  1228. {
  1229. $length = strlen($text);
  1230. if (!$this->padding) {
  1231. if ($length % $this->block_size == 0) {
  1232. return $text;
  1233. } else {
  1234. user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})");
  1235. $this->padding = true;
  1236. }
  1237. }
  1238. $pad = $this->block_size - ($length % $this->block_size);
  1239. return str_pad($text, $length + $pad, chr($pad));
  1240. }
  1241. /**
  1242. * Unpads a string.
  1243. *
  1244. * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong
  1245. * and false will be returned.
  1246. *
  1247. * @see Crypt_Base::_pad()
  1248. * @param String $text
  1249. * @access private
  1250. * @return String
  1251. */
  1252. function _unpad($text)
  1253. {
  1254. if (!$this->padding) {
  1255. return $text;
  1256. }
  1257. $length = ord($text[strlen($text) - 1]);
  1258. if (!$length || $length > $this->block_size) {
  1259. return false;
  1260. }
  1261. return substr($text, 0, -$length);
  1262. }
  1263. /**
  1264. * Clears internal buffers
  1265. *
  1266. * Clearing/resetting the internal buffers is done everytime
  1267. * after disableContinuousBuffer() or on cipher $engine (re)init
  1268. * ie after setKey() or setIV()
  1269. *
  1270. * Note: Could, but not must, extend by the child Crypt_* class
  1271. *
  1272. * @access public
  1273. */
  1274. function _clearBuffers()
  1275. {
  1276. $this->enbuffer = array('encrypted' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true);
  1277. $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'demcrypt_init' => true);
  1278. // mcrypt's handling of invalid's $iv:
  1279. // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size);
  1280. $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0");
  1281. }
  1282. /**
  1283. * String Shift
  1284. *
  1285. * Inspired by array_shift
  1286. *
  1287. * @param String $string
  1288. * @param optional Integer $index
  1289. * @access private
  1290. * @return String
  1291. */
  1292. function _stringShift(&$string, $index = 1)
  1293. {
  1294. $substr = substr($string, 0, $index);
  1295. $string = substr($string, $index);
  1296. return $substr;
  1297. }
  1298. /**
  1299. * Generate CTR XOR encryption key
  1300. *
  1301. * Encrypt the output of this and XOR it against the ciphertext / plaintext to get the
  1302. * plaintext / ciphertext in CTR mode.
  1303. *
  1304. * @see Crypt_Base::decrypt()
  1305. * @see Crypt_Base::encrypt()
  1306. * @param String $iv
  1307. * @param Integer $length
  1308. * @access private
  1309. * @return String $xor
  1310. */
  1311. function _generateXor(&$iv, $length)
  1312. {
  1313. $xor = '';
  1314. $block_size = $this->block_size;
  1315. $num_blocks = floor(($length + ($block_size - 1)) / $block_size);
  1316. for ($i = 0; $i < $num_blocks; $i++) {
  1317. $xor.= $iv;
  1318. for ($j = 4; $j <= $block_size; $j+= 4) {
  1319. $temp = substr($iv, -$j, 4);
  1320. switch ($temp) {
  1321. case "\xFF\xFF\xFF\xFF":
  1322. $iv = substr_replace($iv, "\x00\x00\x00\x00", -$j, 4);
  1323. break;
  1324. case "\x7F\xFF\xFF\xFF":
  1325. $iv = substr_replace($iv, "\x80\x00\x00\x00", -$j, 4);
  1326. break 2;
  1327. default:
  1328. extract(unpack('Ncount', $temp));
  1329. $iv = substr_replace($iv, pack('N', $count + 1), -$j, 4);
  1330. break 2;
  1331. }
  1332. }
  1333. }
  1334. return $xor;
  1335. }
  1336. /**
  1337. * Setup the performance-optimized function for de/encrypt()
  1338. *
  1339. * Stores the created (or existing) callback function-name
  1340. * in $this->inline_crypt
  1341. *
  1342. * Internally for phpseclib developers:
  1343. *
  1344. * _setupInlineCrypt() would be called only if:
  1345. *
  1346. * - $engine == CRYPT_MODE_INTERNAL and
  1347. *
  1348. * - $use_inline_crypt === true
  1349. *
  1350. * - each time on _setup(), after(!) _setupKey()
  1351. *
  1352. *
  1353. * This ensures that _setupInlineCrypt() has allways a
  1354. * full ready2go initializated internal cipher $engine state
  1355. * where, for example, the keys allready expanded,
  1356. * keys/block_size calculated and such.
  1357. *
  1358. * It is, each time if called, the responsibility of _setupInlineCrypt():
  1359. *
  1360. * - to set $this->inline_crypt to a valid and fully working callback function
  1361. * as a (faster) replacement for encrypt() / decrypt()
  1362. *
  1363. * - NOT to create unlimited callback functions (for memory reasons!)
  1364. * no matter how often _setupInlineCrypt() would be called. At some
  1365. * point of amount they must be generic re-useable.
  1366. *
  1367. * - the code of _setupInlineCrypt() it self,
  1368. * and the generated callback code,
  1369. * must be, in following order:
  1370. * - 100% safe
  1371. * - 100% compatible to encrypt()/decrypt()
  1372. * - using only php5+ features/lang-constructs/php-extensions if
  1373. * compatibility (down to php4) or fallback is provided
  1374. * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-)
  1375. * - >= 10% faster than encrypt()/decrypt() [which is, by the way,
  1376. * the reason for the existence of _setupInlineCrypt() :-)]
  1377. * - memory-nice
  1378. * - short (as good as possible)
  1379. *
  1380. * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code.
  1381. * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class.
  1382. * - The following variable names are reserved:
  1383. * - $_* (all variable names prefixed with an underscore)
  1384. * - $self (object reference to it self. Do not use $this, but $self instead)
  1385. * - $in (the content of $in has to en/decrypt by the generated code)
  1386. * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only
  1387. *
  1388. *
  1389. * @see Crypt_Base::_setup()
  1390. * @see Crypt_Base::_createInlineCryptFunction()
  1391. * @see Crypt_Base::encrypt()
  1392. * @see Crypt_Base::decrypt()
  1393. * @access private
  1394. */
  1395. function _setupInlineCrypt()
  1396. {
  1397. // If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt()
  1398. // If, for any reason, an extending Crypt_Base() Crypt_* class
  1399. // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false
  1400. // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class,
  1401. // in the constructor at object instance-time
  1402. // or, if it's runtime-specific, at runtime
  1403. $this->use_inline_crypt = false;
  1404. }
  1405. /**
  1406. * Creates the performance-optimized function for en/decrypt()
  1407. *
  1408. * Internally for phpseclib developers:
  1409. *
  1410. * _createInlineCryptFunction():
  1411. *
  1412. * - merge the $cipher_code [setup'ed by _setupInlineCrypt()]
  1413. * with the current [$this->]mode of operation code
  1414. *
  1415. * - create the $inline function, which called by encrypt() / decrypt()
  1416. * as its replacement to speed up the en/decryption operations.
  1417. *
  1418. * - return the name of the created $inline callback function
  1419. *
  1420. * - used to speed up en/decryption
  1421. *
  1422. *
  1423. *
  1424. * The main reason why can speed up things [up to 50%] this way are:
  1425. *
  1426. * - using variables more effective then regular.
  1427. * (ie no use of expensive arrays but integers $k_0, $k_1 ...
  1428. * or even, for example, the pure $key[] values hardcoded)
  1429. *
  1430. * - avoiding 1000's of function calls of ie _encryptBlock()
  1431. * but inlining the crypt operations.
  1432. * in the mode of operation for() loop.
  1433. *
  1434. * - full loop unroll the (sometimes key-dependent) rounds
  1435. * avoiding this way ++$i counters and runtime-if's etc...
  1436. *
  1437. * The basic code architectur of the generated $inline en/decrypt()
  1438. * lambda function, in pseudo php, is:
  1439. *
  1440. * <code>
  1441. * +----------------------------------------------------------------------------------------------+
  1442. * | callback $inline = create_function: |
  1443. * | lambda_function_0001_crypt_ECB($action, $text) |
  1444. * | { |
  1445. * | INSERT PHP CODE OF: |
  1446. * | $cipher_code['init_crypt']; // general init code. |
  1447. * | // ie: $sbox'es declarations used for |
  1448. * | // encrypt and decrypt'ing. |
  1449. * | |
  1450. * | switch ($action) { |
  1451. * | case 'encrypt': |
  1452. * | INSERT PHP CODE OF: |
  1453. * | $cipher_code['init_encrypt']; // encrypt sepcific init code. |
  1454. * | ie: specified $key or $box |
  1455. * | declarations for encrypt'ing. |
  1456. * | |
  1457. * | foreach ($ciphertext) { |
  1458. * | $in = $block_size of $ciphertext; |
  1459. * | |
  1460. * | INSERT PHP CODE OF: |
  1461. * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: |
  1462. * | // strlen($in) == $this->block_size |
  1463. * | // here comes the cipher algorithm in action |
  1464. * | // for encryption. |
  1465. * | // $cipher_code['encrypt_block'] has to |
  1466. * | // encrypt the content of the $in variable |
  1467. * | |
  1468. * | $plaintext .= $in; |
  1469. * | } |
  1470. * | return $plaintext; |
  1471. * | |
  1472. * | case 'decrypt': |
  1473. * | INSERT PHP CODE OF: |
  1474. * | $cipher_code['init_decrypt']; // decrypt sepcific init code |
  1475. * | ie: specified $key or $box |
  1476. * | declarations for decrypt'ing. |
  1477. * | foreach ($plaintext) { |
  1478. * | $in = $block_size of $plaintext; |
  1479. * | |
  1480. * | INSERT PHP CODE OF: |
  1481. * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always |
  1482. * | // strlen($in) == $this->block_size |
  1483. * | // here comes the cipher algorithm in action |
  1484. * | // for decryption. |
  1485. * | // $cipher_code['decrypt_block'] has to |
  1486. * | // decrypt the content of the $in variable |
  1487. * | $ciphertext .= $in; |
  1488. * | } |
  1489. * | return $ciphertext; |
  1490. * | } |
  1491. * | } |
  1492. * +----------------------------------------------------------------------------------------------+
  1493. * </code>
  1494. *
  1495. * See also the Crypt_*::_setupInlineCrypt()'s for
  1496. * productive inline $cipher_code's how they works.
  1497. *
  1498. * Structure of:
  1499. * <code>
  1500. * $cipher_code = array(
  1501. * 'init_crypt' => (string) '', // optional
  1502. * 'init_encrypt' => (string) '', // optional
  1503. * 'init_decrypt' => (string) '', // optional
  1504. * 'encrypt_block' => (string) '', // required
  1505. * 'decrypt_block' => (string) '' // required
  1506. * );
  1507. * </code>
  1508. *
  1509. * @see Crypt_Base::_setupInlineCrypt()
  1510. * @see Crypt_Base::encrypt()
  1511. * @see Crypt_Base::decrypt()
  1512. * @param Array $cipher_code
  1513. * @access private
  1514. * @return String (the name of the created callback function)
  1515. */
  1516. function _createInlineCryptFunction($cipher_code)
  1517. {
  1518. $block_size = $this->block_size;
  1519. // optional
  1520. $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : '';
  1521. $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : '';
  1522. $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : '';
  1523. // required
  1524. $encrypt_block = $cipher_code['encrypt_block'];
  1525. $decrypt_block = $cipher_code['decrypt_block'];
  1526. // Generating mode of operation inline code,
  1527. // merged with the $cipher_code algorithm
  1528. // for encrypt- and decryption.
  1529. switch ($this->mode) {
  1530. case CRYPT_MODE_ECB:
  1531. $encrypt = $init_encrypt . '
  1532. $_ciphertext = "";
  1533. $_text = $self->_pad($_text);
  1534. $_plaintext_len = strlen($_text);
  1535. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1536. $in = substr($_text, $_i, '.$block_size.');
  1537. '.$encrypt_block.'
  1538. $_ciphertext.= $in;
  1539. }
  1540. return $_ciphertext;
  1541. ';
  1542. $decrypt = $init_decrypt . '
  1543. $_plaintext = "";
  1544. $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
  1545. $_ciphertext_len = strlen($_text);
  1546. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1547. $in = substr($_text, $_i, '.$block_size.');
  1548. '.$decrypt_block.'
  1549. $_plaintext.= $in;
  1550. }
  1551. return $self->_unpad($_plaintext);
  1552. ';
  1553. break;
  1554. case CRYPT_MODE_CTR:
  1555. $encrypt = $init_encrypt . '
  1556. $_ciphertext = "";
  1557. $_plaintext_len = strlen($_text);
  1558. $_xor = $self->encryptIV;
  1559. $_buffer = &$self->enbuffer;
  1560. if (strlen($_buffer["encrypted"])) {
  1561. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1562. $_block = substr($_text, $_i, '.$block_size.');
  1563. if (strlen($_block) > strlen($_buffer["encrypted"])) {
  1564. $in = $self->_generateXor($_xor, '.$block_size.');
  1565. '.$encrypt_block.'
  1566. $_buffer["encrypted"].= $in;
  1567. }
  1568. $_key = $self->_stringShift($_buffer["encrypted"], '.$block_size.');
  1569. $_ciphertext.= $_block ^ $_key;
  1570. }
  1571. } else {
  1572. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1573. $_block = substr($_text, $_i, '.$block_size.');
  1574. $in = $self->_generateXor($_xor, '.$block_size.');
  1575. '.$encrypt_block.'
  1576. $_key = $in;
  1577. $_ciphertext.= $_block ^ $_key;
  1578. }
  1579. }
  1580. if ($self->continuousBuffer) {
  1581. $self->encryptIV = $_xor;
  1582. if ($_start = $_plaintext_len % '.$block_size.') {
  1583. $_buffer["encrypted"] = substr($_key, $_start) . $_buffer["encrypted"];
  1584. }
  1585. }
  1586. return $_ciphertext;
  1587. ';
  1588. $decrypt = $init_encrypt . '
  1589. $_plaintext = "";
  1590. $_ciphertext_len = strlen($_text);
  1591. $_xor = $self->decryptIV;
  1592. $_buffer = &$self->debuffer;
  1593. if (strlen($_buffer["ciphertext"])) {
  1594. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1595. $_block = substr($_text, $_i, '.$block_size.');
  1596. if (strlen($_block) > strlen($_buffer["ciphertext"])) {
  1597. $in = $self->_generateXor($_xor, '.$block_size.');
  1598. '.$encrypt_block.'
  1599. $_buffer["ciphertext"].= $in;
  1600. }
  1601. $_key = $self->_stringShift($_buffer["ciphertext"], '.$block_size.');
  1602. $_plaintext.= $_block ^ $_key;
  1603. }
  1604. } else {
  1605. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1606. $_block = substr($_text, $_i, '.$block_size.');
  1607. $in = $self->_generateXor($_xor, '.$block_size.');
  1608. '.$encrypt_block.'
  1609. $_key = $in;
  1610. $_plaintext.= $_block ^ $_key;
  1611. }
  1612. }
  1613. if ($self->continuousBuffer) {
  1614. $self->decryptIV = $_xor;
  1615. if ($_start = $_ciphertext_len % '.$block_size.') {
  1616. $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"];
  1617. }
  1618. }
  1619. return $_plaintext;
  1620. ';
  1621. break;
  1622. case CRYPT_MODE_CFB:
  1623. $encrypt = $init_encrypt . '
  1624. $_ciphertext = "";
  1625. $_buffer = &$self->enbuffer;
  1626. if ($self->continuousBuffer) {
  1627. $_iv = &$self->encryptIV;
  1628. $_pos = &$_buffer["pos"];
  1629. } else {
  1630. $_iv = $self->encryptIV;
  1631. $_pos = 0;
  1632. }
  1633. $_len = strlen($_text);
  1634. $_i = 0;
  1635. if ($_pos) {
  1636. $_orig_pos = $_pos;
  1637. $_max = '.$block_size.' - $_pos;
  1638. if ($_len >= $_max) {
  1639. $_i = $_max;
  1640. $_len-= $_max;
  1641. $_pos = 0;
  1642. } else {
  1643. $_i = $_len;
  1644. $_pos+= $_len;
  1645. $_len = 0;
  1646. }
  1647. $_ciphertext = substr($_iv, $_orig_pos) ^ $_text;
  1648. $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i);
  1649. }
  1650. while ($_len >= '.$block_size.') {
  1651. $in = $_iv;
  1652. '.$encrypt_block.';
  1653. $_iv = $in ^ substr($_text, $_i, '.$block_size.');
  1654. $_ciphertext.= $_iv;
  1655. $_len-= '.$block_size.';
  1656. $_i+= '.$block_size.';
  1657. }
  1658. if ($_len) {
  1659. $in = $_iv;
  1660. '.$encrypt_block.'
  1661. $_iv = $in;
  1662. $_block = $_iv ^ substr($_text, $_i);
  1663. $_iv = substr_replace($_iv, $_block, 0, $_len);
  1664. $_ciphertext.= $_block;
  1665. $_pos = $_len;
  1666. }
  1667. return $_ciphertext;
  1668. ';
  1669. $decrypt = $init_encrypt . '
  1670. $_plaintext = "";
  1671. $_buffer = &$self->debuffer;
  1672. if ($self->continuousBuffer) {
  1673. $_iv = &$self->decryptIV;
  1674. $_pos = &$_buffer["pos"];
  1675. } else {
  1676. $_iv = $self->decryptIV;
  1677. $_pos = 0;
  1678. }
  1679. $_len = strlen($_text);
  1680. $_i = 0;
  1681. if ($_pos) {
  1682. $_orig_pos = $_pos;
  1683. $_max = '.$block_size.' - $_pos;
  1684. if ($_len >= $_max) {
  1685. $_i = $_max;
  1686. $_len-= $_max;
  1687. $_pos = 0;
  1688. } else {
  1689. $_i = $_len;
  1690. $_pos+= $_len;
  1691. $_len = 0;
  1692. }
  1693. $_plaintext = substr($_iv, $_orig_pos) ^ $_text;
  1694. $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i);
  1695. }
  1696. while ($_len >= '.$block_size.') {
  1697. $in = $_iv;
  1698. '.$encrypt_block.'
  1699. $_iv = $in;
  1700. $cb = substr($_text, $_i, '.$block_size.');
  1701. $_plaintext.= $_iv ^ $cb;
  1702. $_iv = $cb;
  1703. $_len-= '.$block_size.';
  1704. $_i+= '.$block_size.';
  1705. }
  1706. if ($_len) {
  1707. $in = $_iv;
  1708. '.$encrypt_block.'
  1709. $_iv = $in;
  1710. $_plaintext.= $_iv ^ substr($_text, $_i);
  1711. $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len);
  1712. $_pos = $_len;
  1713. }
  1714. return $_plaintext;
  1715. ';
  1716. break;
  1717. case CRYPT_MODE_OFB:
  1718. $encrypt = $init_encrypt . '
  1719. $_ciphertext = "";
  1720. $_plaintext_len = strlen($_text);
  1721. $_xor = $self->encryptIV;
  1722. $_buffer = &$self->enbuffer;
  1723. if (strlen($_buffer["xor"])) {
  1724. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1725. $_block = substr($_text, $_i, '.$block_size.');
  1726. if (strlen($_block) > strlen($_buffer["xor"])) {
  1727. $in = $_xor;
  1728. '.$encrypt_block.'
  1729. $_xor = $in;
  1730. $_buffer["xor"].= $_xor;
  1731. }
  1732. $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
  1733. $_ciphertext.= $_block ^ $_key;
  1734. }
  1735. } else {
  1736. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1737. $in = $_xor;
  1738. '.$encrypt_block.'
  1739. $_xor = $in;
  1740. $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
  1741. }
  1742. $_key = $_xor;
  1743. }
  1744. if ($self->continuousBuffer) {
  1745. $self->encryptIV = $_xor;
  1746. if ($_start = $_plaintext_len % '.$block_size.') {
  1747. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  1748. }
  1749. }
  1750. return $_ciphertext;
  1751. ';
  1752. $decrypt = $init_encrypt . '
  1753. $_plaintext = "";
  1754. $_ciphertext_len = strlen($_text);
  1755. $_xor = $self->decryptIV;
  1756. $_buffer = &$self->debuffer;
  1757. if (strlen($_buffer["xor"])) {
  1758. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1759. $_block = substr($_text, $_i, '.$block_size.');
  1760. if (strlen($_block) > strlen($_buffer["xor"])) {
  1761. $in = $_xor;
  1762. '.$encrypt_block.'
  1763. $_xor = $in;
  1764. $_buffer["xor"].= $_xor;
  1765. }
  1766. $_key = $self->_stringShift($_buffer["xor"], '.$block_size.');
  1767. $_plaintext.= $_block ^ $_key;
  1768. }
  1769. } else {
  1770. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1771. $in = $_xor;
  1772. '.$encrypt_block.'
  1773. $_xor = $in;
  1774. $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor;
  1775. }
  1776. $_key = $_xor;
  1777. }
  1778. if ($self->continuousBuffer) {
  1779. $self->decryptIV = $_xor;
  1780. if ($_start = $_ciphertext_len % '.$block_size.') {
  1781. $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"];
  1782. }
  1783. }
  1784. return $_plaintext;
  1785. ';
  1786. break;
  1787. case CRYPT_MODE_STREAM:
  1788. $encrypt = $init_encrypt . '
  1789. $_ciphertext = "";
  1790. '.$encrypt_block.'
  1791. return $_ciphertext;
  1792. ';
  1793. $decrypt = $init_decrypt . '
  1794. $_plaintext = "";
  1795. '.$decrypt_block.'
  1796. return $_plaintext;
  1797. ';
  1798. break;
  1799. // case CRYPT_MODE_CBC:
  1800. default:
  1801. $encrypt = $init_encrypt . '
  1802. $_ciphertext = "";
  1803. $_text = $self->_pad($_text);
  1804. $_plaintext_len = strlen($_text);
  1805. $in = $self->encryptIV;
  1806. for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') {
  1807. $in = substr($_text, $_i, '.$block_size.') ^ $in;
  1808. '.$encrypt_block.'
  1809. $_ciphertext.= $in;
  1810. }
  1811. if ($self->continuousBuffer) {
  1812. $self->encryptIV = $in;
  1813. }
  1814. return $_ciphertext;
  1815. ';
  1816. $decrypt = $init_decrypt . '
  1817. $_plaintext = "";
  1818. $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0));
  1819. $_ciphertext_len = strlen($_text);
  1820. $_iv = $self->decryptIV;
  1821. for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') {
  1822. $in = $_block = substr($_text, $_i, '.$block_size.');
  1823. '.$decrypt_block.'
  1824. $_plaintext.= $in ^ $_iv;
  1825. $_iv = $_block;
  1826. }
  1827. if ($self->continuousBuffer) {
  1828. $self->decryptIV = $_iv;
  1829. }
  1830. return $self->_unpad($_plaintext);
  1831. ';
  1832. break;
  1833. }
  1834. // Create the $inline function and return its name as string. Ready to run!
  1835. return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }');
  1836. }
  1837. /**
  1838. * Holds the lambda_functions table (classwide)
  1839. *
  1840. * Each name of the lambda function, created from
  1841. * _setupInlineCrypt() && _createInlineCryptFunction()
  1842. * is stored, classwide (!), here for reusing.
  1843. *
  1844. * The string-based index of $function is a classwide
  1845. * uniqe value representing, at least, the $mode of
  1846. * operation (or more... depends of the optimizing level)
  1847. * for which $mode the lambda function was created.
  1848. *
  1849. * @access private
  1850. * @return &Array
  1851. */
  1852. function &_getLambdaFunctions()
  1853. {
  1854. static $functions = array();
  1855. return $functions;
  1856. }
  1857. }
  1858. // vim: ts=4:sw=4:et:
  1859. // vim6: fdl=1: