....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 195.3.193.33  /  Your IP : 216.73.216.125
Web Server : Apache
System : Linux server3 5.10.0-35-amd64 #1 SMP Debian 5.10.237-1 (2025-05-19) x86_64
User : web032 ( 1035)
PHP Version : 7.3.33
Disable Function : show_source, highlight_file, apache_child_terminate, apache_get_modules, apache_note, apache_setenv, virtual, dl, disk_total_space, posix_getpwnam, posix_getpwuid, posix_mkfifo, posix_mknod, posix_setpgid, posix_setsid, posix_setuid, posix_uname, proc_nice, openlog, syslog, pfsockopen
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/web032/htdocs/cms/libraries/php-encryption/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/web032/htdocs/cms/libraries/php-encryption/Crypto.php
<?php

/*
 * PHP Encryption Library
 * Copyright (c) 2014, Taylor Hornby
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, 
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation 
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Web: https://defuse.ca/secure-php-encryption.htm
 * GitHub: https://github.com/defuse/php-encryption 
 *
 * WARNING: This encryption library is not a silver bullet. It only provides
 * symmetric encryption given a uniformly random key. This means you MUST NOT
 * use an ASCII string like a password as the key parameter, it MUST be
 * a uniformly random key generated by CreateNewRandomKey(). If you want to
 * encrypt something with a password, apply a password key derivation function
 * like PBKDF2 or scrypt with a random salt to generate a key.
 *
 * WARNING: Error handling is very important, especially for crypto code! 
 *
 * How to use this code:
 *
 *     Generating a Key
 *     ----------------
 *       try {
 *           $key = Crypto::CreateNewRandomKey();
 *           // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
 *           // they may leak the key to the attacker through side channels.
 *       } catch (CryptoTestFailedException $ex) {
 *           die('Cannot safely create a key');
 *       } catch (CannotPerformOperationException $ex) {
 *           die('Cannot safely create a key');
 *       }
 *
 *     Encrypting a Message
 *     --------------------
 *       $message = "ATTACK AT DAWN";
 *       try {
 *           $ciphertext = Crypto::Encrypt($message, $key);
 *       } catch (CryptoTestFailedException $ex) {
 *           die('Cannot safely perform encryption');
 *       } catch (CannotPerformOperationException $ex) {
 *           die('Cannot safely perform decryption');
 *       }
 *
 *     Decrypting a Message
 *     --------------------
 *       try {
 *           $decrypted = Crypto::Decrypt($ciphertext, $key);
 *       } catch (InvalidCiphertextException $ex) { // VERY IMPORTANT
 *           // Either:
 *           //   1. The ciphertext was modified by the attacker,
 *           //   2. The key is wrong, or
 *           //   3. $ciphertext is not a valid ciphertext or was corrupted.
 *           // Assume the worst.
 *           die('DANGER! DANGER! The ciphertext has been tampered with!');
 *       } catch (CryptoTestFailedException $ex) {
 *           die('Cannot safely perform encryption');
 *       } catch (CannotPerformOperationException $ex) {
 *           die('Cannot safely perform decryption');
 *       }
 */

/* 
 * Raised by Decrypt() when one of the following conditions are met:
 *  - The key is wrong.
 *  - The ciphertext is invalid or not in the correct format.
 *  - The attacker modified the ciphertext.
 */
class InvalidCiphertextException extends Exception {}
/* If you see these, it means it is NOT SAFE to do encryption on your system. */
class CannotPerformOperationException extends Exception {}
class CryptoTestFailedException extends Exception {}

class Crypto
{
    // Ciphertext format: [____HMAC____][____IV____][____CIPHERTEXT____].

    /* Do not change these constants! */
    const CIPHER = MCRYPT_RIJNDAEL_128;
    const KEY_BYTE_SIZE = 16;
    const CIPHER_MODE = 'cbc';
    const HASH_FUNCTION = 'sha256';
    const MAC_BYTE_SIZE = 32;
    const ENCRYPTION_INFO = 'DefusePHP|KeyForEncryption';
    const AUTHENTICATION_INFO = 'DefusePHP|KeyForAuthentication';

