SymmetricKey.php 97 KB

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