Base.php 75 KB

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