Crypto++ 7.0 Free C++ class library of cryptographic schemes

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