    /*
     * Use this to generate a random encryption key.
     */
    public static function CreateNewRandomKey()
    {
        Crypto::RuntimeTest();
        return self::SecureRandom(self::KEY_BYTE_SIZE);
    }

    /*
     * Encrypts a message.
     * $plaintext is the message to encrypt.
     * $key is the encryption key, a value generated by CreateNewRandomKey().
     * You MUST catch exceptions thrown by this function. See docs above.
     */
    public static function Encrypt($plaintext, $key)
    {
        Crypto::RuntimeTest();

        if (self::our_strlen($key) !== self::KEY_BYTE_SIZE)
        {
            throw new CannotPerformOperationException("Bad key.");
        }

        // Generate a sub-key for encryption.
        $keysize = self::KEY_BYTE_SIZE;
        $ekey = self::HKDF(self::HASH_FUNCTION, $key, $keysize, self::ENCRYPTION_INFO);

        // Generate a random initialization vector.
        self::EnsureFunctionExists("mcrypt_get_iv_size");
        $ivsize = mcrypt_get_iv_size(self::CIPHER, self::CIPHER_MODE);
        if ($ivsize === FALSE || $ivsize <= 0) {
            throw new CannotPerformOperationException();
        }
        $iv = self::SecureRandom($ivsize);

        $ciphertext = $iv . self::PlainEncrypt($plaintext, $ekey, $iv);

        // Generate a sub-key for authentication and apply the HMAC.
        $akey = self::HKDF(self::HASH_FUNCTION, $key, self::KEY_BYTE_SIZE, self::AUTHENTICATION_INFO);
        $auth = hash_hmac(self::HASH_FUNCTION, $ciphertext, $akey, true);
        $ciphertext = $auth . $ciphertext;

        return $ciphertext;
    }

    /*
     * Decrypts a ciphertext.
     * $ciphertext is the ciphertext to decrypt.
     * $key is the key that the ciphertext was encrypted with.
     * You MUST catch exceptions thrown by this function. See docs above.
     */
    public static function Decrypt($ciphertext, $key)
    {
        Crypto::RuntimeTest();

        // Extract the HMAC from the front of the ciphertext.
        if (self::our_strlen($ciphertext) <= self::MAC_BYTE_SIZE) {
            throw new InvalidCiphertextException();
        }
        $hmac = self::our_substr($ciphertext, 0, self::MAC_BYTE_SIZE);
        if ($hmac === FALSE) {
            throw new CannotPerformOperationException();
        }
        $ciphertext = self::our_substr($ciphertext, self::MAC_BYTE_SIZE);
        if ($ciphertext === FALSE) {
            throw new CannotPerformOperationException();
        }

        // Regenerate the same authentication sub-key.
        $akey = self::HKDF(self::HASH_FUNCTION, $key, self::KEY_BYTE_SIZE, self::AUTHENTICATION_INFO);

        if (self::VerifyHMAC($hmac, $ciphertext, $akey))
        {
            // Regenerate the same encryption sub-key.
            $keysize = self::KEY_BYTE_SIZE;
            $ekey = self::HKDF(self::HASH_FUNCTION, $key, $keysize, self::ENCRYPTION_INFO);

            // Extract the initialization vector from the ciphertext.
            self::EnsureFunctionExists("mcrypt_get_iv_size");
            $ivsize = mcrypt_get_iv_size(self::CIPHER, self::CIPHER_MODE);
            if ($ivsize === FALSE || $ivsize <= 0) {
                throw new CannotPerformOperationException();
            }
            if (self::our_strlen($ciphertext) <= $ivsize) {
                throw new InvalidCiphertextException();
            }
            $iv = self::our_substr($ciphertext, 0, $ivsize);
            if ($iv === FALSE) {
                throw new CannotPerformOperationException();
            }
            $ciphertext = self::our_substr($ciphertext, $ivsize);
            if ($ciphertext === FALSE) {
                throw new CannotPerformOperationException();
            }
            
            $plaintext = self::PlainDecrypt($ciphertext, $ekey, $iv);

            return $plaintext;
        }
        else
        {
            /*
             * We throw an exception instead of returning FALSE because we want
             * a script that doesn't handle this condition to CRASH, instead
             * of thinking the ciphertext decrypted to the value FALSE.
             */
             throw new InvalidCiphertextException();
        }
    }

