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