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