    /*
     * Runs tests.
     * Raises CannotPerformOperationException or CryptoTestFailedException if
     * one of the tests fail. If any tests fails, your system is not capable of
     * performing encryption, so make sure you fail safe in that case.
     */
    public static function RuntimeTest()
    {
        // 0: Tests haven't been run yet.
        // 1: Tests have passed.
        // 2: Tests are running right now.
        // 3: Tests have failed.
        static $test_state = 0;

        if ($test_state === 1 || $test_state === 2) {
            return;
        }

        try {
            $test_state = 2;
            self::AESTestVector();
            self::HMACTestVector();
            self::HKDFTestVector();

            self::TestEncryptDecrypt();
            if (self::our_strlen(Crypto::CreateNewRandomKey()) != self::KEY_BYTE_SIZE) {
                throw new CryptoTestFailedException();
            }

            if (self::ENCRYPTION_INFO == self::AUTHENTICATION_INFO) {
                throw new CryptoTestFailedException();
            }
        } catch (CryptoTestFailedException $ex) {
            // Do this, otherwise it will stay in the "tests are running" state.
            $test_state = 3;
            throw $ex;
        }

        // Change this to '0' make the tests always re-run (for benchmarking).
        $test_state = 1;
    }

    /*
     * Never call this method directly!
     */
    private static function PlainEncrypt($plaintext, $key, $iv)
    {
        self::EnsureFunctionExists("mcrypt_module_open");
        $crypt = mcrypt_module_open(self::CIPHER, "", self::CIPHER_MODE, "");
        if ($crypt === FALSE) {
            throw new CannotPerformOperationException();
        }

        // Pad the plaintext to a multiple of the block size.
        self::EnsureFunctionExists("mcrypt_enc_get_block_size");
        $block = mcrypt_enc_get_block_size($crypt);
        $pad = $block - (self::our_strlen($plaintext) % $block);
        $plaintext .= str_repeat(chr($pad), $pad);

        self::EnsureFunctionExists("mcrypt_generic_init");
        $ret = mcrypt_generic_init($crypt, $key, $iv);
        if ($ret !== 0) {
            throw new CannotPerformOperationException();
        }
        self::EnsureFunctionExists("mcrypt_generic");
        $ciphertext = mcrypt_generic($crypt, $plaintext);
        self::EnsureFunctionExists("mcrypt_generic_deinit");
        $ret = mcrypt_generic_deinit($crypt);
        if ($ret !== TRUE) {
            throw new CannotPerformOperationException();
        }
        self::EnsureFunctionExists("mcrypt_module_close");
        $ret = mcrypt_module_close($crypt);
        if ($ret !== TRUE) {
            throw new CannotPerformOperationException();
        }

        return $ciphertext;
    }

    /*
     * Never call this method directly!
     */
    private static function PlainDecrypt($ciphertext, $key, $iv)
    {
        self::EnsureFunctionExists("mcrypt_module_open");
        $crypt = mcrypt_module_open(self::CIPHER, "", self::CIPHER_MODE, "");
        if ($crypt === FALSE) {
            throw new CannotPerformOperationException();
        }

        self::EnsureFunctionExists("mcrypt_enc_get_block_size");
        $block = mcrypt_enc_get_block_size($crypt);
        self::EnsureFunctionExists("mcrypt_generic_init");
        $ret = mcrypt_generic_init($crypt, $key, $iv);
        if ($ret !== 0) {
            throw new CannotPerformOperationException();
        }
        self::EnsureFunctionExists("mdecrypt_generic");
        $plaintext = mdecrypt_generic($crypt, $ciphertext);
        self::EnsureFunctionExists("mcrypt_generic_deinit");
        $ret = mcrypt_generic_deinit($crypt);
        if ($ret !== TRUE) {
            throw new CannotPerformOperationException();
        }
        self::EnsureFunctionExists("mcrypt_module_close");
        $ret = mcrypt_module_close($crypt);
        if ($ret !== TRUE) {
            throw new CannotPerformOperationException();
        }

        // Remove the padding.
        $pad = ord($plaintext[self::our_strlen($plaintext) - 1]);
        if ($pad <= 0 || $pad > $block) {
            throw new CannotPerformOperationException();
        }
        $plaintext = self::our_substr($plaintext, 0, self::our_strlen($plaintext) - $pad);
        if ($plaintext === FALSE) {
            throw new CannotPerformOperationException();
        }

        return $plaintext;
    }

