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