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