Security Scol plugin
misc.h
Go to the documentation of this file.
1// misc.h - originally written and placed in the public domain by Wei Dai
2
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
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
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>
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
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
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
226template <class T>
228{
229protected:
230 T m_object;
231};
232
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
255template <class T>
257{
258 T* operator()() const {return new T;}
259};
260
261#if CRYPTOPP_DOXYGEN_PROCESSING
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
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
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;
354 MEMORY_BARRIER();
355
356 if (p)
357 return *p;
358
359 T *newObject = m_objectFactory();
360 p = s_pObject.m_p;
361 MEMORY_BARRIER();
362
363 if (p)
364 {
365 delete newObject;
366 return *p;
367 }
368
369 s_pObject.m_p = newObject;
370 MEMORY_BARRIER();
371
372 return *newObject;
373#endif
374}
375
376// ************** misc functions ***************
377
385template <typename PTR, typename OFF>
386inline PTR PtrAdd(PTR pointer, OFF offset)
387{
388 return pointer+static_cast<ptrdiff_t>(offset);
389}
390
398template <typename PTR, typename OFF>
399inline PTR PtrSub(PTR pointer, OFF offset)
400{
401 return pointer-static_cast<ptrdiff_t>(offset);
402}
403
413template <typename PTR>
414inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2)
415{
416 return pointer1 - pointer2;
417}
418
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
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
454byte* BytePtr(SecByteBlock& str);
455
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
473const byte* ConstBytePtr(const SecByteBlock& str);
474
479inline size_t BytePtrSize(const std::string& str)
480{
481 return str.size();
482}
483
488size_t BytePtrSize(const SecByteBlock& str);
489
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
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
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
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
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
655template <class T> inline const T& STDMIN(const T& a, const T& b)
656{
657 return b < a ? b : a;
658}
659
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
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
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
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
759template <> CRYPTOPP_DLL
760std::string IntToString<word64>(word64 value, unsigned int base);
761
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
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
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
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
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
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
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
938inline size_t BitsToBytes(size_t bitCount)
939{
940 return ((bitCount+7)/(8));
941}
942
948inline size_t BytesToWords(size_t byteCount)
949{
950 return ((byteCount+WORD_SIZE-1)/WORD_SIZE);
951}
952
958inline size_t BitsToWords(size_t bitCount)
959{
960 return ((bitCount+WORD_BITS-1)/(WORD_BITS));
961}
962
968inline size_t BitsToDwords(size_t bitCount)
969{
970 return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS));
971}
972
979CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count);
980
988CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count);
989
1001CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count);
1002
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
1042template<class T>
1044{
1045 CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized);
1046 return (std::numeric_limits<T>::min)();
1047}
1048
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<>
1071inline word128 NumericLimitsMin()
1072{
1073 return 0;
1074}
1075template<>
1076inline word128 NumericLimitsMax()
1077{
1078 return (static_cast<word128>(LWORD_MAX) << 64U) | LWORD_MAX;
1079}
1080#endif
1081
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
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
1124template <class T1, class T2>
1125inline T2 ModPowerOf2(const T1 &a, const T2 &b)
1126{
1127 CRYPTOPP_ASSERT(IsPowerOf2(b));
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
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
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
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
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
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
1265{
1266 return NativeByteOrder::ToEnum();
1267}
1268
1273{
1274 return order == GetNativeByteOrder();
1275}
1276
1287template <class T>
1288inline CipherDir GetCipherDir(const T &obj)
1289{
1290 return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION;
1291}
1292
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
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
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
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
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
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
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
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
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
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
1515std::string StringNarrow(const wchar_t *str, bool throwOnError = true);
1516
1529std::wstring StringWiden(const char *str, bool throwOnError = true);
1530
1531// ************** rotate functions ***************
1532
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
2022inline byte ByteReverse(byte value)
2023{
2024 return value;
2025}
2026
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
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
2075inline word64 ByteReverse(word64 value)
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)
2100inline word128 ByteReverse(word128 value)
2101{
2102 // TODO: speed this up
2103 return (word128(ByteReverse(word64(value))) << 64) | ByteReverse(word64(value>>64));
2104}
2105#endif
2106
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
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
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
2158inline word64 BitReverse(word64 value)
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
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
2207template <class T>
2208inline T ConditionalByteReverse(ByteOrder order, T value)
2209{
2210 return NativeByteOrderIs(order) ? value : ByteReverse(value);
2211}
2212
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
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
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
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
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
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
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)
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
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
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
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
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)
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
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
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
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
2764template <class T, class B, bool A=false>
2766{
2767public:
2770 GetBlock(const void *block)
2771 : m_block((const byte *)block) {}
2772
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
2805template <class T, class B, bool A=false>
2807{
2808public:
2812 PutBlock(const void *xorBlock, void *block)
2813 : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {}
2814
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
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
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
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
2885template <bool overflow> struct SafeShifter;
2886
2890template<> struct SafeShifter<true>
2891{
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
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
2920template<> struct SafeShifter<false>
2921{
2927 template <class T>
2928 static inline T RightShift(T value, unsigned int bits)
2929 {
2930 return value >> bits;
2931 }
2932
2938 template <class T>
2939 static inline T LeftShift(T value, unsigned int bits)
2940 {
2941 return value << bits;
2942 }
2943};
2944
2953template <unsigned int bits, class T>
2954inline T SafeRightShift(T value)
2955{
2956 return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits);
2957}
2958
2967template <unsigned int bits, class T>
2968inline T SafeLeftShift(T value)
2969{
2970 return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits);
2971}
2972
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
Restricts the instantiation of a class to one static object without locks.
Definition misc.h:307
CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) 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.
unsigned char byte
8-bit unsigned datatype
Definition config_int.h:56
const lword LWORD_MAX
Large word type max value.
Definition config_int.h:164
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
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
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULLPTR)
Access a block of memory.
Definition misc.h:2739
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.
Definition integer.cpp:4767
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)
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
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
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count)
Definition misc.cpp:70
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
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
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition misc.cpp:218
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.
Definition integer.cpp:4833
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.
Definition misc.cpp:264
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.
Definition misc.cpp:328
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
T NumericLimitsMax()
Provide the maximum value for a type.
Definition misc.h:1061
T1 SaturatingSubtract1(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 1.
Definition misc.h:1110
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.