    /*
     * Returns a random binary string of length $octets bytes.
     */
    private static function SecureRandom($octets)
    {
        self::EnsureFunctionExists("mcrypt_create_iv");
        $random = mcrypt_create_iv($octets, MCRYPT_DEV_URANDOM);
        if ($random === FALSE) {
            throw new CannotPerformOperationException();
        } else {
            return $random;
        }
    }

    /*
     * Use HKDF to derive multiple keys from one.
     * http://tools.ietf.org/html/rfc5869
     */
    private static function HKDF($hash, $ikm, $length, $info = '', $salt = NULL)
    {
        // Find the correct digest length as quickly as we can.
        $digest_length = self::MAC_BYTE_SIZE;
        if ($hash != self::HASH_FUNCTION) {
            $digest_length = self::our_strlen(hash_hmac($hash, '', '', true));
        }

        // Sanity-check the desired output length.
        if (empty($length) || !is_int($length) ||
            $length < 0 || $length > 255 * $digest_length) {
            throw new CannotPerformOperationException();
        }

        // "if [salt] not provided, is set to a string of HashLen zeroes."
        if (is_null($salt)) {
            $salt = str_repeat("\x00", $digest_length);
        }

        // HKDF-Extract:
        // PRK = HMAC-Hash(salt, IKM)
        // The salt is the HMAC key.
        $prk = hash_hmac($hash, $ikm, $salt, true);

        // HKDF-Expand:

        // This check is useless, but it serves as a reminder to the spec.
        if (self::our_strlen($prk) < $digest_length) {
            throw new CannotPerformOperationException();
        }

        // T(0) = ''
        $t = '';
        $last_block = '';
        for ($block_index = 1; self::our_strlen($t) < $length; $block_index++) {
            // T(i) = HMAC-Hash(PRK, T(i-1) | info | 0x??)
            $last_block = hash_hmac(
                $hash,
                $last_block . $info . chr($block_index),
                $prk,
                true
            );
            // T = T(1) | T(2) | T(3) | ... | T(N)
            $t .= $last_block;
        }

        // ORM = first L octets of T
        $orm = self::our_substr($t, 0, $length);
        if ($orm === FALSE) {
            throw new CannotPerformOperationException();
        }
        return $orm;
    }

    private static function VerifyHMAC($correct_hmac, $message, $key)
    {
        $message_hmac = hash_hmac(self::HASH_FUNCTION, $message, $key, true);

        // We can't just compare the strings with '==', since it would make
        // timing attacks possible. We could use the XOR-OR constant-time
        // comparison algorithm, but I'm not sure if that's good enough way up
        // here in an interpreted language. So we use the method of HMACing the 
        // strings we want to compare with a random key, then comparing those.

        // NOTE: This leaks information when the strings are not the same
        // length, but they should always be the same length here. Enforce it:
        if (self::our_strlen($correct_hmac) !== self::our_strlen($message_hmac)) {
            throw new CannotPerformOperationException();
        }

        $blind = self::CreateNewRandomKey();
        $message_compare = hash_hmac(self::HASH_FUNCTION, $message_hmac, $blind);
        $correct_compare = hash_hmac(self::HASH_FUNCTION, $correct_hmac, $blind);
        return $correct_compare === $message_compare;
    }

