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