source: git/src-cryptopp/misc.h

Last change on this file was e230cb0, checked in by David Stainton <dstainton415@…>, at 2016-10-12T13:27:29Z

Add cryptopp from tag CRYPTOPP_5_6_5

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