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