misc.h 121 KB

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