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