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