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