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