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