    private static function TestEncryptDecrypt()
    {
        $key = Crypto::CreateNewRandomKey();
        $data = "EnCrYpT EvErYThInG\x00\x00";

        // Make sure encrypting then decrypting doesn't change the message.
        $ciphertext = Crypto::Encrypt($data, $key);
        try {
            $decrypted = Crypto::Decrypt($ciphertext, $key);
        } catch (InvalidCiphertextException $ex) {
            // It's important to catch this and change it into a 
            // CryptoTestFailedException, otherwise a test failure could trick
            // the user into thinking it's just an invalid ciphertext!
            throw new CryptoTestFailedException();
        }
        if($decrypted !== $data)
        {
            throw new CryptoTestFailedException();
        }

        // Modifying the ciphertext: Appending a string.
        try {
            Crypto::Decrypt($ciphertext . "a", $key);
            throw new CryptoTestFailedException();
        } catch (InvalidCiphertextException $e) { /* expected */ }

        // Modifying the ciphertext: Changing an IV byte.
        try {
            $ciphertext[0] = chr((ord($ciphertext[0]) + 1) % 256);
            Crypto::Decrypt($ciphertext, $key);
            throw new CryptoTestFailedException();
        } catch (InvalidCiphertextException $e) { /* expected */ }

        // Decrypting with the wrong key.
        $key = Crypto::CreateNewRandomKey();
        $data = "abcdef";
        $ciphertext = Crypto::Encrypt($data, $key);
        $wrong_key = Crypto::CreateNewRandomKey();
        try {
            Crypto::Decrypt($ciphertext, $wrong_key);
            throw new CryptoTestFailedException();
        } catch (InvalidCiphertextException $e) { /* expected */ }

        // Ciphertext too small (shorter than HMAC).
        $key = Crypto::CreateNewRandomKey();
        $ciphertext = str_repeat("A", self::MAC_BYTE_SIZE - 1);
        try {
            Crypto::Decrypt($ciphertext, $key);
            throw new CryptoTestFailedException();
        } catch (InvalidCiphertextException $e) { /* expected */ }
    }

    private static function HKDFTestVector()
    {
        // HKDF test vectors from RFC 5869

        // Test Case 1
        $ikm = str_repeat("\x0b", 22);
        $salt = self::hexToBytes("000102030405060708090a0b0c");
        $info = self::hexToBytes("f0f1f2f3f4f5f6f7f8f9");
        $length = 42;
        $okm = self::hexToBytes(
            "3cb25f25faacd57a90434f64d0362f2a" .
            "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" .
            "34007208d5b887185865"
        );
        $computed_okm = self::HKDF("sha256", $ikm, $length, $info, $salt);
        if ($computed_okm !== $okm) {
            throw new CryptoTestFailedException();
        }

        // Test Case 7
        $ikm = str_repeat("\x0c", 22);
        $length = 42;
        $okm = self::hexToBytes(
            "2c91117204d745f3500d636a62f64f0a" .
            "b3bae548aa53d423b0d1f27ebba6f5e5" .
            "673a081d70cce7acfc48"
        );
        $computed_okm = self::HKDF("sha1", $ikm, $length);
        if ($computed_okm !== $okm) {
            throw new CryptoTestFailedException();
        }

    }

    private static function HMACTestVector()
    {
        // HMAC test vector From RFC 4231 (Test Case 1)
        $key = str_repeat("\x0b", 20);
        $data = "Hi There";
        $correct = "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7";
        if (hash_hmac(self::HASH_FUNCTION, $data, $key) != $correct) {
            throw new CryptoTestFailedException();
        }
    }

