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