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