misc.h 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013
  1. // misc.h - originally written and placed in the public domain by Wei Dai
  2. /// \file misc.h
  3. /// \brief Utility functions for the Crypto++ library.
  4. #ifndef CRYPTOPP_MISC_H
  5. #define CRYPTOPP_MISC_H
  6. #include "config.h"
  7. #include "cryptlib.h"
  8. #include "secblockfwd.h"
  9. #include "smartptr.h"
  10. #include "stdcpp.h"
  11. #include "trap.h"
  12. #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
  13. #if (CRYPTOPP_MSC_VERSION)
  14. # pragma warning(push)
  15. # pragma warning(disable: 4146 4514)
  16. # if (CRYPTOPP_MSC_VERSION >= 1400)
  17. # pragma warning(disable: 6326)
  18. # endif
  19. #endif
  20. // Issue 340 and Issue 793
  21. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  22. # pragma GCC diagnostic push
  23. # pragma GCC diagnostic ignored "-Wconversion"
  24. # pragma GCC diagnostic ignored "-Wsign-conversion"
  25. # pragma GCC diagnostic ignored "-Wunused-function"
  26. #endif
  27. #ifdef _MSC_VER
  28. #if _MSC_VER >= 1400
  29. // VC2005 workaround: disable declarations that conflict with winnt.h
  30. #define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1
  31. #define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2
  32. #define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3
  33. #define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4
  34. #include <intrin.h>
  35. #undef _interlockedbittestandset
  36. #undef _interlockedbittestandreset
  37. #undef _interlockedbittestandset64
  38. #undef _interlockedbittestandreset64
  39. #define CRYPTOPP_FAST_ROTATE(x) 1
  40. #elif _MSC_VER >= 1300
  41. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64)
  42. #else
  43. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
  44. #endif
  45. #elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \
  46. (defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM)))
  47. #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32)
  48. #elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions
  49. #define CRYPTOPP_FAST_ROTATE(x) 1
  50. #else
  51. #define CRYPTOPP_FAST_ROTATE(x) 0
  52. #endif
  53. #ifdef __BORLANDC__
  54. #include <mem.h>
  55. #include <stdlib.h>
  56. #endif
  57. #if (defined(__GNUC__) || defined(__clang__)) && defined(__linux__)
  58. #define CRYPTOPP_BYTESWAP_AVAILABLE 1
  59. #include <byteswap.h>
  60. #endif
  61. // Limit to ARM A-32. Aarch64 is failing self tests.
  62. #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 6)
  63. #define CRYPTOPP_ARM_BYTEREV_AVAILABLE 1
  64. #endif
  65. // Limit to ARM A-32. Aarch64 is failing self tests.
  66. #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 7)
  67. #define CRYPTOPP_ARM_BITREV_AVAILABLE 1
  68. #endif
  69. #if defined(__BMI__)
  70. # include <x86intrin.h>
  71. # include <immintrin.h>
  72. #endif // GCC and BMI
  73. // More LLVM bullshit. Apple Clang 6.0 does not define them.
  74. // Later version of Clang defines them and results in warnings.
  75. #if defined(__clang__)
  76. # ifndef _blsr_u32
  77. # define _blsr_u32 __blsr_u32
  78. # endif
  79. # ifndef _blsr_u64
  80. # define _blsr_u64 __blsr_u64
  81. # endif
  82. # ifndef _tzcnt_u32
  83. # define _tzcnt_u32 __tzcnt_u32
  84. # endif
  85. # ifndef _tzcnt_u64
  86. # define _tzcnt_u64 __tzcnt_u64
  87. # endif
  88. #endif
  89. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  90. #if CRYPTOPP_DOXYGEN_PROCESSING
  91. /// \brief The maximum value of a machine word
  92. /// \details <tt>SIZE_MAX</tt> provides the maximum value of a machine word. The value
  93. /// is <tt>0xffffffff</tt> on 32-bit targets, and <tt>0xffffffffffffffff</tt> on 64-bit
  94. /// targets.
  95. /// \details If <tt>SIZE_MAX</tt> is not defined, then <tt>__SIZE_MAX__</tt> is used if
  96. /// defined. If not defined, then <tt>SIZE_T_MAX</tt> is used if defined. If not defined,
  97. /// then the library uses <tt>std::numeric_limits<size_t>::max()</tt>.
  98. /// \details The library prefers <tt>__SIZE_MAX__</tt> or <tt>__SIZE_T_MAX__</tt> because
  99. /// they are effectively <tt>constexpr</tt> that is optimized well by all compilers.
  100. /// <tt>std::numeric_limits<size_t>::max()</tt> is not always a <tt>constexpr</tt>, and
  101. /// it is not always optimized well.
  102. # define SIZE_MAX ...
  103. #else
  104. // Its amazing portability problems still plague this simple concept in 2015.
  105. // http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max
  106. // Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208
  107. #ifndef SIZE_MAX
  108. # if defined(__SIZE_MAX__)
  109. # define SIZE_MAX __SIZE_MAX__
  110. # elif defined(SIZE_T_MAX)
  111. # define SIZE_MAX SIZE_T_MAX
  112. # elif defined(__SIZE_TYPE__)
  113. # define SIZE_MAX (~(__SIZE_TYPE__)0)
  114. # else
  115. # define SIZE_MAX ((std::numeric_limits<size_t>::max)())
  116. # endif
  117. #endif
  118. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  119. NAMESPACE_BEGIN(CryptoPP)
  120. // Forward declaration for IntToString specialization
  121. class Integer;
  122. // ************** compile-time assertion ***************
  123. #if CRYPTOPP_DOXYGEN_PROCESSING
  124. /// \brief Compile time assertion
  125. /// \param expr the expression to evaluate
  126. /// \details Asserts the expression <tt>expr</tt> during compile. If C++14 and
  127. /// N3928 are available, then C++14 <tt>static_assert</tt> is used. Otherwise,
  128. /// a <tt>CompileAssert</tt> structure is used. When the structure is used
  129. /// a negative-sized array triggers the assert at compile time.
  130. # define CRYPTOPP_COMPILE_ASSERT(expr) { ... }
  131. #elif defined(CRYPTOPP_CXX17_STATIC_ASSERT)
  132. # define CRYPTOPP_COMPILE_ASSERT(expr) static_assert(expr)
  133. #else // CRYPTOPP_DOXYGEN_PROCESSING
  134. template <bool b>
  135. struct CompileAssert
  136. {
  137. static char dummy[2*b-1];
  138. };
  139. #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
  140. #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y)
  141. #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y
  142. #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS)
  143. # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
  144. #else
  145. # if defined(__GNUC__) || defined(__clang__)
  146. # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
  147. static CompileAssert<(assertion)> \
  148. CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused))
  149. # else
  150. # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \
  151. static CompileAssert<(assertion)> \
  152. CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)
  153. # endif // GCC or Clang
  154. #endif
  155. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  156. // ************** count elements in an array ***************
  157. #if CRYPTOPP_DOXYGEN_PROCESSING
  158. /// \brief Counts elements in an array
  159. /// \param arr an array of elements
  160. /// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined
  161. /// to <tt>_countof(x)</tt> to ensure correct results for pointers.
  162. /// \note COUNTOF does not produce correct results with pointers, and an array must be used.
  163. /// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using
  164. /// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms.
  165. # define COUNTOF(arr)
  166. #else
  167. // VS2005 added _countof
  168. #ifndef COUNTOF
  169. # if defined(_MSC_VER) && (_MSC_VER >= 1400)
  170. # define COUNTOF(x) _countof(x)
  171. # else
  172. # define COUNTOF(x) (sizeof(x)/sizeof(x[0]))
  173. # endif
  174. #endif // COUNTOF
  175. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  176. // ************** misc classes ***************
  177. /// \brief An Empty class
  178. /// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists.
  179. class CRYPTOPP_DLL Empty
  180. {
  181. };
  182. #if !defined(CRYPTOPP_DOXYGEN_PROCESSING)
  183. template <class BASE1, class BASE2>
  184. class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2
  185. {
  186. };
  187. template <class BASE1, class BASE2, class BASE3>
  188. class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3
  189. {
  190. };
  191. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  192. /// \tparam T class or type
  193. /// \brief Uses encapsulation to hide an object in derived classes
  194. /// \details The object T is declared as protected.
  195. template <class T>
  196. class ObjectHolder
  197. {
  198. protected:
  199. T m_object;
  200. };
  201. /// \brief Ensures an object is not copyable
  202. /// \details NotCopyable ensures an object is not copyable by making the
  203. /// copy constructor and assignment operator private. Deleters are used
  204. /// under C++11.
  205. /// \sa Clonable class
  206. class NotCopyable
  207. {
  208. public:
  209. NotCopyable() {}
  210. #if CRYPTOPP_CXX11_DELETED_FUNCTIONS
  211. NotCopyable(const NotCopyable &) = delete;
  212. void operator=(const NotCopyable &) = delete;
  213. #else
  214. private:
  215. NotCopyable(const NotCopyable &);
  216. void operator=(const NotCopyable &);
  217. #endif
  218. };
  219. /// \brief An object factory function
  220. /// \tparam T class or type
  221. /// \details NewObject overloads operator()().
  222. template <class T>
  223. struct NewObject
  224. {
  225. T* operator()() const {return new T;}
  226. };
  227. #if CRYPTOPP_DOXYGEN_PROCESSING
  228. /// \brief A memory barrier
  229. /// \details MEMORY_BARRIER attempts to ensure reads and writes are completed
  230. /// in the absence of a language synchronization point. It is used by the
  231. /// Singleton class if the compiler supports it. The barrier is provided at the
  232. /// customary places in a double-checked initialization.
  233. /// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if
  234. /// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>,
  235. /// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used.
  236. #define MEMORY_BARRIER ...
  237. #else
  238. #if defined(CRYPTOPP_CXX11_ATOMIC)
  239. # define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel)
  240. #elif (_MSC_VER >= 1400)
  241. # pragma intrinsic(_ReadWriteBarrier)
  242. # define MEMORY_BARRIER() _ReadWriteBarrier()
  243. #elif defined(__INTEL_COMPILER)
  244. # define MEMORY_BARRIER() __memory_barrier()
  245. #elif defined(__GNUC__) || defined(__clang__)
  246. # define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory")
  247. #else
  248. # define MEMORY_BARRIER()
  249. #endif
  250. #endif // CRYPTOPP_DOXYGEN_PROCESSING
  251. /// \brief Restricts the instantiation of a class to one static object without locks
  252. /// \tparam T the class or type
  253. /// \tparam F the object factory for T
  254. /// \tparam instance an instance counter for the class object
  255. /// \details This class safely initializes a static object in a multi-threaded environment. For C++03
  256. /// and below it will do so without using locks for portability. If two threads call Ref() at the same
  257. /// time, they may get back different references, and one object may end up being memory leaked. This
  258. /// is by design and it avoids a subtle initialization problem in a multi-threaded environment with thread
  259. /// local storage on early Windows platforms, like Windows XP and Windows 2003.
  260. /// \details For C++11 and above, a standard double-checked locking pattern with thread fences
  261. /// are used. The locks and fences are standard and do not hinder portability.
  262. /// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and
  263. /// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should
  264. /// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015.
  265. /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking
  266. /// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic
  267. /// Initialization and Destruction with Concurrency</A> and
  268. /// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN.
  269. /// \since Crypto++ 5.2
  270. template <class T, class F = NewObject<T>, int instance=0>
  271. class Singleton
  272. {
  273. public:
  274. Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {}
  275. // prevent this function from being inlined
  276. CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const;
  277. private:
  278. F m_objectFactory;
  279. };
  280. /// \brief Return a reference to the inner Singleton object
  281. /// \tparam T the class or type
  282. /// \tparam F the object factory for T
  283. /// \tparam instance an instance counter for the class object
  284. /// \details Ref() is used to create the object using the object factory. The
  285. /// object is only created once with the limitations discussed in the class documentation.
  286. /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A>
  287. /// \since Crypto++ 5.2
  288. template <class T, class F, int instance>
  289. const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const
  290. {
  291. #if defined(CRYPTOPP_CXX11_ATOMIC) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_STATIC_INIT)
  292. static std::mutex s_mutex;
  293. static std::atomic<T*> s_pObject;
  294. T *p = s_pObject.load(std::memory_order_relaxed);
  295. std::atomic_thread_fence(std::memory_order_acquire);
  296. if (p)
  297. return *p;
  298. std::lock_guard<std::mutex> lock(s_mutex);
  299. p = s_pObject.load(std::memory_order_relaxed);
  300. std::atomic_thread_fence(std::memory_order_acquire);
  301. if (p)
  302. return *p;
  303. T *newObject = m_objectFactory();
  304. s_pObject.store(newObject, std::memory_order_relaxed);
  305. std::atomic_thread_fence(std::memory_order_release);
  306. return *newObject;
  307. #else
  308. static volatile simple_ptr<T> s_pObject;
  309. T *p = s_pObject.m_p;
  310. MEMORY_BARRIER();
  311. if (p)
  312. return *p;
  313. T *newObject = m_objectFactory();
  314. p = s_pObject.m_p;
  315. MEMORY_BARRIER();
  316. if (p)
  317. {
  318. delete newObject;
  319. return *p;
  320. }
  321. s_pObject.m_p = newObject;
  322. MEMORY_BARRIER();
  323. return *newObject;
  324. #endif
  325. }
  326. // ************** misc functions ***************
  327. /// \brief Create a pointer with an offset
  328. /// \tparam PTR a pointer type
  329. /// \tparam OFF a size type
  330. /// \param pointer a pointer
  331. /// \param offset a offset into the pointer
  332. /// \details PtrAdd can be used to squash Clang and GCC
  333. /// UBsan findings for pointer addition and subtraction.
  334. template <typename PTR, typename OFF>
  335. inline PTR PtrAdd(PTR pointer, OFF offset)
  336. {
  337. return pointer+static_cast<ptrdiff_t>(offset);
  338. }
  339. /// \brief Create a pointer with an offset
  340. /// \tparam PTR a pointer type
  341. /// \tparam OFF a size type
  342. /// \param pointer a pointer
  343. /// \param offset a offset into the pointer
  344. /// \details PtrSub can be used to squash Clang and GCC
  345. /// UBsan findings for pointer addition and subtraction.
  346. template <typename PTR, typename OFF>
  347. inline PTR PtrSub(PTR pointer, OFF offset)
  348. {
  349. return pointer-static_cast<ptrdiff_t>(offset);
  350. }
  351. /// \brief Determine pointer difference
  352. /// \tparam PTR a pointer type
  353. /// \param pointer1 the first pointer
  354. /// \param pointer2 the second pointer
  355. /// \details PtrDiff can be used to squash Clang and GCC
  356. /// UBsan findings for pointer addition and subtraction.
  357. /// pointer1 and pointer2 must point to the same object or
  358. /// array (or one past the end), and yields the number of
  359. /// elements (not bytes) difference.
  360. template <typename PTR>
  361. inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
  362. {
  363. return pointer1 - pointer2;
  364. }
  365. /// \brief Determine pointer difference
  366. /// \tparam PTR a pointer type
  367. /// \param pointer1 the first pointer
  368. /// \param pointer2 the second pointer
  369. /// \details PtrByteDiff can be used to squash Clang and GCC
  370. /// UBsan findings for pointer addition and subtraction.
  371. /// pointer1 and pointer2 must point to the same object or
  372. /// array (or one past the end), and yields the number of
  373. /// bytes (not elements) difference.
  374. template <typename PTR>
  375. inline size_t PtrByteDiff(const PTR pointer1, const PTR pointer2)
  376. {
  377. return (size_t)(reinterpret_cast<uintptr_t>(pointer1) - reinterpret_cast<uintptr_t>(pointer2));
  378. }
  379. /// \brief Pointer to the first element of a string
  380. /// \param str std::string
  381. /// \details BytePtr returns NULL pointer for an empty string.
  382. /// \return Pointer to the first element of a string
  383. /// \since Crypto++ 8.0
  384. inline byte* BytePtr(std::string& str)
  385. {
  386. // Caller wants a writable pointer
  387. CRYPTOPP_ASSERT(str.empty() == false);
  388. if (str.empty())
  389. return NULLPTR;
  390. return reinterpret_cast<byte*>(&str[0]);
  391. }
  392. /// \brief Pointer to the first element of a string
  393. /// \param str SecByteBlock
  394. /// \details BytePtr returns NULL pointer for an empty string.
  395. /// \return Pointer to the first element of a string
  396. /// \since Crypto++ 8.3
  397. byte* BytePtr(SecByteBlock& str);
  398. /// \brief Const pointer to the first element of a string
  399. /// \param str std::string
  400. /// \details ConstBytePtr returns non-NULL pointer for an empty string.
  401. /// \return Pointer to the first element of a string
  402. /// \since Crypto++ 8.0
  403. inline const byte* ConstBytePtr(const std::string& str)
  404. {
  405. if (str.empty())
  406. return NULLPTR;
  407. return reinterpret_cast<const byte*>(&str[0]);
  408. }
  409. /// \brief Const pointer to the first element of a string
  410. /// \param str SecByteBlock
  411. /// \details ConstBytePtr returns non-NULL pointer for an empty string.
  412. /// \return Pointer to the first element of a string
  413. /// \since Crypto++ 8.3
  414. const byte* ConstBytePtr(const SecByteBlock& str);
  415. /// \brief Size of a string
  416. /// \param str std::string
  417. /// \return size of a string
  418. /// \since Crypto++ 8.3
  419. inline size_t BytePtrSize(const std::string& str)
  420. {
  421. return str.size();
  422. }
  423. /// \brief Size of a string
  424. /// \param str SecByteBlock
  425. /// \return size of a string
  426. /// \since Crypto++ 8.3
  427. size_t BytePtrSize(const SecByteBlock& str);
  428. /// \brief Integer value
  429. /// \details EnumToInt avoids C++20 enum-enum conversion
  430. /// warnings under GCC and Clang. C++11 and above use a
  431. /// constexpr function. C++03 and below use a macro due
  432. /// to [lack of] constexpr-ness in early versions of C++.
  433. /// \since Crypto++ 8.6
  434. #if (CRYPTOPP_CXX11_CONSTEXPR)
  435. template <typename T>
  436. constexpr int EnumToInt(T v) {
  437. return static_cast<int>(v);
  438. }
  439. #else
  440. # define EnumToInt(v) static_cast<int>(v)
  441. #endif
  442. #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB)
  443. /// \brief Bounds checking replacement for memcpy()
  444. /// \param dest pointer to the destination memory block
  445. /// \param sizeInBytes size of the destination memory block, in bytes
  446. /// \param src pointer to the source memory block
  447. /// \param count the number of bytes to copy
  448. /// \throw InvalidArgument
  449. /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
  450. /// unsafe functions like memcpy(), strcpy() and memmove(). However,
  451. /// not all standard libraries provides them, like Glibc. The library's
  452. /// memcpy_s() is a near-drop in replacement. Its only a near-replacement
  453. /// because the library's version throws an InvalidArgument on a bounds violation.
  454. /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
  455. /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
  456. /// makes memcpy_s() and memmove_s() available. The library will also optionally
  457. /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
  458. /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
  459. /// \details memcpy_s() will assert the pointers src and dest are not NULL
  460. /// in debug builds. Passing NULL for either pointer is undefined behavior.
  461. inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
  462. {
  463. // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
  464. // Pointers must be valid; otherwise undefined behavior
  465. CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
  466. // Restricted pointers. We want to check ranges, but it is not clear how to do it.
  467. CRYPTOPP_ASSERT(src != dest);
  468. // Destination buffer must be large enough to satisfy request
  469. CRYPTOPP_ASSERT(sizeInBytes >= count);
  470. if (count > sizeInBytes)
  471. throw InvalidArgument("memcpy_s: buffer overflow");
  472. #if CRYPTOPP_MSC_VERSION
  473. # pragma warning(push)
  474. # pragma warning(disable: 4996)
  475. # if (CRYPTOPP_MSC_VERSION >= 1400)
  476. # pragma warning(disable: 6386)
  477. # endif
  478. #endif
  479. if (src != NULLPTR && dest != NULLPTR)
  480. std::memcpy(dest, src, count);
  481. #if CRYPTOPP_MSC_VERSION
  482. # pragma warning(pop)
  483. #endif
  484. }
  485. /// \brief Bounds checking replacement for memmove()
  486. /// \param dest pointer to the destination memory block
  487. /// \param sizeInBytes size of the destination memory block, in bytes
  488. /// \param src pointer to the source memory block
  489. /// \param count the number of bytes to copy
  490. /// \throw InvalidArgument
  491. /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially
  492. /// unsafe functions like memcpy(), strcpy() and memmove(). However,
  493. /// not all standard libraries provides them, like Glibc. The library's
  494. /// memmove_s() is a near-drop in replacement. Its only a near-replacement
  495. /// because the library's version throws an InvalidArgument on a bounds violation.
  496. /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__.
  497. /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library
  498. /// makes memcpy_s() and memmove_s() available. The library will also optionally
  499. /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined.
  500. /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default.
  501. /// \details memmove_s() will assert the pointers src and dest are not NULL
  502. /// in debug builds. Passing NULL for either pointer is undefined behavior.
  503. inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count)
  504. {
  505. // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55
  506. // Pointers must be valid; otherwise undefined behavior
  507. CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR);
  508. // Destination buffer must be large enough to satisfy request
  509. CRYPTOPP_ASSERT(sizeInBytes >= count);
  510. if (count > sizeInBytes)
  511. throw InvalidArgument("memmove_s: buffer overflow");
  512. #if CRYPTOPP_MSC_VERSION
  513. # pragma warning(push)
  514. # pragma warning(disable: 4996)
  515. # if (CRYPTOPP_MSC_VERSION >= 1400)
  516. # pragma warning(disable: 6386)
  517. # endif
  518. #endif
  519. if (src != NULLPTR && dest != NULLPTR)
  520. std::memmove(dest, src, count);
  521. #if CRYPTOPP_MSC_VERSION
  522. # pragma warning(pop)
  523. #endif
  524. }
  525. #if __BORLANDC__ >= 0x620
  526. // C++Builder 2010 workaround: can't use std::memcpy_s
  527. // because it doesn't allow 0 lengths
  528. # define memcpy_s CryptoPP::memcpy_s
  529. # define memmove_s CryptoPP::memmove_s
  530. #endif
  531. #endif // __STDC_WANT_SECURE_LIB__
  532. /// \brief Swaps two variables which are arrays
  533. /// \tparam T class or type
  534. /// \param a the first value
  535. /// \param b the second value
  536. /// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt>
  537. /// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers
  538. /// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.
  539. /// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables
  540. /// in C++03 given its an opaque type and an array?</A> on Stack Overflow.
  541. template <class T>
  542. inline void vec_swap(T& a, T& b)
  543. {
  544. // __m128i is an unsigned long long[2], and support for swapping it was
  545. // not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while
  546. // SunCC 12.4 consumes it without -std=c++11.
  547. #if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120)
  548. T t;
  549. t=a, a=b, b=t;
  550. #else
  551. std::swap(a, b);
  552. #endif
  553. }
  554. /// \brief Memory block initializer
  555. /// \param ptr pointer to the memory block being written
  556. /// \param val the integer value to write for each byte
  557. /// \param num the size of the source memory block, in bytes
  558. /// \details Internally the function calls memset with the value <tt>val</tt>.
  559. /// memset_z can be used to initialize a freshly allocated memory block.
  560. /// To zeroize a memory block on destruction use <tt>SecureWipeBuffer</tt>.
  561. /// \return the pointer to the memory block
  562. /// \sa SecureWipeBuffer
  563. inline void * memset_z(void *ptr, int val, size_t num)
  564. {
  565. // avoid extraneous warning on GCC 4.3.2 Ubuntu 8.10
  566. #if CRYPTOPP_GCC_VERSION >= 30001 || CRYPTOPP_LLVM_CLANG_VERSION >= 20800 || \
  567. CRYPTOPP_APPLE_CLANG_VERSION >= 30000
  568. if (__builtin_constant_p(num) && num==0)
  569. return ptr;
  570. #endif
  571. return std::memset(ptr, val, num);
  572. }
  573. /// \brief Replacement function for std::min
  574. /// \tparam T class or type
  575. /// \param a the first value
  576. /// \param b the second value
  577. /// \return the minimum value based on a comparison of <tt>b \< a</tt> using <tt>operator\<</tt>
  578. /// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
  579. template <class T> inline const T& STDMIN(const T& a, const T& b)
  580. {
  581. return b < a ? b : a;
  582. }
  583. /// \brief Replacement function for std::max
  584. /// \tparam T class or type
  585. /// \param a the first value
  586. /// \param b the second value
  587. /// \return the minimum value based on a comparison of <tt>a \< b</tt> using <tt>operator\<</tt>
  588. /// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0
  589. template <class T> inline const T& STDMAX(const T& a, const T& b)
  590. {
  591. return a < b ? b : a;
  592. }
  593. #if CRYPTOPP_MSC_VERSION
  594. # pragma warning(push)
  595. # pragma warning(disable: 4389)
  596. #endif
  597. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  598. # pragma GCC diagnostic push
  599. # pragma GCC diagnostic ignored "-Wsign-compare"
  600. # pragma GCC diagnostic ignored "-Wstrict-overflow"
  601. # if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000)
  602. # pragma GCC diagnostic ignored "-Wtautological-compare"
  603. # elif (CRYPTOPP_GCC_VERSION >= 40300)
  604. # pragma GCC diagnostic ignored "-Wtype-limits"
  605. # endif
  606. #endif
  607. /// \brief Safe comparison of values that could be negative and incorrectly promoted
  608. /// \tparam T1 class or type
  609. /// \tparam T2 class or type
  610. /// \param a the first value
  611. /// \param b the second value
  612. /// \return the minimum value based on a comparison a and b using <tt>operator&lt;</tt>.
  613. /// \details The comparison <tt>b \< a</tt> is performed and the value returned is a's type T1.
  614. template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b)
  615. {
  616. CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0));
  617. if (sizeof(T1)<=sizeof(T2))
  618. return b < (T2)a ? (T1)b : a;
  619. else
  620. return (T1)b < a ? (T1)b : a;
  621. }
  622. /// \brief Tests whether a conversion from -> to is safe to perform
  623. /// \tparam T1 class or type
  624. /// \tparam T2 class or type
  625. /// \param from the first value
  626. /// \param to the second value
  627. /// \return true if its safe to convert from into to, false otherwise.
  628. template <class T1, class T2>
  629. inline bool SafeConvert(T1 from, T2 &to)
  630. {
  631. to = static_cast<T2>(from);
  632. if (from != to || (from > 0) != (to > 0))
  633. return false;
  634. return true;
  635. }
  636. /// \brief Converts a value to a string
  637. /// \tparam T class or type
  638. /// \param value the value to convert
  639. /// \param base the base to use during the conversion
  640. /// \return the string representation of value in base.
  641. template <class T>
  642. std::string IntToString(T value, unsigned int base = 10)
  643. {
  644. // Hack... set the high bit for uppercase.
  645. const unsigned int HIGH_BIT = (1U << 31);
  646. const char CH = !!(base & HIGH_BIT) ? 'A' : 'a';
  647. base &= ~HIGH_BIT;
  648. CRYPTOPP_ASSERT(base >= 2);
  649. if (value == 0)
  650. return "0";
  651. bool negate = false;
  652. if (value < 0)
  653. {
  654. negate = true;
  655. value = 0-value; // VC .NET does not like -a
  656. }
  657. std::string result;
  658. while (value > 0)
  659. {
  660. T digit = value % base;
  661. result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result;
  662. value /= base;
  663. }
  664. if (negate)
  665. result = "-" + result;
  666. return result;
  667. }
  668. /// \brief Converts an unsigned value to a string
  669. /// \param value the value to convert
  670. /// \param base the base to use during the conversion
  671. /// \return the string representation of value in base.
  672. /// \details this template function specialization was added to suppress
  673. /// Coverity findings on IntToString() with unsigned types.
  674. template <> CRYPTOPP_DLL
  675. std::string IntToString<word64>(word64 value, unsigned int base);
  676. /// \brief Converts an Integer to a string
  677. /// \param value the Integer to convert
  678. /// \param base the base to use during the conversion
  679. /// \return the string representation of value in base.
  680. /// \details This is a template specialization of IntToString(). Use it
  681. /// like IntToString():
  682. /// <pre>
  683. /// // Print integer in base 10
  684. /// Integer n...
  685. /// std::string s = IntToString(n, 10);
  686. /// </pre>
  687. /// \details The string is presented with lowercase letters by default. A
  688. /// hack is available to switch to uppercase letters without modifying
  689. /// the function signature.
  690. /// <pre>
  691. /// // Print integer in base 16, uppercase letters
  692. /// Integer n...
  693. /// const unsigned int UPPER = (1 << 31);
  694. /// std::string s = IntToString(n, (UPPER | 16));</pre>
  695. template <> CRYPTOPP_DLL
  696. std::string IntToString<Integer>(Integer value, unsigned int base);
  697. #if CRYPTOPP_MSC_VERSION
  698. # pragma warning(pop)
  699. #endif
  700. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  701. # pragma GCC diagnostic pop
  702. #endif
  703. #define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue
  704. // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
  705. #define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y)))
  706. // these may be faster on other CPUs/compilers
  707. // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
  708. // #define GETBYTE(x, y) (((byte *)&(x))[y])
  709. #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y)))
  710. /// \brief Returns the parity of a value
  711. /// \tparam T class or type
  712. /// \param value the value to provide the parity
  713. /// \return 1 if the number 1-bits in the value is odd, 0 otherwise
  714. template <class T>
  715. unsigned int Parity(T value)
  716. {
  717. for (unsigned int i=8*sizeof(value)/2; i>0; i/=2)
  718. value ^= value >> i;
  719. return (unsigned int)value&1;
  720. }
  721. /// \brief Returns the number of 8-bit bytes or octets required for a value
  722. /// \tparam T class or type
  723. /// \param value the value to test
  724. /// \return the minimum number of 8-bit bytes or octets required to represent a value
  725. template <class T>
  726. unsigned int BytePrecision(const T &value)
  727. {
  728. if (!value)
  729. return 0;
  730. unsigned int l=0, h=8*sizeof(value);
  731. while (h-l > 8)
  732. {
  733. unsigned int t = (l+h)/2;
  734. if (value >> t)
  735. l = t;
  736. else
  737. h = t;
  738. }
  739. return h/8;
  740. }
  741. /// \brief Returns the number of bits required for a value
  742. /// \tparam T class or type
  743. /// \param value the value to test
  744. /// \return the maximum number of bits required to represent a value.
  745. template <class T>
  746. unsigned int BitPrecision(const T &value)
  747. {
  748. if (!value)
  749. return 0;
  750. unsigned int l=0, h=8*sizeof(value);
  751. while (h-l > 1)
  752. {
  753. unsigned int t = (l+h)/2;
  754. if (value >> t)
  755. l = t;
  756. else
  757. h = t;
  758. }
  759. return h;
  760. }
  761. /// Determines the number of trailing 0-bits in a value
  762. /// \param v the 32-bit value to test
  763. /// \return the number of trailing 0-bits in v, starting at the least significant bit position
  764. /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
  765. /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
  766. /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
  767. inline unsigned int TrailingZeros(word32 v)
  768. {
  769. // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
  770. // We don't enable for Microsoft because it requires a runtime check.
  771. // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
  772. CRYPTOPP_ASSERT(v != 0);
  773. #if defined(__BMI__)
  774. return (unsigned int)_tzcnt_u32(v);
  775. #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
  776. return (unsigned int)__builtin_ctz(v);
  777. #elif defined(_MSC_VER) && (_MSC_VER >= 1400)
  778. unsigned long result;
  779. _BitScanForward(&result, v);
  780. return static_cast<unsigned int>(result);
  781. #else
  782. // from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
  783. static const int MultiplyDeBruijnBitPosition[32] =
  784. {
  785. 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  786. 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
  787. };
  788. return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27];
  789. #endif
  790. }
  791. /// Determines the number of trailing 0-bits in a value
  792. /// \param v the 64-bit value to test
  793. /// \return the number of trailing 0-bits in v, starting at the least significant bit position
  794. /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least
  795. /// significant bit position. The return value is undefined if there are no 1-bits set in the value v.
  796. /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position.
  797. inline unsigned int TrailingZeros(word64 v)
  798. {
  799. // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors
  800. // We don't enable for Microsoft because it requires a runtime check.
  801. // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx
  802. CRYPTOPP_ASSERT(v != 0);
  803. #if defined(__BMI__) && defined(__x86_64__)
  804. return (unsigned int)_tzcnt_u64(v);
  805. #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400)
  806. return (unsigned int)__builtin_ctzll(v);
  807. #elif defined(_MSC_VER) && (_MSC_VER >= 1400) && (defined(_M_X64) || defined(_M_IA64))
  808. unsigned long result;
  809. _BitScanForward64(&result, v);
  810. return static_cast<unsigned int>(result);
  811. #else
  812. return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32));
  813. #endif
  814. }
  815. /// \brief Truncates the value to the specified number of bits.
  816. /// \tparam T class or type
  817. /// \param value the value to truncate or mask
  818. /// \param bits the number of bits to truncate or mask
  819. /// \return the value truncated to the specified number of bits, starting at the least
  820. /// significant bit position
  821. /// \details This function masks the low-order bits of value and returns the result. The
  822. /// mask is created with <tt>(1 << bits) - 1</tt>.
  823. template <class T>
  824. inline T Crop(T value, size_t bits)
  825. {
  826. if (bits < 8*sizeof(value))
  827. return T(value & ((T(1) << bits) - 1));
  828. else
  829. return value;
  830. }
  831. /// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits
  832. /// \param bitCount the number of bits
  833. /// \return the minimum number of 8-bit bytes or octets required by bitCount
  834. /// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes.
  835. inline size_t BitsToBytes(size_t bitCount)
  836. {
  837. return ((bitCount+7)/(8));
  838. }
  839. /// \brief Returns the number of words required for the specified number of bytes
  840. /// \param byteCount the number of bytes
  841. /// \return the minimum number of words required by byteCount
  842. /// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>.
  843. /// <tt>WORD_SIZE</tt> is defined in config.h
  844. inline size_t BytesToWords(size_t byteCount)
  845. {
  846. return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
  847. }
  848. /// \brief Returns the number of words required for the specified number of bits
  849. /// \param bitCount the number of bits
  850. /// \return the minimum number of words required by bitCount
  851. /// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>.
  852. /// <tt>WORD_BITS</tt> is defined in config.h
  853. inline size_t BitsToWords(size_t bitCount)
  854. {
  855. return ((bitCount+WORD_BITS-1)/(WORD_BITS));
  856. }
  857. /// \brief Returns the number of double words required for the specified number of bits
  858. /// \param bitCount the number of bits
  859. /// \return the minimum number of double words required by bitCount
  860. /// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>.
  861. /// <tt>WORD_BITS</tt> is defined in config.h
  862. inline size_t BitsToDwords(size_t bitCount)
  863. {
  864. return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
  865. }
  866. /// Performs an XOR of a buffer with a mask
  867. /// \param buf the buffer to XOR with the mask
  868. /// \param mask the mask to XOR with the buffer
  869. /// \param count the size of the buffers, in bytes
  870. /// \details The function effectively visits each element in the buffers and performs
  871. /// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size.
  872. CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
  873. /// Performs an XOR of an input buffer with a mask and stores the result in an output buffer
  874. /// \param output the destination buffer
  875. /// \param input the source buffer to XOR with the mask
  876. /// \param mask the mask buffer to XOR with the input buffer
  877. /// \param count the size of the buffers, in bytes
  878. /// \details The function effectively visits each element in the buffers and performs
  879. /// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size.
  880. CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
  881. /// \brief Performs a near constant-time comparison of two equally sized buffers
  882. /// \param buf1 the first buffer
  883. /// \param buf2 the second buffer
  884. /// \param count the size of the buffers, in bytes
  885. /// \details VerifyBufsEqual performs an XOR of the elements in two equally sized
  886. /// buffers and returns a result based on the XOR operation. A count of 0 returns
  887. /// true because two empty buffers are considered equal.
  888. /// \details The function is near constant-time because CPU micro-code timings could
  889. /// affect the "constant-ness". Calling code is responsible for mitigating timing
  890. /// attacks if the buffers are not equally sized.
  891. /// \sa ModPowerOf2
  892. CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
  893. /// \brief Tests whether a value is a power of 2
  894. /// \param value the value to test
  895. /// \return true if value is a power of 2, false otherwise
  896. /// \details The function creates a mask of <tt>value - 1</tt> and returns the result
  897. /// of an AND operation compared to 0. If value is 0 or less than 0, then the function
  898. /// returns false.
  899. template <class T>
  900. inline bool IsPowerOf2(const T &value)
  901. {
  902. return value > 0 && (value & (value-1)) == 0;
  903. }
  904. #if defined(__BMI__)
  905. template <>
  906. inline bool IsPowerOf2<word32>(const word32 &value)
  907. {
  908. return value > 0 && _blsr_u32(value) == 0;
  909. }
  910. # if defined(__x86_64__)
  911. template <>
  912. inline bool IsPowerOf2<word64>(const word64 &value)
  913. {
  914. return value > 0 && _blsr_u64(value) == 0;
  915. }
  916. # endif // __x86_64__
  917. #endif // __BMI__
  918. /// \brief Provide the minimum value for a type
  919. /// \tparam T type of class
  920. /// \return the minimum value of the type or class
  921. /// \details NumericLimitsMin() was introduced for Clang at <A
  922. /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364,
  923. /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>.
  924. /// \details NumericLimitsMin() requires a specialization for <tt>T</tt>,
  925. /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return
  926. /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize
  927. /// <tt>numeric_limits</tt> for the type.
  928. /// \since Crypto++ 8.1
  929. template<class T>
  930. inline T NumericLimitsMin()
  931. {
  932. CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
  933. return (std::numeric_limits<T>::min)();
  934. }
  935. /// \brief Provide the maximum value for a type
  936. /// \tparam T type of class
  937. /// \return the maximum value of the type or class
  938. /// \details NumericLimitsMax() was introduced for Clang at <A
  939. /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364,
  940. /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>.
  941. /// \details NumericLimitsMax() requires a specialization for <tt>T</tt>,
  942. /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return
  943. /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize
  944. /// <tt>numeric_limits</tt> for the type.
  945. /// \since Crypto++ 8.1
  946. template<class T>
  947. inline T NumericLimitsMax()
  948. {
  949. CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
  950. return (std::numeric_limits<T>::max)();
  951. }
  952. // NumericLimitsMin and NumericLimitsMax added for word128 types,
  953. // see http://github.com/weidai11/cryptopp/issues/364
  954. #if defined(CRYPTOPP_WORD128_AVAILABLE)
  955. template<>
  956. inline word128 NumericLimitsMin()
  957. {
  958. return 0;
  959. }
  960. template<>
  961. inline word128 NumericLimitsMax()
  962. {
  963. return (static_cast<word128>(LWORD_MAX) << 64U) | LWORD_MAX;
  964. }
  965. #endif
  966. /// \brief Performs a saturating subtract clamped at 0
  967. /// \tparam T1 class or type
  968. /// \tparam T2 class or type
  969. /// \param a the minuend
  970. /// \param b the subtrahend
  971. /// \return the difference produced by the saturating subtract
  972. /// \details Saturating arithmetic restricts results to a fixed range. Results that are
  973. /// less than 0 are clamped at 0.
  974. /// \details Use of saturating arithmetic in places can be advantageous because it can
  975. /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
  976. template <class T1, class T2>
  977. inline T1 SaturatingSubtract(const T1 &a, const T2 &b)
  978. {
  979. // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
  980. return T1((a > b) ? (a - b) : 0);
  981. }
  982. /// \brief Performs a saturating subtract clamped at 1
  983. /// \tparam T1 class or type
  984. /// \tparam T2 class or type
  985. /// \param a the minuend
  986. /// \param b the subtrahend
  987. /// \return the difference produced by the saturating subtract
  988. /// \details Saturating arithmetic restricts results to a fixed range. Results that are
  989. /// less than 1 are clamped at 1.
  990. /// \details Use of saturating arithmetic in places can be advantageous because it can
  991. /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>).
  992. template <class T1, class T2>
  993. inline T1 SaturatingSubtract1(const T1 &a, const T2 &b)
  994. {
  995. // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html
  996. return T1((a > b) ? (a - b) : 1);
  997. }
  998. /// \brief Reduces a value to a power of 2
  999. /// \tparam T1 class or type
  1000. /// \tparam T2 class or type
  1001. /// \param a the first value
  1002. /// \param b the second value
  1003. /// \return ModPowerOf2() returns <tt>a & (b-1)</tt>. <tt>b</tt> must be a power of 2.
  1004. /// Use IsPowerOf2() to determine if <tt>b</tt> is a suitable candidate.
  1005. /// \sa IsPowerOf2
  1006. template <class T1, class T2>
  1007. inline T2 ModPowerOf2(const T1 &a, const T2 &b)
  1008. {
  1009. CRYPTOPP_ASSERT(IsPowerOf2(b));
  1010. // Coverity finding CID 170383 Overflowed return value (INTEGER_OVERFLOW)
  1011. // Visual Studio and /RTCc warning, https://docs.microsoft.com/en-us/cpp/build/reference/rtc-run-time-error-checks
  1012. return T2(a & SaturatingSubtract(b,1U));
  1013. }
  1014. /// \brief Rounds a value down to a multiple of a second value
  1015. /// \tparam T1 class or type
  1016. /// \tparam T2 class or type
  1017. /// \param n the value to reduce
  1018. /// \param m the value to reduce <tt>n</tt> to a multiple
  1019. /// \return the possibly unmodified value \n
  1020. /// \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns
  1021. /// the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned.
  1022. /// \note <tt>T1</tt> and <tt>T2</tt> should be unsigned arithmetic types. If <tt>T1</tt> or
  1023. /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
  1024. /// debug builds when practical, but allows you to perform the operation in release builds.
  1025. template <class T1, class T2>
  1026. inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m)
  1027. {
  1028. // http://github.com/weidai11/cryptopp/issues/364
  1029. #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
  1030. CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
  1031. CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
  1032. #endif
  1033. CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
  1034. CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
  1035. if (IsPowerOf2(m))
  1036. return n - ModPowerOf2(n, m);
  1037. else
  1038. return n - n%m;
  1039. }
  1040. /// \brief Rounds a value up to a multiple of a second value
  1041. /// \tparam T1 class or type
  1042. /// \tparam T2 class or type
  1043. /// \param n the value to reduce
  1044. /// \param m the value to reduce <tt>n</tt> to a multiple
  1045. /// \return the possibly unmodified value \n
  1046. /// \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function
  1047. /// returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is
  1048. /// returned. If the value n would overflow, then an InvalidArgument exception is thrown.
  1049. /// \note <tt>T1</tt> and <tt>T2</tt> should be unsigned arithmetic types. If <tt>T1</tt> or
  1050. /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in
  1051. /// debug builds when practical, but allows you to perform the operation in release builds.
  1052. template <class T1, class T2>
  1053. inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
  1054. {
  1055. // http://github.com/weidai11/cryptopp/issues/364
  1056. #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000)
  1057. CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer);
  1058. CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer);
  1059. #endif
  1060. CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0);
  1061. CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0);
  1062. if (NumericLimitsMax<T1>() - m + 1 < n)
  1063. throw InvalidArgument("RoundUpToMultipleOf: integer overflow");
  1064. return RoundDownToMultipleOf(T1(n+m-1), m);
  1065. }
  1066. /// \brief Returns the minimum alignment requirements of a type
  1067. /// \tparam T class or type
  1068. /// \return the minimum alignment requirements of <tt>T</tt>, in bytes
  1069. /// \details Internally the function calls C++11's <tt>alignof</tt> if
  1070. /// available. If not available, then the function uses compiler
  1071. /// specific extensions such as <tt>__alignof</tt> and <tt>_alignof_</tt>.
  1072. /// If an extension is not available, then the function uses
  1073. /// <tt>sizeof(T)</tt>.
  1074. template <class T>
  1075. inline unsigned int GetAlignmentOf()
  1076. {
  1077. #if defined(CRYPTOPP_CXX11_ALIGNOF)
  1078. return alignof(T);
  1079. #elif (_MSC_VER >= 1300)
  1080. return __alignof(T);
  1081. #elif defined(__GNUC__)
  1082. return __alignof__(T);
  1083. #elif defined(__SUNPRO_CC)
  1084. return __alignof__(T);
  1085. #elif defined(__IBM_ALIGNOF__)
  1086. return __alignof__(T);
  1087. #elif CRYPTOPP_BOOL_SLOW_WORD64
  1088. return UnsignedMin(4U, sizeof(T));
  1089. #else
  1090. return sizeof(T);
  1091. #endif
  1092. }
  1093. /// \brief Determines whether ptr is aligned to a minimum value
  1094. /// \param ptr the pointer being checked for alignment
  1095. /// \param alignment the alignment value to test the pointer against
  1096. /// \return true if <tt>ptr</tt> is aligned on at least <tt>alignment</tt>
  1097. /// boundary, false otherwise
  1098. /// \details Internally the function tests whether alignment is 1. If so,
  1099. /// the function returns true. If not, then the function effectively
  1100. /// performs a modular reduction and returns true if the residue is 0.
  1101. inline bool IsAlignedOn(const void *ptr, unsigned int alignment)
  1102. {
  1103. const uintptr_t x = reinterpret_cast<uintptr_t>(ptr);
  1104. return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2(x, alignment) == 0 : x % alignment == 0);
  1105. }
  1106. /// \brief Determines whether ptr is minimally aligned
  1107. /// \tparam T class or type
  1108. /// \param ptr the pointer to check for alignment
  1109. /// \return true if <tt>ptr</tt> is aligned to at least <tt>T</tt>
  1110. /// boundary, false otherwise
  1111. /// \details Internally the function calls IsAlignedOn with a second
  1112. /// parameter of GetAlignmentOf<T>.
  1113. template <class T>
  1114. inline bool IsAligned(const void *ptr)
  1115. {
  1116. return IsAlignedOn(ptr, GetAlignmentOf<T>());
  1117. }
  1118. #if (CRYPTOPP_LITTLE_ENDIAN)
  1119. typedef LittleEndian NativeByteOrder;
  1120. #elif (CRYPTOPP_BIG_ENDIAN)
  1121. typedef BigEndian NativeByteOrder;
  1122. #else
  1123. # error "Unable to determine endianness"
  1124. #endif
  1125. /// \brief Returns NativeByteOrder as an enumerated ByteOrder value
  1126. /// \return LittleEndian if the native byte order is little-endian,
  1127. /// and BigEndian if the native byte order is big-endian
  1128. /// \details NativeByteOrder is a typedef depending on the platform.
  1129. /// If CRYPTOPP_LITTLE_ENDIAN is set in config.h, then
  1130. /// GetNativeByteOrder returns LittleEndian. If CRYPTOPP_BIG_ENDIAN
  1131. /// is set, then GetNativeByteOrder returns BigEndian.
  1132. /// \note There are other byte orders besides little- and big-endian,
  1133. /// and they include bi-endian and PDP-endian. If a system is neither
  1134. /// little-endian nor big-endian, then a compile time error occurs.
  1135. inline ByteOrder GetNativeByteOrder()
  1136. {
  1137. return NativeByteOrder::ToEnum();
  1138. }
  1139. /// \brief Determines whether order follows native byte ordering
  1140. /// \param order the ordering being tested against native byte ordering
  1141. /// \return true if order follows native byte ordering, false otherwise
  1142. inline bool NativeByteOrderIs(ByteOrder order)
  1143. {
  1144. return order == GetNativeByteOrder();
  1145. }
  1146. /// \brief Returns the direction the cipher is being operated
  1147. /// \tparam T class or type
  1148. /// \param obj the cipher object being queried
  1149. /// \return ENCRYPTION if the cipher obj is being operated in its forward direction,
  1150. /// DECRYPTION otherwise
  1151. /// \details A cipher can be operated in a "forward" direction (encryption) or a "reverse"
  1152. /// direction (decryption). The operations do not have to be symmetric, meaning a second
  1153. /// application of the transformation does not necessarily return the original message.
  1154. /// That is, <tt>E(D(m))</tt> may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not
  1155. /// equal <tt>D(D(m))</tt>.
  1156. template <class T>
  1157. inline CipherDir GetCipherDir(const T &obj)
  1158. {
  1159. return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
  1160. }
  1161. /// \brief Performs an addition with carry on a block of bytes
  1162. /// \param inout the byte block
  1163. /// \param size the size of the block, in bytes
  1164. /// \details Performs an addition with carry by adding 1 on a block of bytes starting at the least
  1165. /// significant byte. Once carry is 0, the function terminates and returns to the caller.
  1166. /// \note The function is not constant time because it stops processing when the carry is 0.
  1167. inline void IncrementCounterByOne(byte *inout, unsigned int size)
  1168. {
  1169. CRYPTOPP_ASSERT(inout != NULLPTR);
  1170. unsigned int carry=1;
  1171. while (carry && size != 0)
  1172. {
  1173. // On carry inout[n] equals 0
  1174. carry = ! ++inout[size-1];
  1175. size--;
  1176. }
  1177. }
  1178. /// \brief Performs an addition with carry on a block of bytes
  1179. /// \param output the destination block of bytes
  1180. /// \param input the source block of bytes
  1181. /// \param size the size of the block
  1182. /// \details Performs an addition with carry on a block of bytes starting at the least significant
  1183. /// byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.
  1184. /// \details The function is close to near-constant time because it operates on all the bytes in the blocks.
  1185. inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size)
  1186. {
  1187. CRYPTOPP_ASSERT(output != NULLPTR);
  1188. CRYPTOPP_ASSERT(input != NULLPTR);
  1189. unsigned int carry=1;
  1190. while (carry && size != 0)
  1191. {
  1192. // On carry output[n] equals 0
  1193. carry = ! (output[size-1] = input[size-1] + 1);
  1194. size--;
  1195. }
  1196. while (size != 0)
  1197. {
  1198. output[size-1] = input[size-1];
  1199. size--;
  1200. }
  1201. }
  1202. /// \brief Performs a branch-less swap of values a and b if condition c is true
  1203. /// \tparam T class or type
  1204. /// \param c the condition to perform the swap
  1205. /// \param a the first value
  1206. /// \param b the second value
  1207. template <class T>
  1208. inline void ConditionalSwap(bool c, T &a, T &b)
  1209. {
  1210. T t = c * (a ^ b);
  1211. a ^= t;
  1212. b ^= t;
  1213. }
  1214. /// \brief Performs a branch-less swap of pointers a and b if condition c is true
  1215. /// \tparam T class or type
  1216. /// \param c the condition to perform the swap
  1217. /// \param a the first pointer
  1218. /// \param b the second pointer
  1219. template <class T>
  1220. inline void ConditionalSwapPointers(bool c, T &a, T &b)
  1221. {
  1222. ptrdiff_t t = size_t(c) * (a - b);
  1223. a -= t;
  1224. b += t;
  1225. }
  1226. // see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html
  1227. // and http://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data
  1228. /// \brief Sets each element of an array to 0
  1229. /// \tparam T class or type
  1230. /// \param buf an array of elements
  1231. /// \param n the number of elements in the array
  1232. /// \details The operation performs a wipe or zeroization. The function
  1233. /// attempts to survive optimizations and dead code removal.
  1234. template <class T>
  1235. void SecureWipeBuffer(T *buf, size_t n)
  1236. {
  1237. // GCC 4.3.2 on Cygwin optimizes away the first store if this
  1238. // loop is done in the forward direction
  1239. volatile T *p = buf+n;
  1240. while (n--)
  1241. *(--p) = 0;
  1242. }
  1243. #if !defined(CRYPTOPP_DISABLE_ASM) && \
  1244. (_MSC_VER >= 1400 || defined(__GNUC__)) && \
  1245. (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86)
  1246. /// \brief Sets each byte of an array to 0
  1247. /// \param buf an array of bytes
  1248. /// \param n the number of elements in the array
  1249. /// \details The operation performs a wipe or zeroization. The function
  1250. /// attempts to survive optimizations and dead code removal.
  1251. template<> inline void SecureWipeBuffer(byte *buf, size_t n)
  1252. {
  1253. volatile byte *p = buf;
  1254. #ifdef __GNUC__
  1255. asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  1256. #else
  1257. __stosb(reinterpret_cast<byte *>(reinterpret_cast<size_t>(p)), 0, n);
  1258. #endif
  1259. }
  1260. /// \brief Sets each 16-bit element of an array to 0
  1261. /// \param buf an array of 16-bit words
  1262. /// \param n the number of elements in the array
  1263. /// \details The operation performs a wipe or zeroization. The function
  1264. /// attempts to survive optimizations and dead code removal.
  1265. template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
  1266. {
  1267. volatile word16 *p = buf;
  1268. #ifdef __GNUC__
  1269. asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  1270. #else
  1271. __stosw(reinterpret_cast<word16 *>(reinterpret_cast<size_t>(p)), 0, n);
  1272. #endif
  1273. }
  1274. /// \brief Sets each 32-bit element of an array to 0
  1275. /// \param buf an array of 32-bit words
  1276. /// \param n the number of elements in the array
  1277. /// \details The operation performs a wipe or zeroization. The function
  1278. /// attempts to survive optimizations and dead code removal.
  1279. template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
  1280. {
  1281. volatile word32 *p = buf;
  1282. #ifdef __GNUC__
  1283. asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  1284. #else
  1285. __stosd(reinterpret_cast<unsigned long *>(reinterpret_cast<size_t>(p)), 0, n);
  1286. #endif
  1287. }
  1288. /// \brief Sets each 64-bit element of an array to 0
  1289. /// \param buf an array of 64-bit words
  1290. /// \param n the number of elements in the array
  1291. /// \details The operation performs a wipe or zeroization. The function
  1292. /// attempts to survive optimizations and dead code removal.
  1293. template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
  1294. {
  1295. #if CRYPTOPP_BOOL_X64
  1296. volatile word64 *p = buf;
  1297. # ifdef __GNUC__
  1298. asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory");
  1299. # else
  1300. __stosq(const_cast<word64 *>(p), 0, n);
  1301. # endif
  1302. #else
  1303. SecureWipeBuffer(reinterpret_cast<word32 *>(buf), 2*n);
  1304. #endif
  1305. }
  1306. #endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86
  1307. #if !defined(CRYPTOPP_DISABLE_ASM) && (_MSC_VER >= 1700) && defined(_M_ARM)
  1308. template<> inline void SecureWipeBuffer(byte *buf, size_t n)
  1309. {
  1310. char *p = reinterpret_cast<char*>(buf+n);
  1311. while (n--)
  1312. __iso_volatile_store8(--p, 0);
  1313. }
  1314. template<> inline void SecureWipeBuffer(word16 *buf, size_t n)
  1315. {
  1316. short *p = reinterpret_cast<short*>(buf+n);
  1317. while (n--)
  1318. __iso_volatile_store16(--p, 0);
  1319. }
  1320. template<> inline void SecureWipeBuffer(word32 *buf, size_t n)
  1321. {
  1322. int *p = reinterpret_cast<int*>(buf+n);
  1323. while (n--)
  1324. __iso_volatile_store32(--p, 0);
  1325. }
  1326. template<> inline void SecureWipeBuffer(word64 *buf, size_t n)
  1327. {
  1328. __int64 *p = reinterpret_cast<__int64*>(buf+n);
  1329. while (n--)
  1330. __iso_volatile_store64(--p, 0);
  1331. }
  1332. #endif
  1333. /// \brief Sets each element of an array to 0
  1334. /// \tparam T class or type
  1335. /// \param buf an array of elements
  1336. /// \param n the number of elements in the array
  1337. /// \details The operation performs a wipe or zeroization. The function
  1338. /// attempts to survive optimizations and dead code removal.
  1339. template <class T>
  1340. inline void SecureWipeArray(T *buf, size_t n)
  1341. {
  1342. if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0)
  1343. SecureWipeBuffer(reinterpret_cast<word64 *>(static_cast<void *>(buf)), n * (sizeof(T)/8));
  1344. else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0)
  1345. SecureWipeBuffer(reinterpret_cast<word32 *>(static_cast<void *>(buf)), n * (sizeof(T)/4));
  1346. else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0)
  1347. SecureWipeBuffer(reinterpret_cast<word16 *>(static_cast<void *>(buf)), n * (sizeof(T)/2));
  1348. else
  1349. SecureWipeBuffer(reinterpret_cast<byte *>(static_cast<void *>(buf)), n * sizeof(T));
  1350. }
  1351. /// \brief Converts a wide character C-string to a multibyte string
  1352. /// \param str C-string consisting of wide characters
  1353. /// \param throwOnError flag indicating the function should throw on error
  1354. /// \return str converted to a multibyte string or an empty string.
  1355. /// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under
  1356. /// the executing thread's locale. A locale must be set before using this function, and it can be
  1357. /// set with std::setlocale() if needed. Upon success, the converted string is returned.
  1358. /// \details Upon failure with throwOnError as false, the function returns an empty string. If
  1359. /// throwOnError as true, the function throws an InvalidArgument() exception.
  1360. /// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8
  1361. /// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available,
  1362. /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
  1363. std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
  1364. /// \brief Converts a multibyte C-string to a wide character string
  1365. /// \param str C-string consisting of wide characters
  1366. /// \param throwOnError flag indicating the function should throw on error
  1367. /// \return str converted to a multibyte string or an empty string.
  1368. /// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under
  1369. /// the executing thread's locale. A locale must be set before using this function, and it can be
  1370. /// set with std::setlocale() if needed. Upon success, the converted string is returned.
  1371. /// \details Upon failure with throwOnError as false, the function returns an empty string. If
  1372. /// throwOnError as true, the function throws an InvalidArgument() exception.
  1373. /// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8)
  1374. /// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available,
  1375. /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.
  1376. std::wstring StringWiden(const char *str, bool throwOnError = true);
  1377. // ************** rotate functions ***************
  1378. /// \brief Performs a left rotate
  1379. /// \tparam R the number of bit positions to rotate the value
  1380. /// \tparam T the word type
  1381. /// \param x the value to rotate
  1382. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1383. /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1384. /// Use rotlMod if the rotate amount R is outside the range.
  1385. /// \details Use rotlConstant when the rotate amount is constant. The template function was added
  1386. /// because Clang did not propagate the constant when passed as a function parameter. Clang's
  1387. /// need for a constexpr meant rotlFixed failed to compile on occasion.
  1388. /// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1389. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1390. /// counterparts.
  1391. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1392. /// \since Crypto++ 6.0
  1393. template <unsigned int R, class T> inline T rotlConstant(T x)
  1394. {
  1395. // Portable rotate that reduces to single instruction...
  1396. // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1397. // http://software.intel.com/en-us/forums/topic/580884
  1398. // and http://llvm.org/bugs/show_bug.cgi?id=24226
  1399. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1400. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1401. CRYPTOPP_ASSERT(static_cast<int>(R) < THIS_SIZE);
  1402. return T((x<<R)|(x>>(-R&MASK)));
  1403. }
  1404. /// \brief Performs a right rotate
  1405. /// \tparam R the number of bit positions to rotate the value
  1406. /// \tparam T the word type
  1407. /// \param x the value to rotate
  1408. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1409. /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1410. /// Use rotrMod if the rotate amount R is outside the range.
  1411. /// \details Use rotrConstant when the rotate amount is constant. The template function was added
  1412. /// because Clang did not propagate the constant when passed as a function parameter. Clang's
  1413. /// need for a constexpr meant rotrFixed failed to compile on occasion.
  1414. /// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1415. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1416. /// counterparts.
  1417. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1418. template <unsigned int R, class T> inline T rotrConstant(T x)
  1419. {
  1420. // Portable rotate that reduces to single instruction...
  1421. // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1422. // http://software.intel.com/en-us/forums/topic/580884
  1423. // and http://llvm.org/bugs/show_bug.cgi?id=24226
  1424. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1425. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1426. CRYPTOPP_ASSERT(static_cast<int>(R) < THIS_SIZE);
  1427. return T((x >> R)|(x<<(-R&MASK)));
  1428. }
  1429. /// \brief Performs a left rotate
  1430. /// \tparam T the word type
  1431. /// \param x the value to rotate
  1432. /// \param y the number of bit positions to rotate the value
  1433. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1434. /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1435. /// Use rotlMod if the rotate amount y is outside the range.
  1436. /// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1437. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1438. /// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a
  1439. /// template parameter.
  1440. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1441. /// \since Crypto++ 6.0
  1442. template <class T> inline T rotlFixed(T x, unsigned int y)
  1443. {
  1444. // Portable rotate that reduces to single instruction...
  1445. // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1446. // http://software.intel.com/en-us/forums/topic/580884
  1447. // and http://llvm.org/bugs/show_bug.cgi?id=24226
  1448. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1449. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1450. CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE);
  1451. return T((x<<y)|(x>>(-y&MASK)));
  1452. }
  1453. /// \brief Performs a right rotate
  1454. /// \tparam T the word type
  1455. /// \param x the value to rotate
  1456. /// \param y the number of bit positions to rotate the value
  1457. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1458. /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1459. /// Use rotrMod if the rotate amount y is outside the range.
  1460. /// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1461. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1462. /// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a
  1463. /// template parameter.
  1464. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1465. /// \since Crypto++ 3.0
  1466. template <class T> inline T rotrFixed(T x, unsigned int y)
  1467. {
  1468. // Portable rotate that reduces to single instruction...
  1469. // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157,
  1470. // http://software.intel.com/en-us/forums/topic/580884
  1471. // and http://llvm.org/bugs/show_bug.cgi?id=24226
  1472. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1473. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1474. CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE);
  1475. return T((x >> y)|(x<<(-y&MASK)));
  1476. }
  1477. /// \brief Performs a left rotate
  1478. /// \tparam T the word type
  1479. /// \param x the value to rotate
  1480. /// \param y the number of bit positions to rotate the value
  1481. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1482. /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1483. /// Use rotlMod if the rotate amount y is outside the range.
  1484. /// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1485. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1486. /// counterparts.
  1487. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1488. /// \since Crypto++ 3.0
  1489. template <class T> inline T rotlVariable(T x, unsigned int y)
  1490. {
  1491. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1492. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1493. CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE);
  1494. return T((x<<y)|(x>>(-y&MASK)));
  1495. }
  1496. /// \brief Performs a right rotate
  1497. /// \tparam T the word type
  1498. /// \param x the value to rotate
  1499. /// \param y the number of bit positions to rotate the value
  1500. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1501. /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1502. /// Use rotrMod if the rotate amount y is outside the range.
  1503. /// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster
  1504. /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register
  1505. /// counterparts.
  1506. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1507. /// \since Crypto++ 3.0
  1508. template <class T> inline T rotrVariable(T x, unsigned int y)
  1509. {
  1510. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1511. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1512. CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE);
  1513. return T((x>>y)|(x<<(-y&MASK)));
  1514. }
  1515. /// \brief Performs a left rotate
  1516. /// \tparam T the word type
  1517. /// \param x the value to rotate
  1518. /// \param y the number of bit positions to rotate the value
  1519. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1520. /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1521. /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
  1522. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1523. /// \since Crypto++ 3.0
  1524. template <class T> inline T rotlMod(T x, unsigned int y)
  1525. {
  1526. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1527. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1528. return T((x<<(y&MASK))|(x>>(-y&MASK)));
  1529. }
  1530. /// \brief Performs a right rotate
  1531. /// \tparam T the word type
  1532. /// \param x the value to rotate
  1533. /// \param y the number of bit positions to rotate the value
  1534. /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.
  1535. /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1536. /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>.
  1537. /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
  1538. /// \since Crypto++ 3.0
  1539. template <class T> inline T rotrMod(T x, unsigned int y)
  1540. {
  1541. CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8);
  1542. CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1);
  1543. return T((x>>(y&MASK))|(x<<(-y&MASK)));
  1544. }
  1545. #ifdef _MSC_VER
  1546. /// \brief Performs a left rotate
  1547. /// \tparam T the word type
  1548. /// \param x the 32-bit value to rotate
  1549. /// \param y the number of bit positions to rotate the value
  1550. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1551. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1552. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1553. /// \note rotlFixed will assert in Debug builds if is outside the allowed range.
  1554. /// \since Crypto++ 3.0
  1555. template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
  1556. {
  1557. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1558. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1559. return y ? _lrotl(x, static_cast<byte>(y)) : x;
  1560. }
  1561. /// \brief Performs a right rotate
  1562. /// \tparam T the word type
  1563. /// \param x the 32-bit value to rotate
  1564. /// \param y the number of bit positions to rotate the value
  1565. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1566. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1567. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1568. /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1569. /// \since Crypto++ 3.0
  1570. template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
  1571. {
  1572. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1573. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1574. return y ? _lrotr(x, static_cast<byte>(y)) : x;
  1575. }
  1576. /// \brief Performs a left rotate
  1577. /// \tparam T the word type
  1578. /// \param x the 32-bit value to rotate
  1579. /// \param y the number of bit positions to rotate the value
  1580. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1581. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1582. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1583. /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
  1584. /// \since Crypto++ 3.0
  1585. template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
  1586. {
  1587. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1588. return _lrotl(x, static_cast<byte>(y));
  1589. }
  1590. /// \brief Performs a right rotate
  1591. /// \tparam T the word type
  1592. /// \param x the 32-bit value to rotate
  1593. /// \param y the number of bit positions to rotate the value
  1594. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1595. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1596. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1597. /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
  1598. /// \since Crypto++ 3.0
  1599. template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
  1600. {
  1601. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1602. return _lrotr(x, static_cast<byte>(y));
  1603. }
  1604. /// \brief Performs a left rotate
  1605. /// \tparam T the word type
  1606. /// \param x the 32-bit value to rotate
  1607. /// \param y the number of bit positions to rotate the value
  1608. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1609. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1610. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1611. /// \since Crypto++ 3.0
  1612. template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
  1613. {
  1614. y %= 8*sizeof(x);
  1615. return _lrotl(x, static_cast<byte>(y));
  1616. }
  1617. /// \brief Performs a right rotate
  1618. /// \tparam T the word type
  1619. /// \param x the 32-bit value to rotate
  1620. /// \param y the number of bit positions to rotate the value
  1621. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1622. /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range
  1623. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1624. /// \since Crypto++ 3.0
  1625. template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
  1626. {
  1627. y %= 8*sizeof(x);
  1628. return _lrotr(x, static_cast<byte>(y));
  1629. }
  1630. #endif // #ifdef _MSC_VER
  1631. #if (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
  1632. // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions
  1633. /// \brief Performs a left rotate
  1634. /// \tparam T the word type
  1635. /// \param x the 64-bit value to rotate
  1636. /// \param y the number of bit positions to rotate the value
  1637. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1638. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1639. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1640. /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1641. /// \since Crypto++ 3.0
  1642. template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y)
  1643. {
  1644. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1645. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1646. return y ? _rotl64(x, static_cast<byte>(y)) : x;
  1647. }
  1648. /// \brief Performs a right rotate
  1649. /// \tparam T the word type
  1650. /// \param x the 64-bit value to rotate
  1651. /// \param y the number of bit positions to rotate the value
  1652. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1653. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1654. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1655. /// \note rotrFixed will assert in Debug builds if is outside the allowed range.
  1656. /// \since Crypto++ 3.0
  1657. template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y)
  1658. {
  1659. // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules.
  1660. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1661. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1662. }
  1663. /// \brief Performs a left rotate
  1664. /// \tparam T the word type
  1665. /// \param x the 64-bit value to rotate
  1666. /// \param y the number of bit positions to rotate the value
  1667. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1668. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1669. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1670. /// \note rotlVariable will assert in Debug builds if is outside the allowed range.
  1671. /// \since Crypto++ 3.0
  1672. template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y)
  1673. {
  1674. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1675. return _rotl64(x, static_cast<byte>(y));
  1676. }
  1677. /// \brief Performs a right rotate
  1678. /// \tparam T the word type
  1679. /// \param x the 64-bit value to rotate
  1680. /// \param y the number of bit positions to rotate the value
  1681. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1682. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1683. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1684. /// \note rotrVariable will assert in Debug builds if is outside the allowed range.
  1685. /// \since Crypto++ 3.0
  1686. template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y)
  1687. {
  1688. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1689. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1690. }
  1691. /// \brief Performs a left rotate
  1692. /// \tparam T the word type
  1693. /// \param x the 64-bit value to rotate
  1694. /// \param y the number of bit positions to rotate the value
  1695. /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by
  1696. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1697. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1698. /// \since Crypto++ 3.0
  1699. template<> inline word64 rotlMod<word64>(word64 x, unsigned int y)
  1700. {
  1701. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1702. return y ? _rotl64(x, static_cast<byte>(y)) : x;
  1703. }
  1704. /// \brief Performs a right rotate
  1705. /// \tparam T the word type
  1706. /// \param x the 64-bit value to rotate
  1707. /// \param y the number of bit positions to rotate the value
  1708. /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by
  1709. /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range
  1710. /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior.
  1711. /// \since Crypto++ 3.0
  1712. template<> inline word64 rotrMod<word64>(word64 x, unsigned int y)
  1713. {
  1714. CRYPTOPP_ASSERT(y < 8*sizeof(x));
  1715. return y ? _rotr64(x, static_cast<byte>(y)) : x;
  1716. }
  1717. #endif // #if _MSC_VER >= 1310
  1718. #if _MSC_VER >= 1400 && !defined(__INTEL_COMPILER)
  1719. // Intel C++ Compiler 10.0 gives undefined externals with these
  1720. template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y)
  1721. {
  1722. // Intrinsic, not bound to C/C++ language rules.
  1723. return _rotl16(x, static_cast<byte>(y));
  1724. }
  1725. template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y)
  1726. {
  1727. // Intrinsic, not bound to C/C++ language rules.
  1728. return _rotr16(x, static_cast<byte>(y));
  1729. }
  1730. template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y)
  1731. {
  1732. return _rotl16(x, static_cast<byte>(y));
  1733. }
  1734. template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y)
  1735. {
  1736. return _rotr16(x, static_cast<byte>(y));
  1737. }
  1738. template<> inline word16 rotlMod<word16>(word16 x, unsigned int y)
  1739. {
  1740. return _rotl16(x, static_cast<byte>(y));
  1741. }
  1742. template<> inline word16 rotrMod<word16>(word16 x, unsigned int y)
  1743. {
  1744. return _rotr16(x, static_cast<byte>(y));
  1745. }
  1746. template<> inline byte rotlFixed<byte>(byte x, unsigned int y)
  1747. {
  1748. // Intrinsic, not bound to C/C++ language rules.
  1749. return _rotl8(x, static_cast<byte>(y));
  1750. }
  1751. template<> inline byte rotrFixed<byte>(byte x, unsigned int y)
  1752. {
  1753. // Intrinsic, not bound to C/C++ language rules.
  1754. return _rotr8(x, static_cast<byte>(y));
  1755. }
  1756. template<> inline byte rotlVariable<byte>(byte x, unsigned int y)
  1757. {
  1758. return _rotl8(x, static_cast<byte>(y));
  1759. }
  1760. template<> inline byte rotrVariable<byte>(byte x, unsigned int y)
  1761. {
  1762. return _rotr8(x, static_cast<byte>(y));
  1763. }
  1764. template<> inline byte rotlMod<byte>(byte x, unsigned int y)
  1765. {
  1766. return _rotl8(x, static_cast<byte>(y));
  1767. }
  1768. template<> inline byte rotrMod<byte>(byte x, unsigned int y)
  1769. {
  1770. return _rotr8(x, static_cast<byte>(y));
  1771. }
  1772. #endif // #if _MSC_VER >= 1400
  1773. #if (defined(__MWERKS__) && TARGET_CPU_PPC)
  1774. template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y)
  1775. {
  1776. CRYPTOPP_ASSERT(y < 32);
  1777. return y ? __rlwinm(x,y,0,31) : x;
  1778. }
  1779. template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y)
  1780. {
  1781. CRYPTOPP_ASSERT(y < 32);
  1782. return y ? __rlwinm(x,32-y,0,31) : x;
  1783. }
  1784. template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y)
  1785. {
  1786. CRYPTOPP_ASSERT(y < 32);
  1787. return (__rlwnm(x,y,0,31));
  1788. }
  1789. template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y)
  1790. {
  1791. CRYPTOPP_ASSERT(y < 32);
  1792. return (__rlwnm(x,32-y,0,31));
  1793. }
  1794. template<> inline word32 rotlMod<word32>(word32 x, unsigned int y)
  1795. {
  1796. return (__rlwnm(x,y,0,31));
  1797. }
  1798. template<> inline word32 rotrMod<word32>(word32 x, unsigned int y)
  1799. {
  1800. return (__rlwnm(x,32-y,0,31));
  1801. }
  1802. #endif // __MWERKS__ && TARGET_CPU_PPC
  1803. // ************** endian reversal ***************
  1804. /// \brief Gets a byte from a value
  1805. /// \param order the ByteOrder of the value
  1806. /// \param value the value to retrieve the byte
  1807. /// \param index the location of the byte to retrieve
  1808. template <class T>
  1809. inline unsigned int GetByte(ByteOrder order, T value, unsigned int index)
  1810. {
  1811. if (order == LITTLE_ENDIAN_ORDER)
  1812. return GETBYTE(value, index);
  1813. else
  1814. return GETBYTE(value, sizeof(T)-index-1);
  1815. }
  1816. /// \brief Reverses bytes in a 8-bit value
  1817. /// \param value the 8-bit value to reverse
  1818. /// \note ByteReverse returns the value passed to it since there is nothing to
  1819. /// reverse.
  1820. inline byte ByteReverse(byte value)
  1821. {
  1822. return value;
  1823. }
  1824. /// \brief Reverses bytes in a 16-bit value
  1825. /// \param value the 16-bit value to reverse
  1826. /// \details ByteReverse calls bswap if available. Otherwise the function
  1827. /// performs a 8-bit rotate on the word16.
  1828. inline word16 ByteReverse(word16 value)
  1829. {
  1830. #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
  1831. return bswap_16(value);
  1832. #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
  1833. return _byteswap_ushort(value);
  1834. #else
  1835. return rotlFixed(value, 8U);
  1836. #endif
  1837. }
  1838. /// \brief Reverses bytes in a 32-bit value
  1839. /// \param value the 32-bit value to reverse
  1840. /// \details ByteReverse calls bswap if available. Otherwise the function uses
  1841. /// a combination of rotates on the word32.
  1842. inline word32 ByteReverse(word32 value)
  1843. {
  1844. #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
  1845. return bswap_32(value);
  1846. #elif defined(CRYPTOPP_ARM_BYTEREV_AVAILABLE)
  1847. word32 rvalue;
  1848. __asm__ ("rev %0, %1" : "=r" (rvalue) : "r" (value));
  1849. return rvalue;
  1850. #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE)
  1851. __asm__ ("bswap %0" : "=r" (value) : "0" (value));
  1852. return value;
  1853. #elif defined(__MWERKS__) && TARGET_CPU_PPC
  1854. return (word32)__lwbrx(&value,0);
  1855. #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
  1856. return _byteswap_ulong(value);
  1857. #elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__)
  1858. // 5 instructions with rotate instruction, 9 without
  1859. return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff);
  1860. #else
  1861. // 6 instructions with rotate instruction, 8 without
  1862. value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8);
  1863. return rotlFixed(value, 16U);
  1864. #endif
  1865. }
  1866. /// \brief Reverses bytes in a 64-bit value
  1867. /// \param value the 64-bit value to reverse
  1868. /// \details ByteReverse calls bswap if available. Otherwise the function uses
  1869. /// a combination of rotates on the word64.
  1870. inline word64 ByteReverse(word64 value)
  1871. {
  1872. #if defined(CRYPTOPP_BYTESWAP_AVAILABLE)
  1873. return bswap_64(value);
  1874. #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__)
  1875. __asm__ ("bswap %0" : "=r" (value) : "0" (value));
  1876. return value;
  1877. #elif (_MSC_VER >= 1400) || (defined(_MSC_VER) && !defined(_DLL))
  1878. return _byteswap_uint64(value);
  1879. #elif CRYPTOPP_BOOL_SLOW_WORD64
  1880. return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32));
  1881. #else
  1882. value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8);
  1883. value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16);
  1884. return rotlFixed(value, 32U);
  1885. #endif
  1886. }
  1887. #if defined(CRYPTOPP_WORD128_AVAILABLE)
  1888. /// \brief Reverses bytes in a 128-bit value
  1889. /// \param value the 128-bit value to reverse
  1890. /// \details ByteReverse calls bswap if available. Otherwise the function uses
  1891. /// a combination of rotates on the word128.
  1892. /// \note word128 is available on some 64-bit platforms when the compiler supports it.
  1893. /// \since Crypto++ 8.7
  1894. inline word128 ByteReverse(word128 value)
  1895. {
  1896. // TODO: speed this up
  1897. return (word128(ByteReverse(word64(value))) << 64) | ByteReverse(word64(value>>64));
  1898. }
  1899. #endif
  1900. /// \brief Reverses bits in a 8-bit value
  1901. /// \param value the 8-bit value to reverse
  1902. /// \details BitReverse performs a combination of shifts on the byte.
  1903. inline byte BitReverse(byte value)
  1904. {
  1905. value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1);
  1906. value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2);
  1907. return rotlFixed(value, 4U);
  1908. }
  1909. /// \brief Reverses bits in a 16-bit value
  1910. /// \param value the 16-bit value to reverse
  1911. /// \details BitReverse performs a combination of shifts on the word16.
  1912. inline word16 BitReverse(word16 value)
  1913. {
  1914. #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE)
  1915. // 4 instructions on ARM.
  1916. word32 rvalue;
  1917. __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value));
  1918. return word16(rvalue >> 16);
  1919. #else
  1920. // 15 instructions on ARM.
  1921. value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1);
  1922. value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2);
  1923. value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4);
  1924. return ByteReverse(value);
  1925. #endif
  1926. }
  1927. /// \brief Reverses bits in a 32-bit value
  1928. /// \param value the 32-bit value to reverse
  1929. /// \details BitReverse performs a combination of shifts on the word32.
  1930. inline word32 BitReverse(word32 value)
  1931. {
  1932. #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE)
  1933. // 2 instructions on ARM.
  1934. word32 rvalue;
  1935. __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value));
  1936. return rvalue;
  1937. #else
  1938. // 19 instructions on ARM.
  1939. value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1);
  1940. value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2);
  1941. value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4);
  1942. return ByteReverse(value);
  1943. #endif
  1944. }
  1945. /// \brief Reverses bits in a 64-bit value
  1946. /// \param value the 64-bit value to reverse
  1947. /// \details BitReverse performs a combination of shifts on the word64.
  1948. inline word64 BitReverse(word64 value)
  1949. {
  1950. #if CRYPTOPP_BOOL_SLOW_WORD64
  1951. return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32));
  1952. #else
  1953. value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1);
  1954. value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2);
  1955. value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4);
  1956. return ByteReverse(value);
  1957. #endif
  1958. }
  1959. /// \brief Reverses bits in a value
  1960. /// \param value the value to reverse
  1961. /// \details The template overload of BitReverse operates on signed and unsigned values.
  1962. /// Internally the size of T is checked, and then value is cast to a byte,
  1963. /// word16, word32 or word64. After the cast, the appropriate BitReverse
  1964. /// overload is called.
  1965. /// \note word128 is available on some 64-bit platforms when the compiler supports it.
  1966. /// \since Crypto++ 1.0, word128 since Crypto++ 8.7
  1967. template <class T>
  1968. inline T BitReverse(T value)
  1969. {
  1970. if (sizeof(T) == 1)
  1971. return (T)BitReverse((byte)value);
  1972. else if (sizeof(T) == 2)
  1973. return (T)BitReverse((word16)value);
  1974. else if (sizeof(T) == 4)
  1975. return (T)BitReverse((word32)value);
  1976. else if (sizeof(T) == 8)
  1977. return (T)BitReverse((word64)value);
  1978. #if defined(CRYPTOPP_WORD128_AVAILABLE)
  1979. else if (sizeof(T) == 16)
  1980. return (T)BitReverse((word128)value);
  1981. #endif
  1982. else
  1983. {
  1984. CRYPTOPP_ASSERT(0);
  1985. return (T)BitReverse((word64)value);
  1986. }
  1987. }
  1988. /// \brief Reverses bytes in a value depending upon endianness
  1989. /// \tparam T the class or type
  1990. /// \param order the ByteOrder of the data
  1991. /// \param value the value to conditionally reverse
  1992. /// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs.
  1993. /// If order matches native byte order, then the original value is returned.
  1994. /// If not, then ByteReverse is called on the value before returning to the caller.
  1995. template <class T>
  1996. inline T ConditionalByteReverse(ByteOrder order, T value)
  1997. {
  1998. return NativeByteOrderIs(order) ? value : ByteReverse(value);
  1999. }
  2000. /// \brief Reverses bytes in an element from an array of elements
  2001. /// \tparam T the class or type
  2002. /// \param out the output array of elements
  2003. /// \param in the input array of elements
  2004. /// \param byteCount the total number of bytes in the array
  2005. /// \details Internally, ByteReverse visits each element in the in array
  2006. /// calls ByteReverse on it, and writes the result to out.
  2007. /// \details ByteReverse does not process tail byes, or bytes that are
  2008. /// not part of a full element. If T is int (and int is 4 bytes), then
  2009. /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
  2010. /// reversed.
  2011. /// \details The following program should help illustrate the behavior.
  2012. /// <pre>vector<word32> v1, v2;
  2013. ///
  2014. /// v1.push_back(1);
  2015. /// v1.push_back(2);
  2016. /// v1.push_back(3);
  2017. /// v1.push_back(4);
  2018. ///
  2019. /// v2.resize(v1.size());
  2020. /// ByteReverse<word32>(&v2[0], &v1[0], 16);
  2021. ///
  2022. /// cout << "V1: ";
  2023. /// for(unsigned int i = 0; i < v1.size(); i++)
  2024. /// cout << std::hex << v1[i] << " ";
  2025. /// cout << endl;
  2026. ///
  2027. /// cout << "V2: ";
  2028. /// for(unsigned int i = 0; i < v2.size(); i++)
  2029. /// cout << std::hex << v2[i] << " ";
  2030. /// cout << endl;</pre>
  2031. /// The program above results in the following output.
  2032. /// <pre>V1: 00000001 00000002 00000003 00000004
  2033. /// V2: 01000000 02000000 03000000 04000000</pre>
  2034. /// \sa ConditionalByteReverse
  2035. template <class T>
  2036. void ByteReverse(T *out, const T *in, size_t byteCount)
  2037. {
  2038. // Alignment check due to Issues 690
  2039. CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0);
  2040. CRYPTOPP_ASSERT(IsAligned<T>(in));
  2041. CRYPTOPP_ASSERT(IsAligned<T>(out));
  2042. size_t count = byteCount/sizeof(T);
  2043. for (size_t i=0; i<count; i++)
  2044. out[i] = ByteReverse(in[i]);
  2045. }
  2046. /// \brief Conditionally reverses bytes in an element from an array of elements
  2047. /// \tparam T the class or type
  2048. /// \param order the ByteOrder of the data
  2049. /// \param out the output array of elements
  2050. /// \param in the input array of elements
  2051. /// \param byteCount the byte count of the arrays
  2052. /// \details ConditionalByteReverse visits each element in the in array
  2053. /// calls ByteReverse on it depending on the desired endianness, and writes the result to out.
  2054. /// \details ByteReverse does not process tail byes, or bytes that are
  2055. /// not part of a full element. If T is int (and int is 4 bytes), then
  2056. /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are
  2057. /// reversed.
  2058. /// \sa ByteReverse
  2059. template <class T>
  2060. inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount)
  2061. {
  2062. if (!NativeByteOrderIs(order))
  2063. ByteReverse(out, in, byteCount);
  2064. else if (in != out)
  2065. memcpy_s(out, byteCount, in, byteCount);
  2066. }
  2067. /// \brief Copy bytes in a buffer to an array of elements in big-endian order
  2068. /// \tparam T the class or type
  2069. /// \param order the ByteOrder of the data
  2070. /// \param out the output array of elements
  2071. /// \param outlen the byte count of the array
  2072. /// \param in the input array of elements
  2073. /// \param inlen the byte count of the array
  2074. template <class T>
  2075. inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
  2076. {
  2077. const size_t U = sizeof(T);
  2078. CRYPTOPP_ASSERT(inlen <= outlen*U);
  2079. memcpy_s(out, outlen*U, in, inlen);
  2080. memset_z((byte *)out+inlen, 0, outlen*U-inlen);
  2081. ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U));
  2082. }
  2083. /// \brief Retrieve a byte from an unaligned buffer
  2084. /// \param order the ByteOrder of the data
  2085. /// \param block an unaligned buffer
  2086. /// \param unused dummy parameter
  2087. /// \return byte value
  2088. /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a byte value.
  2089. /// \since Crypto++ 1.0
  2090. inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *unused)
  2091. {
  2092. CRYPTOPP_UNUSED(order); CRYPTOPP_UNUSED(unused);
  2093. return block[0];
  2094. }
  2095. /// \brief Retrieve a word16 from an unaligned buffer
  2096. /// \param order the ByteOrder of the data
  2097. /// \param block an unaligned buffer
  2098. /// \param unused dummy parameter
  2099. /// \return byte value
  2100. /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word16 value.
  2101. /// \since Crypto++ 1.0
  2102. inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *unused)
  2103. {
  2104. CRYPTOPP_UNUSED(unused);
  2105. return (order == BIG_ENDIAN_ORDER)
  2106. ? block[1] | (block[0] << 8)
  2107. : block[0] | (block[1] << 8);
  2108. }
  2109. /// \brief Retrieve a word32 from an unaligned buffer
  2110. /// \param order the ByteOrder of the data
  2111. /// \param block an unaligned buffer
  2112. /// \param unused dummy parameter
  2113. /// \return byte value
  2114. /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word32 value.
  2115. /// \since Crypto++ 1.0
  2116. inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *unused)
  2117. {
  2118. CRYPTOPP_UNUSED(unused);
  2119. return (order == BIG_ENDIAN_ORDER)
  2120. ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24)
  2121. : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24);
  2122. }
  2123. /// \brief Retrieve a word64 from an unaligned buffer
  2124. /// \param order the ByteOrder of the data
  2125. /// \param block an unaligned buffer
  2126. /// \param unused dummy parameter
  2127. /// \return byte value
  2128. /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word64 value.
  2129. /// \since Crypto++ 1.0
  2130. inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *unused)
  2131. {
  2132. CRYPTOPP_UNUSED(unused);
  2133. return (order == BIG_ENDIAN_ORDER)
  2134. ?
  2135. (word64(block[7]) |
  2136. (word64(block[6]) << 8) |
  2137. (word64(block[5]) << 16) |
  2138. (word64(block[4]) << 24) |
  2139. (word64(block[3]) << 32) |
  2140. (word64(block[2]) << 40) |
  2141. (word64(block[1]) << 48) |
  2142. (word64(block[0]) << 56))
  2143. :
  2144. (word64(block[0]) |
  2145. (word64(block[1]) << 8) |
  2146. (word64(block[2]) << 16) |
  2147. (word64(block[3]) << 24) |
  2148. (word64(block[4]) << 32) |
  2149. (word64(block[5]) << 40) |
  2150. (word64(block[6]) << 48) |
  2151. (word64(block[7]) << 56));
  2152. }
  2153. #if defined(CRYPTOPP_WORD128_AVAILABLE)
  2154. /// \brief Retrieve a word128 from an unaligned buffer
  2155. /// \param order the ByteOrder of the data
  2156. /// \param block an unaligned buffer
  2157. /// \param unused dummy parameter
  2158. /// \return byte value
  2159. /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word128 value.
  2160. /// \note word128 is available on some 64-bit platforms when the compiler supports it.
  2161. /// \since Crypto++ 8.7
  2162. inline word128 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word128 *unused)
  2163. {
  2164. CRYPTOPP_UNUSED(unused);
  2165. return (order == BIG_ENDIAN_ORDER)
  2166. ?
  2167. (word128(block[15]) |
  2168. (word128(block[14]) << 8) |
  2169. (word128(block[13]) << 16) |
  2170. (word128(block[12]) << 24) |
  2171. (word128(block[11]) << 32) |
  2172. (word128(block[10]) << 40) |
  2173. (word128(block[ 9]) << 48) |
  2174. (word128(block[ 8]) << 56) |
  2175. (word128(block[ 7]) << 64) |
  2176. (word128(block[ 6]) << 72) |
  2177. (word128(block[ 5]) << 80) |
  2178. (word128(block[ 4]) << 88) |
  2179. (word128(block[ 3]) << 96) |
  2180. (word128(block[ 2]) << 104) |
  2181. (word128(block[ 1]) << 112) |
  2182. (word128(block[ 0]) << 120))
  2183. :
  2184. (word128(block[ 0]) |
  2185. (word128(block[ 1]) << 8) |
  2186. (word128(block[ 2]) << 16) |
  2187. (word128(block[ 3]) << 24) |
  2188. (word128(block[ 4]) << 32) |
  2189. (word128(block[ 5]) << 40) |
  2190. (word128(block[ 6]) << 48) |
  2191. (word128(block[ 7]) << 56) |
  2192. (word128(block[ 8]) << 64) |
  2193. (word128(block[ 9]) << 72) |
  2194. (word128(block[10]) << 80) |
  2195. (word128(block[11]) << 88) |
  2196. (word128(block[12]) << 96) |
  2197. (word128(block[13]) << 104) |
  2198. (word128(block[14]) << 112) |
  2199. (word128(block[15]) << 120));
  2200. }
  2201. #endif
  2202. /// \brief Write a byte to an unaligned buffer
  2203. /// \param order the ByteOrder of the data
  2204. /// \param block an unaligned output buffer
  2205. /// \param value byte value
  2206. /// \param xorBlock optional unaligned xor buffer
  2207. /// \details UnalignedbyteNonTemplate writes a byte value to an unaligned buffer.
  2208. /// \since Crypto++ 1.0
  2209. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock)
  2210. {
  2211. CRYPTOPP_UNUSED(order);
  2212. block[0] = static_cast<byte>(xorBlock ? (value ^ xorBlock[0]) : value);
  2213. }
  2214. /// \brief Write a word16 to an unaligned buffer
  2215. /// \param order the ByteOrder of the data
  2216. /// \param block an unaligned output buffer
  2217. /// \param value word16 value
  2218. /// \param xorBlock optional unaligned xor buffer
  2219. /// \details UnalignedbyteNonTemplate writes a word16 value to an unaligned buffer.
  2220. /// \since Crypto++ 1.0
  2221. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock)
  2222. {
  2223. if (order == BIG_ENDIAN_ORDER)
  2224. {
  2225. if (xorBlock)
  2226. {
  2227. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2228. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2229. }
  2230. else
  2231. {
  2232. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2233. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2234. }
  2235. }
  2236. else
  2237. {
  2238. if (xorBlock)
  2239. {
  2240. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2241. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2242. }
  2243. else
  2244. {
  2245. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2246. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2247. }
  2248. }
  2249. }
  2250. /// \brief Write a word32 to an unaligned buffer
  2251. /// \param order the ByteOrder of the data
  2252. /// \param block an unaligned output buffer
  2253. /// \param value word32 value
  2254. /// \param xorBlock optional unaligned xor buffer
  2255. /// \details UnalignedbyteNonTemplate writes a word32 value to an unaligned buffer.
  2256. /// \since Crypto++ 1.0
  2257. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock)
  2258. {
  2259. if (order == BIG_ENDIAN_ORDER)
  2260. {
  2261. if (xorBlock)
  2262. {
  2263. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2264. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2265. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2266. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2267. }
  2268. else
  2269. {
  2270. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2271. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2272. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2273. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2274. }
  2275. }
  2276. else
  2277. {
  2278. if (xorBlock)
  2279. {
  2280. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2281. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2282. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2283. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2284. }
  2285. else
  2286. {
  2287. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2288. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2289. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2290. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2291. }
  2292. }
  2293. }
  2294. /// \brief Write a word64 to an unaligned buffer
  2295. /// \param order the ByteOrder of the data
  2296. /// \param block an unaligned output buffer
  2297. /// \param value word64 value
  2298. /// \param xorBlock optional unaligned xor buffer
  2299. /// \details UnalignedbyteNonTemplate writes a word64 value to an unaligned buffer.
  2300. /// \since Crypto++ 1.0
  2301. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock)
  2302. {
  2303. if (order == BIG_ENDIAN_ORDER)
  2304. {
  2305. if (xorBlock)
  2306. {
  2307. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2308. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2309. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2310. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2311. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2312. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2313. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2314. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2315. }
  2316. else
  2317. {
  2318. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2319. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2320. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2321. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2322. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2323. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2324. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2325. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2326. }
  2327. }
  2328. else
  2329. {
  2330. if (xorBlock)
  2331. {
  2332. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2333. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2334. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2335. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2336. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2337. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2338. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2339. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2340. }
  2341. else
  2342. {
  2343. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2344. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2345. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2346. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2347. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2348. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2349. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2350. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2351. }
  2352. }
  2353. }
  2354. #if defined(CRYPTOPP_WORD128_AVAILABLE)
  2355. /// \brief Write a word128 to an unaligned buffer
  2356. /// \param order the ByteOrder of the data
  2357. /// \param block an unaligned output buffer
  2358. /// \param value word128 value
  2359. /// \param xorBlock optional unaligned xor buffer
  2360. /// \details UnalignedbyteNonTemplate writes a word128 value to an unaligned buffer.
  2361. /// \note word128 is available on some 64-bit platforms when the compiler supports it.
  2362. /// \since Crypto++ 8.7
  2363. inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word128 value, const byte *xorBlock)
  2364. {
  2365. if (order == BIG_ENDIAN_ORDER)
  2366. {
  2367. if (xorBlock)
  2368. {
  2369. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 15);
  2370. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 14);
  2371. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 13);
  2372. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 12);
  2373. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 11);
  2374. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 10);
  2375. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 9);
  2376. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 8);
  2377. block[ 8] = xorBlock[ 8] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2378. block[ 9] = xorBlock[ 9] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2379. block[10] = xorBlock[10] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2380. block[11] = xorBlock[11] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2381. block[12] = xorBlock[12] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2382. block[13] = xorBlock[13] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2383. block[14] = xorBlock[14] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2384. block[15] = xorBlock[15] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2385. }
  2386. else
  2387. {
  2388. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 15);
  2389. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 14);
  2390. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 13);
  2391. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 12);
  2392. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 11);
  2393. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 10);
  2394. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 9);
  2395. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 8);
  2396. block[ 8] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2397. block[ 9] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2398. block[10] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2399. block[11] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2400. block[12] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2401. block[13] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2402. block[14] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2403. block[15] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2404. }
  2405. }
  2406. else
  2407. {
  2408. if (xorBlock)
  2409. {
  2410. block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2411. block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2412. block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2413. block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2414. block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2415. block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2416. block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2417. block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2418. block[ 8] = xorBlock[ 8] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 8);
  2419. block[ 9] = xorBlock[ 9] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 9);
  2420. block[10] = xorBlock[10] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 10);
  2421. block[11] = xorBlock[11] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 11);
  2422. block[12] = xorBlock[12] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 12);
  2423. block[13] = xorBlock[13] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 13);
  2424. block[14] = xorBlock[14] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 14);
  2425. block[15] = xorBlock[15] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 15);
  2426. }
  2427. else
  2428. {
  2429. block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0);
  2430. block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1);
  2431. block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2);
  2432. block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3);
  2433. block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4);
  2434. block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5);
  2435. block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6);
  2436. block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7);
  2437. block[ 8] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 8);
  2438. block[ 9] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 9);
  2439. block[10] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 10);
  2440. block[11] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 11);
  2441. block[12] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 12);
  2442. block[13] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 13);
  2443. block[14] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 14);
  2444. block[15] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 15);
  2445. }
  2446. }
  2447. }
  2448. #endif
  2449. /// \brief Access a block of memory
  2450. /// \tparam T class or type
  2451. /// \param assumeAligned flag indicating alignment
  2452. /// \param order the ByteOrder of the data
  2453. /// \param block the byte buffer to be processed
  2454. /// \return the word in the specified byte order
  2455. /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
  2456. /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
  2457. /// LITTLE_ENDIAN_ORDER.
  2458. /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
  2459. /// will be <tt>0x03020100</tt>.
  2460. /// <pre>
  2461. /// word32 w;
  2462. /// byte buffer[4] = {0,1,2,3};
  2463. /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
  2464. /// </pre>
  2465. template <class T>
  2466. inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block)
  2467. {
  2468. CRYPTOPP_UNUSED(assumeAligned);
  2469. T temp = 0;
  2470. if (block != NULLPTR) {std::memcpy(&temp, block, sizeof(T));}
  2471. return ConditionalByteReverse(order, temp);
  2472. }
  2473. /// \brief Access a block of memory
  2474. /// \tparam T class or type
  2475. /// \param assumeAligned flag indicating alignment
  2476. /// \param order the ByteOrder of the data
  2477. /// \param result the word in the specified byte order
  2478. /// \param block the byte buffer to be processed
  2479. /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates
  2480. /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
  2481. /// LITTLE_ENDIAN_ORDER.
  2482. /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt>
  2483. /// will be <tt>0x03020100</tt>.
  2484. /// <pre>
  2485. /// word32 w;
  2486. /// byte buffer[4] = {0,1,2,3};
  2487. /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);
  2488. /// </pre>
  2489. template <class T>
  2490. inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block)
  2491. {
  2492. result = GetWord<T>(assumeAligned, order, block);
  2493. }
  2494. /// \brief Access a block of memory
  2495. /// \tparam T class or type
  2496. /// \param assumeAligned flag indicating alignment
  2497. /// \param order the ByteOrder of the data
  2498. /// \param block the destination byte buffer
  2499. /// \param value the word in the specified byte order
  2500. /// \param xorBlock an optional byte buffer to xor
  2501. /// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates
  2502. /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or
  2503. /// LITTLE_ENDIAN_ORDER.
  2504. template <class T>
  2505. inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR)
  2506. {
  2507. CRYPTOPP_UNUSED(assumeAligned);
  2508. T t1, t2;
  2509. t1 = ConditionalByteReverse(order, value);
  2510. if (xorBlock != NULLPTR) {std::memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;}
  2511. if (block != NULLPTR) {std::memcpy(block, &t1, sizeof(T));}
  2512. }
  2513. /// \brief Access a block of memory
  2514. /// \tparam T class or type
  2515. /// \tparam B enumeration indicating endianness
  2516. /// \tparam A flag indicating alignment
  2517. /// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is
  2518. /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
  2519. /// Repeatedly applying operator() results in advancing in the block of memory.
  2520. /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt>
  2521. /// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>.
  2522. /// <pre>
  2523. /// word32 w1, w2;
  2524. /// byte buffer[8] = {0,1,2,3,4,5,6,7};
  2525. /// GetBlock<word32, LittleEndian> block(buffer);
  2526. /// block(w1)(w2);
  2527. /// </pre>
  2528. template <class T, class B, bool A=false>
  2529. class GetBlock
  2530. {
  2531. public:
  2532. /// \brief Construct a GetBlock
  2533. /// \param block the memory block
  2534. GetBlock(const void *block)
  2535. : m_block((const byte *)block) {}
  2536. /// \brief Access a block of memory
  2537. /// \tparam U class or type
  2538. /// \param x the value to read
  2539. /// \return pointer to the remainder of the block after reading x
  2540. template <class U>
  2541. inline GetBlock<T, B, A> & operator()(U &x)
  2542. {
  2543. CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T));
  2544. x = GetWord<T>(A, B::ToEnum(), m_block);
  2545. m_block += sizeof(T);
  2546. return *this;
  2547. }
  2548. private:
  2549. const byte *m_block;
  2550. };
  2551. /// \brief Access a block of memory
  2552. /// \tparam T class or type
  2553. /// \tparam B enumeration indicating endianness
  2554. /// \tparam A flag indicating alignment
  2555. /// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is
  2556. /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
  2557. /// Repeatedly applying operator() results in advancing in the block of memory.
  2558. /// \details An example of writing two word32 values from a block of memory is shown below. After the code
  2559. /// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>.
  2560. /// <pre>
  2561. /// word32 w1=0x03020100, w2=0x07060504;
  2562. /// byte buffer[8];
  2563. /// PutBlock<word32, LittleEndian> block(NULLPTR, buffer);
  2564. /// block(w1)(w2);
  2565. /// </pre>
  2566. template <class T, class B, bool A=false>
  2567. class PutBlock
  2568. {
  2569. public:
  2570. /// \brief Construct a PutBlock
  2571. /// \param block the memory block
  2572. /// \param xorBlock optional mask
  2573. PutBlock(const void *xorBlock, void *block)
  2574. : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
  2575. /// \brief Access a block of memory
  2576. /// \tparam U class or type
  2577. /// \param x the value to write
  2578. /// \return pointer to the remainder of the block after writing x
  2579. template <class U>
  2580. inline PutBlock<T, B, A> & operator()(U x)
  2581. {
  2582. PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock);
  2583. m_block += sizeof(T);
  2584. if (m_xorBlock)
  2585. m_xorBlock += sizeof(T);
  2586. return *this;
  2587. }
  2588. private:
  2589. const byte *m_xorBlock;
  2590. byte *m_block;
  2591. };
  2592. /// \brief Access a block of memory
  2593. /// \tparam T class or type
  2594. /// \tparam B enumeration indicating endianness
  2595. /// \tparam GA flag indicating alignment for the Get operation
  2596. /// \tparam PA flag indicating alignment for the Put operation
  2597. /// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is
  2598. /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T.
  2599. /// \sa GetBlock() and PutBlock().
  2600. template <class T, class B, bool GA=false, bool PA=false>
  2601. struct BlockGetAndPut
  2602. {
  2603. // function needed because of C++ grammatical ambiguity between expression-statements and declarations
  2604. static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);}
  2605. typedef PutBlock<T, B, PA> Put;
  2606. };
  2607. /// \brief Convert a word to a string
  2608. /// \tparam T class or type
  2609. /// \param value the word to convert
  2610. /// \param order byte order
  2611. /// \return a string representing the value of the word
  2612. template <class T>
  2613. std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER)
  2614. {
  2615. if (!NativeByteOrderIs(order))
  2616. value = ByteReverse(value);
  2617. return std::string((char *)&value, sizeof(value));
  2618. }
  2619. /// \brief Convert a string to a word
  2620. /// \tparam T class or type
  2621. /// \param str the string to convert
  2622. /// \param order byte order
  2623. /// \return a word representing the value of the string
  2624. template <class T>
  2625. T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER)
  2626. {
  2627. T value = 0;
  2628. memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value)));
  2629. return NativeByteOrderIs(order) ? value : ByteReverse(value);
  2630. }
  2631. // ************** help remove warning on g++ ***************
  2632. /// \brief Safely shift values when undefined behavior could occur
  2633. /// \tparam overflow boolean flag indicating if overflow is present
  2634. /// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules.
  2635. /// The class behaves much like a saturating arithmetic class, clamping values rather than allowing
  2636. /// the compiler to remove undefined behavior.
  2637. /// \sa SafeShifter<true>, SafeShifter<false>
  2638. template <bool overflow> struct SafeShifter;
  2639. /// \brief Shifts a value in the presence of overflow
  2640. /// \details the true template parameter indicates overflow would occur.
  2641. /// In this case, SafeShifter clamps the value and returns 0.
  2642. template<> struct SafeShifter<true>
  2643. {
  2644. /// \brief Right shifts a value that overflows
  2645. /// \tparam T class or type
  2646. /// \return 0
  2647. /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
  2648. /// \sa SafeLeftShift
  2649. template <class T>
  2650. static inline T RightShift(T value, unsigned int bits)
  2651. {
  2652. CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
  2653. return 0;
  2654. }
  2655. /// \brief Left shifts a value that overflows
  2656. /// \tparam T class or type
  2657. /// \return 0
  2658. /// \details Since <tt>overflow == true</tt>, the value 0 is always returned.
  2659. /// \sa SafeRightShift
  2660. template <class T>
  2661. static inline T LeftShift(T value, unsigned int bits)
  2662. {
  2663. CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits);
  2664. return 0;
  2665. }
  2666. };
  2667. /// \brief Shifts a value in the absence of overflow
  2668. /// \details the false template parameter indicates overflow would not occur.
  2669. /// In this case, SafeShifter returns the shfted value.
  2670. template<> struct SafeShifter<false>
  2671. {
  2672. /// \brief Right shifts a value that does not overflow
  2673. /// \tparam T class or type
  2674. /// \return the shifted value
  2675. /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
  2676. /// \sa SafeLeftShift
  2677. template <class T>
  2678. static inline T RightShift(T value, unsigned int bits)
  2679. {
  2680. return value >> bits;
  2681. }
  2682. /// \brief Left shifts a value that does not overflow
  2683. /// \tparam T class or type
  2684. /// \return the shifted value
  2685. /// \details Since <tt>overflow == false</tt>, the shifted value is returned.
  2686. /// \sa SafeRightShift
  2687. template <class T>
  2688. static inline T LeftShift(T value, unsigned int bits)
  2689. {
  2690. return value << bits;
  2691. }
  2692. };
  2693. /// \brief Safely right shift values when undefined behavior could occur
  2694. /// \tparam bits the number of bit positions to shift the value
  2695. /// \tparam T class or type
  2696. /// \param value the value to right shift
  2697. /// \result the shifted value or 0
  2698. /// \details SafeRightShift safely shifts the value to the right when undefined behavior
  2699. /// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0
  2700. /// if undefined behavior would occur.
  2701. template <unsigned int bits, class T>
  2702. inline T SafeRightShift(T value)
  2703. {
  2704. return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
  2705. }
  2706. /// \brief Safely left shift values when undefined behavior could occur
  2707. /// \tparam bits the number of bit positions to shift the value
  2708. /// \tparam T class or type
  2709. /// \param value the value to left shift
  2710. /// \result the shifted value or 0
  2711. /// \details SafeLeftShift safely shifts the value to the left when undefined behavior
  2712. /// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0
  2713. /// if undefined behavior would occur.
  2714. template <unsigned int bits, class T>
  2715. inline T SafeLeftShift(T value)
  2716. {
  2717. return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
  2718. }
  2719. /// \brief Finds first element not in a range
  2720. /// \tparam InputIt Input iterator type
  2721. /// \tparam T class or type
  2722. /// \param first iterator to first element
  2723. /// \param last iterator to last element
  2724. /// \param value the value used as a predicate
  2725. /// \return iterator to the first element in the range that is not value
  2726. template<typename InputIt, typename T>
  2727. inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) {
  2728. #ifdef CRYPTOPP_CXX11_LAMBDA
  2729. return std::find_if(first, last, [&value](const T &o) {
  2730. return value!=o;
  2731. });
  2732. #else
  2733. return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value));
  2734. #endif
  2735. }
  2736. // ************** use one buffer for multiple data members ***************
  2737. #define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2738. #define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2739. #define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2740. #define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2741. #define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2742. #define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2743. #define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2744. #define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}
  2745. #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
  2746. NAMESPACE_END
  2747. #if (CRYPTOPP_MSC_VERSION)
  2748. # pragma warning(pop)
  2749. #endif
  2750. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  2751. # pragma GCC diagnostic pop
  2752. #endif
  2753. #endif