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