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