    private static function AESTestVector()
    {
        // AES CBC mode test vector from NIST SP 800-38A
        $key = self::hexToBytes("2b7e151628aed2a6abf7158809cf4f3c");
        $iv = self::hexToBytes("000102030405060708090a0b0c0d0e0f");
        $plaintext = self::hexToBytes(
            "6bc1bee22e409f96e93d7e117393172a" . 
            "ae2d8a571e03ac9c9eb76fac45af8e51" .
            "30c81c46a35ce411e5fbc1191a0a52ef" .
            "f69f2445df4f9b17ad2b417be66c3710"
        );
        $ciphertext = self::hexToBytes(
            "7649abac8119b246cee98e9b12e9197d" .
            "5086cb9b507219ee95db113a917678b2" .
            "73bed6b8e3c1743b7116e69e22229516" .
            "3ff1caa1681fac09120eca307586e1a7" .
            /* Block due to padding. Not from NIST test vector. 
                Padding Block: 10101010101010101010101010101010
                Ciphertext:    3ff1caa1681fac09120eca307586e1a7
                           (+) 2fe1dab1780fbc19021eda206596f1b7 
                           AES 8cb82807230e1321d3fae00d18cc2012
             
             */
            "8cb82807230e1321d3fae00d18cc2012"
        );

        $computed_ciphertext = self::PlainEncrypt($plaintext, $key, $iv);
        if ($computed_ciphertext !== $ciphertext) {
            throw new CryptoTestFailedException();
        }

        $computed_plaintext = self::PlainDecrypt($ciphertext, $key, $iv);
        if ($computed_plaintext !== $plaintext) {
            throw new CryptoTestFailedException();
        }
    }

    /* WARNING: Do not call this function on secrets. It creates side channels. */
    private static function hexToBytes($hex_string)
    {
        return pack("H*", $hex_string);
    }

    private static function EnsureFunctionExists($name)
    {
        if (!function_exists($name)) {
            throw new CannotPerformOperationException();
        }
    }

    /*
     * We need these strlen() and substr() functions because when
     * 'mbstring.func_overload' is set in php.ini, the standard strlen() and
     * substr() are replaced by mb_strlen() and mb_substr().
     */

    private static function our_strlen($str)
    {
        if (function_exists('mb_strlen')) {
            $length = mb_strlen($str, '8bit');
            if ($length === FALSE) {
                throw new CannotPerformOperationException();
            }
            return $length;
        } else {
            return strlen($str);
        }
    }

    private static function our_substr($str, $start, $length = NULL)
    {
        if (function_exists('mb_substr'))
        {
            // mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP
            // 5.3, so we have to find the length ourselves.
            if (!isset($length)) {
                if ($start >= 0) {
                    $length = self::our_strlen($str) - $start;
                } else {
                    $length = -$start;
                }
            }

            return mb_substr($str, $start, $length, '8bit');
        }

        // Unlike mb_substr(), substr() doesn't accept NULL for length
        if (isset($length)) {
            return substr($str, $start, $length);
        } else {
            return substr($str, $start);
        }
    }

}

/*
 * We want to catch all uncaught exceptions that come from the Crypto class,
 * since by default, PHP will leak the key in the stack trace from an uncaught
 * exception. This is a really ugly hack, but I think it's justified.
 *
 * Everything up to handler() getting called should be reliable, so this should
 * reliably suppress the stack traces. The rest is just a bonus so that we don't
 * make it impossible to debug other exceptions.
 *
 * This bit of code was adapted from: http://stackoverflow.com/a/7939492
 */

class CryptoExceptionHandler
{
    private $rethrow = NULL;

    public function __construct()
    {
        set_exception_handler(array($this, "handler"));
    }

    public function handler($ex)
    {
        if (
            $ex instanceof InvalidCiphertextException ||
            $ex instanceof CannotPerformOperationException ||
            $ex instanceof CryptoTestFailedException
        ) {
            echo "FATAL ERROR: Uncaught crypto exception. Suppresssing output.\n";
        } else {
            /* Re-throw the exception in the destructor. */
            $this->rethrow = $ex;
        }
    }

    public function __destruct() {
        if ($this->rethrow) {
            throw $this->rethrow;
        }
    }
}

$crypto_exception_handler_object_dont_touch_me = new CryptoExceptionHandler();


Youez - 2016 - github.com/yon3zu
LinuXploit