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