|
||||
File indexing completed on 2025-01-18 09:55:05
0001 // misc.h - originally written and placed in the public domain by Wei Dai 0002 0003 /// \file misc.h 0004 /// \brief Utility functions for the Crypto++ library. 0005 0006 #ifndef CRYPTOPP_MISC_H 0007 #define CRYPTOPP_MISC_H 0008 0009 #include "config.h" 0010 0011 #include "cryptlib.h" 0012 #include "secblockfwd.h" 0013 #include "smartptr.h" 0014 #include "stdcpp.h" 0015 #include "trap.h" 0016 0017 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING) 0018 0019 #if (CRYPTOPP_MSC_VERSION) 0020 # pragma warning(push) 0021 # pragma warning(disable: 4146 4514) 0022 # if (CRYPTOPP_MSC_VERSION >= 1400) 0023 # pragma warning(disable: 6326) 0024 # endif 0025 #endif 0026 0027 // Issue 340 and Issue 793 0028 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 0029 # pragma GCC diagnostic push 0030 # pragma GCC diagnostic ignored "-Wconversion" 0031 # pragma GCC diagnostic ignored "-Wsign-conversion" 0032 # pragma GCC diagnostic ignored "-Wunused-function" 0033 #endif 0034 0035 #ifdef CRYPTOPP_MSC_VERSION 0036 #if CRYPTOPP_MSC_VERSION >= 1400 0037 // VC2005 workaround: disable declarations that conflict with winnt.h 0038 #define _interlockedbittestandset CRYPTOPP_DISABLED_INTRINSIC_1 0039 #define _interlockedbittestandreset CRYPTOPP_DISABLED_INTRINSIC_2 0040 #define _interlockedbittestandset64 CRYPTOPP_DISABLED_INTRINSIC_3 0041 #define _interlockedbittestandreset64 CRYPTOPP_DISABLED_INTRINSIC_4 0042 #include <intrin.h> 0043 #undef _interlockedbittestandset 0044 #undef _interlockedbittestandreset 0045 #undef _interlockedbittestandset64 0046 #undef _interlockedbittestandreset64 0047 #define CRYPTOPP_FAST_ROTATE(x) 1 0048 #elif CRYPTOPP_MSC_VERSION >= 1300 0049 #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32 | (x) == 64) 0050 #else 0051 #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32) 0052 #endif 0053 #elif (defined(__MWERKS__) && TARGET_CPU_PPC) || \ 0054 (defined(__GNUC__) && (defined(_ARCH_PWR2) || defined(_ARCH_PWR) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_COM))) 0055 #define CRYPTOPP_FAST_ROTATE(x) ((x) == 32) 0056 #elif defined(__GNUC__) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X86) // depend on GCC's peephole optimization to generate rotate instructions 0057 #define CRYPTOPP_FAST_ROTATE(x) 1 0058 #else 0059 #define CRYPTOPP_FAST_ROTATE(x) 0 0060 #endif 0061 0062 #ifdef __BORLANDC__ 0063 #include <mem.h> 0064 #include <stdlib.h> 0065 #endif 0066 0067 #if (defined(__GNUC__) || defined(__clang__)) && defined(__linux__) 0068 #define CRYPTOPP_BYTESWAP_AVAILABLE 1 0069 #include <byteswap.h> 0070 #endif 0071 0072 // Limit to ARM A-32. Aarch64 is failing self tests. 0073 #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 6) 0074 #define CRYPTOPP_ARM_BYTEREV_AVAILABLE 1 0075 #endif 0076 0077 // Limit to ARM A-32. Aarch64 is failing self tests. 0078 #if defined(__arm__) && (defined(__GNUC__) || defined(__clang__)) && (__ARM_ARCH >= 7) 0079 #define CRYPTOPP_ARM_BITREV_AVAILABLE 1 0080 #endif 0081 0082 #if defined(__BMI__) 0083 # if defined(CRYPTOPP_GCC_COMPATIBLE) 0084 # include <x86intrin.h> 0085 # endif 0086 # include <immintrin.h> 0087 #endif // BMI 0088 0089 // More LLVM bullshit. Apple Clang 6.0 does not define them. 0090 // Later version of Clang defines them and results in warnings. 0091 #if defined(__clang__) 0092 # ifndef _blsr_u32 0093 # define _blsr_u32 __blsr_u32 0094 # endif 0095 # ifndef _blsr_u64 0096 # define _blsr_u64 __blsr_u64 0097 # endif 0098 # ifndef _tzcnt_u32 0099 # define _tzcnt_u32 __tzcnt_u32 0100 # endif 0101 # ifndef _tzcnt_u64 0102 # define _tzcnt_u64 __tzcnt_u64 0103 # endif 0104 #endif 0105 0106 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0107 0108 #if CRYPTOPP_DOXYGEN_PROCESSING 0109 /// \brief The maximum value of a machine word 0110 /// \details <tt>SIZE_MAX</tt> provides the maximum value of a machine word. The value 0111 /// is <tt>0xffffffff</tt> on 32-bit targets, and <tt>0xffffffffffffffff</tt> on 64-bit 0112 /// targets. 0113 /// \details If <tt>SIZE_MAX</tt> is not defined, then <tt>__SIZE_MAX__</tt> is used if 0114 /// defined. If not defined, then <tt>SIZE_T_MAX</tt> is used if defined. If not defined, 0115 /// then the library uses <tt>std::numeric_limits<size_t>::max()</tt>. 0116 /// \details The library prefers <tt>__SIZE_MAX__</tt> or <tt>__SIZE_T_MAX__</tt> because 0117 /// they are effectively <tt>constexpr</tt> that is optimized well by all compilers. 0118 /// <tt>std::numeric_limits<size_t>::max()</tt> is not always a <tt>constexpr</tt>, and 0119 /// it is not always optimized well. 0120 # define SIZE_MAX ... 0121 #else 0122 // Its amazing portability problems still plague this simple concept in 2015. 0123 // http://stackoverflow.com/questions/30472731/which-c-standard-header-defines-size-max 0124 // Avoid NOMINMAX macro on Windows. http://support.microsoft.com/en-us/kb/143208 0125 #ifndef SIZE_MAX 0126 # if defined(__SIZE_MAX__) 0127 # define SIZE_MAX __SIZE_MAX__ 0128 # elif defined(SIZE_T_MAX) 0129 # define SIZE_MAX SIZE_T_MAX 0130 # elif defined(__SIZE_TYPE__) 0131 # define SIZE_MAX (~(__SIZE_TYPE__)0) 0132 # else 0133 # define SIZE_MAX ((std::numeric_limits<size_t>::max)()) 0134 # endif 0135 #endif 0136 0137 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0138 0139 NAMESPACE_BEGIN(CryptoPP) 0140 0141 // Forward declaration for IntToString specialization 0142 class Integer; 0143 0144 // ************** compile-time assertion *************** 0145 0146 #if CRYPTOPP_DOXYGEN_PROCESSING 0147 /// \brief Compile time assertion 0148 /// \param expr the expression to evaluate 0149 /// \details Asserts the expression <tt>expr</tt> during compile. If C++14 and 0150 /// N3928 are available, then C++14 <tt>static_assert</tt> is used. Otherwise, 0151 /// a <tt>CompileAssert</tt> structure is used. When the structure is used 0152 /// a negative-sized array triggers the assert at compile time. 0153 # define CRYPTOPP_COMPILE_ASSERT(expr) { ... } 0154 #elif defined(CRYPTOPP_CXX17_STATIC_ASSERT) 0155 # define CRYPTOPP_COMPILE_ASSERT(expr) static_assert(expr) 0156 #else // CRYPTOPP_DOXYGEN_PROCESSING 0157 template <bool b> 0158 struct CompileAssert 0159 { 0160 static char dummy[2*b-1]; 0161 }; 0162 0163 #define CRYPTOPP_COMPILE_ASSERT(assertion) CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__) 0164 #define CRYPTOPP_ASSERT_JOIN(X, Y) CRYPTOPP_DO_ASSERT_JOIN(X, Y) 0165 #define CRYPTOPP_DO_ASSERT_JOIN(X, Y) X##Y 0166 0167 #if defined(CRYPTOPP_EXPORTS) || defined(CRYPTOPP_IMPORTS) 0168 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) 0169 #else 0170 # if defined(__GNUC__) || defined(__clang__) 0171 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \ 0172 static CompileAssert<(assertion)> \ 0173 CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) __attribute__ ((unused)) 0174 # else 0175 # define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance) \ 0176 static CompileAssert<(assertion)> \ 0177 CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance) 0178 # endif // GCC or Clang 0179 #endif 0180 0181 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0182 0183 // ************** count elements in an array *************** 0184 0185 #if CRYPTOPP_DOXYGEN_PROCESSING 0186 /// \brief Counts elements in an array 0187 /// \param arr an array of elements 0188 /// \details COUNTOF counts elements in an array. On Windows COUNTOF(x) is defined 0189 /// to <tt>_countof(x)</tt> to ensure correct results for pointers. 0190 /// \note COUNTOF does not produce correct results with pointers, and an array must be used. 0191 /// <tt>sizeof(x)/sizeof(x[0])</tt> suffers the same problem. The risk is eliminated by using 0192 /// <tt>_countof(x)</tt> on Windows. Windows will provide the immunity for other platforms. 0193 # define COUNTOF(arr) 0194 #else 0195 // VS2005 added _countof 0196 #ifndef COUNTOF 0197 # if defined(CRYPTOPP_MSC_VERSION) && (CRYPTOPP_MSC_VERSION >= 1400) 0198 # define COUNTOF(x) _countof(x) 0199 # else 0200 # define COUNTOF(x) (sizeof(x)/sizeof(x[0])) 0201 # endif 0202 #endif // COUNTOF 0203 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0204 0205 // ************** misc classes *************** 0206 0207 /// \brief An Empty class 0208 /// \details The Empty class can be used as a template parameter <tt>BASE</tt> when no base class exists. 0209 class CRYPTOPP_DLL Empty 0210 { 0211 }; 0212 0213 #if !defined(CRYPTOPP_DOXYGEN_PROCESSING) 0214 template <class BASE1, class BASE2> 0215 class CRYPTOPP_NO_VTABLE TwoBases : public BASE1, public BASE2 0216 { 0217 }; 0218 0219 template <class BASE1, class BASE2, class BASE3> 0220 class CRYPTOPP_NO_VTABLE ThreeBases : public BASE1, public BASE2, public BASE3 0221 { 0222 }; 0223 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0224 0225 /// \tparam T class or type 0226 /// \brief Uses encapsulation to hide an object in derived classes 0227 /// \details The object T is declared as protected. 0228 template <class T> 0229 class ObjectHolder 0230 { 0231 protected: 0232 T m_object; 0233 }; 0234 0235 /// \brief Ensures an object is not copyable 0236 /// \details NotCopyable ensures an object is not copyable by making the 0237 /// copy constructor and assignment operator private. Deleters are used 0238 /// under C++11. 0239 /// \sa Clonable class 0240 class NotCopyable 0241 { 0242 public: 0243 NotCopyable() {} 0244 #if CRYPTOPP_CXX11_DELETED_FUNCTIONS 0245 NotCopyable(const NotCopyable &) = delete; 0246 void operator=(const NotCopyable &) = delete; 0247 #else 0248 private: 0249 NotCopyable(const NotCopyable &); 0250 void operator=(const NotCopyable &); 0251 #endif 0252 }; 0253 0254 /// \brief An object factory function 0255 /// \tparam T class or type 0256 /// \details NewObject overloads operator()(). 0257 template <class T> 0258 struct NewObject 0259 { 0260 T* operator()() const {return new T;} 0261 }; 0262 0263 #if CRYPTOPP_DOXYGEN_PROCESSING 0264 /// \brief A memory barrier 0265 /// \details MEMORY_BARRIER attempts to ensure reads and writes are completed 0266 /// in the absence of a language synchronization point. It is used by the 0267 /// Singleton class if the compiler supports it. The barrier is provided at the 0268 /// customary places in a double-checked initialization. 0269 /// \details Internally, MEMORY_BARRIER uses <tt>std::atomic_thread_fence</tt> if 0270 /// C++11 atomics are available. Otherwise, <tt>intrinsic(_ReadWriteBarrier)</tt>, 0271 /// <tt>_ReadWriteBarrier()</tt> or <tt>__asm__("" ::: "memory")</tt> is used. 0272 #define MEMORY_BARRIER ... 0273 #else 0274 #if defined(CRYPTOPP_CXX11_ATOMIC) 0275 # define MEMORY_BARRIER() std::atomic_thread_fence(std::memory_order_acq_rel) 0276 #elif (CRYPTOPP_MSC_VERSION >= 1400) 0277 # pragma intrinsic(_ReadWriteBarrier) 0278 # define MEMORY_BARRIER() _ReadWriteBarrier() 0279 #elif defined(__INTEL_COMPILER) 0280 # define MEMORY_BARRIER() __memory_barrier() 0281 #elif defined(__GNUC__) || defined(__clang__) 0282 # define MEMORY_BARRIER() __asm__ __volatile__ ("" ::: "memory") 0283 #else 0284 # define MEMORY_BARRIER() 0285 #endif 0286 #endif // CRYPTOPP_DOXYGEN_PROCESSING 0287 0288 /// \brief Restricts the instantiation of a class to one static object without locks 0289 /// \tparam T the class or type 0290 /// \tparam F the object factory for T 0291 /// \tparam instance an instance counter for the class object 0292 /// \details This class safely initializes a static object in a multi-threaded environment. For C++03 0293 /// and below it will do so without using locks for portability. If two threads call Ref() at the same 0294 /// time, they may get back different references, and one object may end up being memory leaked. This 0295 /// is by design and it avoids a subtle initialization problem in a multi-threaded environment with thread 0296 /// local storage on early Windows platforms, like Windows XP and Windows 2003. 0297 /// \details For C++11 and above, a standard double-checked locking pattern with thread fences 0298 /// are used. The locks and fences are standard and do not hinder portability. 0299 /// \details Microsoft's C++11 implementation provides the necessary primitive support on Windows Vista and 0300 /// above when using Visual Studio 2015 (<tt>cl.exe</tt> version 19.00). If C++11 is desired, you should 0301 /// set <tt>WINVER</tt> or <tt>_WIN32_WINNT</tt> to 0x600 (or above), and compile with Visual Studio 2015. 0302 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking 0303 /// is Fixed In C++11</A>, <A HREF="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm">Dynamic 0304 /// Initialization and Destruction with Concurrency</A> and 0305 /// <A HREF="http://msdn.microsoft.com/en-us/library/6yh4a9k1.aspx">Thread Local Storage (TLS)</A> on MSDN. 0306 /// \since Crypto++ 5.2 0307 template <class T, class F = NewObject<T>, int instance=0> 0308 class Singleton 0309 { 0310 public: 0311 Singleton(F objectFactory = F()) : m_objectFactory(objectFactory) {} 0312 0313 // prevent this function from being inlined 0314 CRYPTOPP_NOINLINE const T & Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const; 0315 0316 private: 0317 F m_objectFactory; 0318 }; 0319 0320 /// \brief Return a reference to the inner Singleton object 0321 /// \tparam T the class or type 0322 /// \tparam F the object factory for T 0323 /// \tparam instance an instance counter for the class object 0324 /// \details Ref() is used to create the object using the object factory. The 0325 /// object is only created once with the limitations discussed in the class documentation. 0326 /// \sa <A HREF="http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/">Double-Checked Locking is Fixed In C++11</A> 0327 /// \since Crypto++ 5.2 0328 template <class T, class F, int instance> 0329 const T & Singleton<T, F, instance>::Ref(CRYPTOPP_NOINLINE_DOTDOTDOT) const 0330 { 0331 #if defined(CRYPTOPP_CXX11_ATOMIC) && defined(CRYPTOPP_CXX11_SYNCHRONIZATION) && defined(CRYPTOPP_CXX11_STATIC_INIT) 0332 static std::mutex s_mutex; 0333 static std::atomic<T*> s_pObject; 0334 0335 T *p = s_pObject.load(std::memory_order_relaxed); 0336 std::atomic_thread_fence(std::memory_order_acquire); 0337 0338 if (p) 0339 return *p; 0340 0341 std::lock_guard<std::mutex> lock(s_mutex); 0342 p = s_pObject.load(std::memory_order_relaxed); 0343 std::atomic_thread_fence(std::memory_order_acquire); 0344 0345 if (p) 0346 return *p; 0347 0348 T *newObject = m_objectFactory(); 0349 std::atomic_thread_fence(std::memory_order_release); 0350 s_pObject.store(newObject, std::memory_order_relaxed); 0351 0352 return *newObject; 0353 #else 0354 static volatile simple_ptr<T> s_pObject; 0355 T *p = s_pObject.m_p; 0356 MEMORY_BARRIER(); 0357 0358 if (p) 0359 return *p; 0360 0361 T *newObject = m_objectFactory(); 0362 p = s_pObject.m_p; 0363 MEMORY_BARRIER(); 0364 0365 if (p) 0366 { 0367 delete newObject; 0368 return *p; 0369 } 0370 0371 s_pObject.m_p = newObject; 0372 MEMORY_BARRIER(); 0373 0374 return *newObject; 0375 #endif 0376 } 0377 0378 // ************** misc functions *************** 0379 0380 /// \brief Create a pointer with an offset 0381 /// \tparam PTR a pointer type 0382 /// \tparam OFF a size type 0383 /// \param pointer a pointer 0384 /// \param offset a offset into the pointer 0385 /// \details PtrAdd can be used to squash Clang and GCC 0386 /// UBsan findings for pointer addition and subtraction. 0387 template <typename PTR, typename OFF> 0388 inline PTR PtrAdd(PTR pointer, OFF offset) 0389 { 0390 return pointer+static_cast<ptrdiff_t>(offset); 0391 } 0392 0393 /// \brief Create a pointer with an offset 0394 /// \tparam PTR a pointer type 0395 /// \tparam OFF a size type 0396 /// \param pointer a pointer 0397 /// \param offset a offset into the pointer 0398 /// \details PtrSub can be used to squash Clang and GCC 0399 /// UBsan findings for pointer addition and subtraction. 0400 template <typename PTR, typename OFF> 0401 inline PTR PtrSub(PTR pointer, OFF offset) 0402 { 0403 return pointer-static_cast<ptrdiff_t>(offset); 0404 } 0405 0406 /// \brief Determine pointer difference 0407 /// \tparam PTR a pointer type 0408 /// \param pointer1 the first pointer 0409 /// \param pointer2 the second pointer 0410 /// \details PtrDiff can be used to squash Clang and GCC 0411 /// UBsan findings for pointer addition and subtraction. 0412 /// pointer1 and pointer2 must point to the same object or 0413 /// array (or one past the end), and yields the number of 0414 /// elements (not bytes) difference. 0415 template <typename PTR> 0416 inline ptrdiff_t PtrDiff(const PTR pointer1, const PTR pointer2) 0417 { 0418 return pointer1 - pointer2; 0419 } 0420 0421 /// \brief Determine pointer difference 0422 /// \tparam PTR a pointer type 0423 /// \param pointer1 the first pointer 0424 /// \param pointer2 the second pointer 0425 /// \details PtrByteDiff can be used to squash Clang and GCC 0426 /// UBsan findings for pointer addition and subtraction. 0427 /// pointer1 and pointer2 must point to the same object or 0428 /// array (or one past the end), and yields the number of 0429 /// bytes (not elements) difference. 0430 template <typename PTR> 0431 inline size_t PtrByteDiff(const PTR pointer1, const PTR pointer2) 0432 { 0433 return (size_t)(reinterpret_cast<uintptr_t>(pointer1) - reinterpret_cast<uintptr_t>(pointer2)); 0434 } 0435 0436 /// \brief Pointer to the first element of a string 0437 /// \param str string 0438 /// \details BytePtr returns NULL pointer for an empty string. 0439 /// \return Pointer to the first element of a string 0440 /// \since Crypto++ 8.0 0441 inline byte* BytePtr(std::string& str) 0442 { 0443 // Caller wants a writable pointer 0444 CRYPTOPP_ASSERT(str.empty() == false); 0445 0446 if (str.empty()) 0447 return NULLPTR; 0448 return reinterpret_cast<byte*>(&str[0]); 0449 } 0450 0451 /// \brief Pointer to the first element of a string 0452 /// \param str SecByteBlock 0453 /// \details BytePtr returns NULL pointer for an empty string. 0454 /// \return Pointer to the first element of a string 0455 /// \since Crypto++ 8.3 0456 byte* BytePtr(SecByteBlock& str); 0457 0458 /// \brief Const pointer to the first element of a string 0459 /// \param str string 0460 /// \details ConstBytePtr returns non-NULL pointer for an empty string. 0461 /// \return Pointer to the first element of a string 0462 /// \since Crypto++ 8.0 0463 inline const byte* ConstBytePtr(const std::string& str) 0464 { 0465 if (str.empty()) 0466 return NULLPTR; 0467 return reinterpret_cast<const byte*>(&str[0]); 0468 } 0469 0470 /// \brief Const pointer to the first element of a string 0471 /// \param str SecByteBlock 0472 /// \details ConstBytePtr returns non-NULL pointer for an empty string. 0473 /// \return Pointer to the first element of a string 0474 /// \since Crypto++ 8.3 0475 const byte* ConstBytePtr(const SecByteBlock& str); 0476 0477 /// \brief Size of a string 0478 /// \param str string 0479 /// \return size of a string 0480 /// \since Crypto++ 8.3 0481 inline size_t BytePtrSize(const std::string& str) 0482 { 0483 return str.size(); 0484 } 0485 0486 /// \brief Size of a string 0487 /// \param str SecByteBlock 0488 /// \return size of a string 0489 /// \since Crypto++ 8.3 0490 size_t BytePtrSize(const SecByteBlock& str); 0491 0492 /// \brief Integer value 0493 /// \details EnumToInt avoids C++20 enum-enum conversion 0494 /// warnings under GCC and Clang. C++11 and above use a 0495 /// constexpr function. C++03 and below use a macro due 0496 /// to [lack of] constexpr-ness in early versions of C++. 0497 /// \since Crypto++ 8.6 0498 #if (CRYPTOPP_CXX11_CONSTEXPR) 0499 template <typename T> 0500 constexpr int EnumToInt(T v) { 0501 return static_cast<int>(v); 0502 } 0503 #else 0504 # define EnumToInt(v) static_cast<int>(v) 0505 #endif 0506 0507 #if (!__STDC_WANT_SECURE_LIB__ && !defined(_MEMORY_S_DEFINED)) || defined(CRYPTOPP_WANT_SECURE_LIB) 0508 0509 /// \brief Bounds checking replacement for memcpy() 0510 /// \param dest pointer to the destination memory block 0511 /// \param sizeInBytes size of the destination memory block, in bytes 0512 /// \param src pointer to the source memory block 0513 /// \param count the number of bytes to copy 0514 /// \throw InvalidArgument 0515 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially 0516 /// unsafe functions like memcpy(), strcpy() and memmove(). However, 0517 /// not all standard libraries provides them, like Glibc. The library's 0518 /// memcpy_s() is a near-drop in replacement. Its only a near-replacement 0519 /// because the library's version throws an InvalidArgument on a bounds violation. 0520 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__. 0521 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library 0522 /// makes memcpy_s() and memmove_s() available. The library will also optionally 0523 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined. 0524 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default. 0525 /// \details memcpy_s() will assert the pointers src and dest are not NULL 0526 /// in debug builds. Passing NULL for either pointer is undefined behavior. 0527 inline void memcpy_s(void *dest, size_t sizeInBytes, const void *src, size_t count) 0528 { 0529 // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55 0530 0531 // Pointers must be valid; otherwise undefined behavior 0532 CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR); 0533 // Restricted pointers. We want to check ranges, but it is not clear how to do it. 0534 CRYPTOPP_ASSERT(src != dest); 0535 // Destination buffer must be large enough to satisfy request 0536 CRYPTOPP_ASSERT(sizeInBytes >= count); 0537 0538 if (count > sizeInBytes) 0539 throw InvalidArgument("memcpy_s: buffer overflow"); 0540 0541 #if CRYPTOPP_MSC_VERSION 0542 # pragma warning(push) 0543 # pragma warning(disable: 4996) 0544 # if (CRYPTOPP_MSC_VERSION >= 1400) 0545 # pragma warning(disable: 6386) 0546 # endif 0547 #endif 0548 if (src != NULLPTR && dest != NULLPTR) 0549 std::memcpy(dest, src, count); 0550 #if CRYPTOPP_MSC_VERSION 0551 # pragma warning(pop) 0552 #endif 0553 } 0554 0555 /// \brief Bounds checking replacement for memmove() 0556 /// \param dest pointer to the destination memory block 0557 /// \param sizeInBytes size of the destination memory block, in bytes 0558 /// \param src pointer to the source memory block 0559 /// \param count the number of bytes to copy 0560 /// \throw InvalidArgument 0561 /// \details ISO/IEC TR-24772 provides bounds checking interfaces for potentially 0562 /// unsafe functions like memcpy(), strcpy() and memmove(). However, 0563 /// not all standard libraries provides them, like Glibc. The library's 0564 /// memmove_s() is a near-drop in replacement. Its only a near-replacement 0565 /// because the library's version throws an InvalidArgument on a bounds violation. 0566 /// \details memcpy_s() and memmove_s() are guarded by __STDC_WANT_SECURE_LIB__. 0567 /// If __STDC_WANT_SECURE_LIB__ is not defined or defined to 0, then the library 0568 /// makes memcpy_s() and memmove_s() available. The library will also optionally 0569 /// make the symbols available if <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is defined. 0570 /// <tt>CRYPTOPP_WANT_SECURE_LIB</tt> is in config.h, but it is disabled by default. 0571 /// \details memmove_s() will assert the pointers src and dest are not NULL 0572 /// in debug builds. Passing NULL for either pointer is undefined behavior. 0573 inline void memmove_s(void *dest, size_t sizeInBytes, const void *src, size_t count) 0574 { 0575 // Safer functions on Windows for C&A, http://github.com/weidai11/cryptopp/issues/55 0576 0577 // Pointers must be valid; otherwise undefined behavior 0578 CRYPTOPP_ASSERT(dest != NULLPTR); CRYPTOPP_ASSERT(src != NULLPTR); 0579 // Destination buffer must be large enough to satisfy request 0580 CRYPTOPP_ASSERT(sizeInBytes >= count); 0581 0582 if (count > sizeInBytes) 0583 throw InvalidArgument("memmove_s: buffer overflow"); 0584 0585 #if CRYPTOPP_MSC_VERSION 0586 # pragma warning(push) 0587 # pragma warning(disable: 4996) 0588 # if (CRYPTOPP_MSC_VERSION >= 1400) 0589 # pragma warning(disable: 6386) 0590 # endif 0591 #endif 0592 if (src != NULLPTR && dest != NULLPTR) 0593 std::memmove(dest, src, count); 0594 #if CRYPTOPP_MSC_VERSION 0595 # pragma warning(pop) 0596 #endif 0597 } 0598 0599 #if __BORLANDC__ >= 0x620 0600 // C++Builder 2010 workaround: can't use memcpy_s 0601 // because it doesn't allow 0 lengths 0602 # define memcpy_s CryptoPP::memcpy_s 0603 # define memmove_s CryptoPP::memmove_s 0604 #endif 0605 0606 #endif // __STDC_WANT_SECURE_LIB__ 0607 0608 /// \brief Swaps two variables which are arrays 0609 /// \tparam T class or type 0610 /// \param a the first value 0611 /// \param b the second value 0612 /// \details C++03 does not provide support for <tt>std::swap(__m128i a, __m128i b)</tt> 0613 /// because <tt>__m128i</tt> is an <tt>unsigned long long[2]</tt>. Most compilers 0614 /// support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not. 0615 /// \sa <A HREF="http://stackoverflow.com/q/38417413">How to swap two __m128i variables 0616 /// in C++03 given its an opaque type and an array?</A> on Stack Overflow. 0617 template <class T> 0618 inline void vec_swap(T& a, T& b) 0619 { 0620 // __m128i is an unsigned long long[2], and support for swapping it was 0621 // not added until C++11. SunCC 12.1 - 12.3 fail to consume the swap; while 0622 // SunCC 12.4 consumes it without -std=c++11. 0623 #if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x5120) 0624 T t; 0625 t=a, a=b, b=t; 0626 #else 0627 std::swap(a, b); 0628 #endif 0629 } 0630 0631 /// \brief Memory block initializer 0632 /// \param ptr pointer to the memory block being written 0633 /// \param val the integer value to write for each byte 0634 /// \param num the size of the source memory block, in bytes 0635 /// \details Internally the function calls memset with the value <tt>val</tt>. 0636 /// memset_z can be used to initialize a freshly allocated memory block. 0637 /// To zeroize a memory block on destruction use <tt>SecureWipeBuffer</tt>. 0638 /// \return the pointer to the memory block 0639 /// \sa SecureWipeBuffer 0640 inline void * memset_z(void *ptr, int val, size_t num) 0641 { 0642 // avoid extraneous warning on GCC 4.3.2 Ubuntu 8.10 0643 #if CRYPTOPP_GCC_VERSION >= 30001 || CRYPTOPP_LLVM_CLANG_VERSION >= 20800 || \ 0644 CRYPTOPP_APPLE_CLANG_VERSION >= 30000 0645 if (__builtin_constant_p(num) && num==0) 0646 return ptr; 0647 #endif 0648 return std::memset(ptr, val, num); 0649 } 0650 0651 /// \brief Replacement function for std::min 0652 /// \tparam T class or type 0653 /// \param a the first value 0654 /// \param b the second value 0655 /// \return the minimum value based on a comparison of <tt>b \< a</tt> using <tt>operator\<</tt> 0656 /// \details STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0 0657 template <class T> inline const T& STDMIN(const T& a, const T& b) 0658 { 0659 return b < a ? b : a; 0660 } 0661 0662 /// \brief Replacement function for std::max 0663 /// \tparam T class or type 0664 /// \param a the first value 0665 /// \param b the second value 0666 /// \return the minimum value based on a comparison of <tt>a \< b</tt> using <tt>operator\<</tt> 0667 /// \details STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0 0668 template <class T> inline const T& STDMAX(const T& a, const T& b) 0669 { 0670 return a < b ? b : a; 0671 } 0672 0673 #if CRYPTOPP_MSC_VERSION 0674 # pragma warning(push) 0675 # pragma warning(disable: 4389) 0676 #endif 0677 0678 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 0679 # pragma GCC diagnostic push 0680 # pragma GCC diagnostic ignored "-Wstrict-overflow" 0681 # if (CRYPTOPP_LLVM_CLANG_VERSION >= 20800) || (CRYPTOPP_APPLE_CLANG_VERSION >= 30000) 0682 # pragma GCC diagnostic ignored "-Wtautological-compare" 0683 # elif (CRYPTOPP_GCC_VERSION >= 40300) 0684 # pragma GCC diagnostic ignored "-Wtype-limits" 0685 # endif 0686 #endif 0687 0688 /// \brief Safe comparison of values that could be negative and incorrectly promoted 0689 /// \tparam T1 class or type 0690 /// \tparam T2 class or type 0691 /// \param a the first value 0692 /// \param b the second value 0693 /// \return the minimum value based on a comparison a and b using <tt>operator<</tt>. 0694 /// \details The comparison <tt>b \< a</tt> is performed and the value returned is type T1. 0695 template <class T1, class T2> inline const T1 UnsignedMin(const T1& a, const T2& b) 0696 { 0697 CRYPTOPP_COMPILE_ASSERT((sizeof(T1)<=sizeof(T2) && T2(-1)>0) || (sizeof(T1)>sizeof(T2) && T1(-1)>0)); 0698 CRYPTOPP_COMPILE_ASSERT(std::numeric_limits<T1>::is_signed == false); 0699 CRYPTOPP_COMPILE_ASSERT(std::numeric_limits<T2>::is_signed == false); 0700 0701 if (sizeof(T1)<=sizeof(T2)) 0702 return b < (T2)a ? (T1)b : a; 0703 else 0704 return (T1)b < a ? (T1)b : a; 0705 } 0706 0707 /// \brief Perform a conversion from \p from to \p to 0708 /// \tparam T1 class or type 0709 /// \tparam T2 class or type 0710 /// \param from the first value 0711 /// \param to the second value 0712 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0713 /// \details if the function returns true, then it is safe to use \p to. If the function returns false, 0714 /// then \p to is undefined and should not be used. 0715 /// \note for integral conversions, a template specialization should be provided. The specialization 0716 /// will perform more efficiently, and avoid warnings for truncation and sign compares. 0717 template <class T1, class T2> 0718 inline bool SafeConvert(T1 from, T2 &to) 0719 { 0720 to = static_cast<T2>(from); 0721 if (from != to || (from > 0) != (to > 0)) 0722 return false; 0723 return true; 0724 } 0725 0726 // The following specializations are the product of {word32, sword32, word64, sword64} -> 0727 // {word32, sword32, word64, sword64}. There are 16 of them, but we can omit specializations 0728 // of {word64} -> {word64}, {word32} -> {word32}, etc. 0729 // 0730 // The list below proceeds to list the conversion to word64 (3 each), followed by 0731 // sword64 (3 each), followed by word32 (3 each), and finally follwed by sword32 (3 each). 0732 0733 /// \brief Perform a conversion from \p from to \p to 0734 /// \param from the first value 0735 /// \param to the second value 0736 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0737 /// \details if the function returns true, then it is safe to use \p to. If the function 0738 /// returns false, then \p to is undefined and should not be used. 0739 /// \since Crypto++ 8.8 0740 template<> 0741 inline bool SafeConvert(sword64 from, word64 &to) 0742 { 0743 if (from < 0) 0744 return false; 0745 to = static_cast<word64>(from); 0746 return true; 0747 } 0748 0749 /// \brief Perform a conversion from \p from to \p to 0750 /// \param from the first value 0751 /// \param to the second value 0752 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0753 /// \details if the function returns true, then it is safe to use \p to. If the function 0754 /// returns false, then \p to is undefined and should not be used. 0755 /// \since Crypto++ 8.8 0756 template<> 0757 inline bool SafeConvert(word32 from, word64 &to) 0758 { 0759 to = static_cast<word64>(from); 0760 return true; 0761 } 0762 0763 /// \brief Perform a conversion from \p from to \p to 0764 /// \param from the first value 0765 /// \param to the second value 0766 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0767 /// \details if the function returns true, then it is safe to use \p to. If the function 0768 /// returns false, then \p to is undefined and should not be used. 0769 /// \since Crypto++ 8.8 0770 template<> 0771 inline bool SafeConvert(sword32 from, word64 &to) 0772 { 0773 if (from < 0) 0774 return false; 0775 to = static_cast<word64>(from); 0776 return true; 0777 } 0778 0779 /// \brief Perform a conversion from \p from to \p to 0780 /// \param from the first value 0781 /// \param to the second value 0782 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0783 /// \details if the function returns true, then it is safe to use \p to. If the function 0784 /// returns false, then \p to is undefined and should not be used. 0785 /// \since Crypto++ 8.8 0786 template<> 0787 inline bool SafeConvert(word64 from, sword64 &to) 0788 { 0789 if (from > static_cast<word64>((std::numeric_limits<sword64>::max)())) 0790 return false; 0791 to = static_cast<sword64>(from); 0792 return true; 0793 } 0794 0795 /// \brief Perform a conversion from \p from to \p to 0796 /// \param from the first value 0797 /// \param to the second value 0798 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0799 /// \details if the function returns true, then it is safe to use \p to. If the function 0800 /// returns false, then \p to is undefined and should not be used. 0801 /// \since Crypto++ 8.8 0802 template<> 0803 inline bool SafeConvert(word32 from, sword64 &to) 0804 { 0805 to = static_cast<sword64>(from); 0806 return true; 0807 } 0808 0809 /// \brief Perform a conversion from \p from to \p to 0810 /// \param from the first value 0811 /// \param to the second value 0812 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0813 /// \details if the function returns true, then it is safe to use \p to. If the function 0814 /// returns false, then \p to is undefined and should not be used. 0815 /// \since Crypto++ 8.8 0816 template<> 0817 inline bool SafeConvert(sword32 from, sword64 &to) 0818 { 0819 to = static_cast<sword64>(from); 0820 return true; 0821 } 0822 0823 /// \brief Perform a conversion from \p from to \p to 0824 /// \param from the first value 0825 /// \param to the second value 0826 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0827 /// \details if the function returns true, then it is safe to use \p to. If the function 0828 /// returns false, then \p to is undefined and should not be used. 0829 /// \since Crypto++ 8.8 0830 template<> 0831 inline bool SafeConvert(word64 from, word32 &to) 0832 { 0833 if (from > static_cast<word64>((std::numeric_limits<word32>::max)())) 0834 return false; 0835 to = static_cast<word32>(from); 0836 return true; 0837 } 0838 0839 /// \brief Perform a conversion from \p from to \p to 0840 /// \param from the first value 0841 /// \param to the second value 0842 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0843 /// \details if the function returns true, then it is safe to use \p to. If the function 0844 /// returns false, then \p to is undefined and should not be used. 0845 /// \since Crypto++ 8.8 0846 template<> 0847 inline bool SafeConvert(sword64 from, word32 &to) 0848 { 0849 if (from < 0) 0850 return false; 0851 else if (from > static_cast<sword64>((std::numeric_limits<word32>::max)())) 0852 return false; 0853 to = static_cast<word32>(from); 0854 return true; 0855 } 0856 0857 /// \brief Perform a conversion from \p from to \p to 0858 /// \param from the first value 0859 /// \param to the second value 0860 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0861 /// \details if the function returns true, then it is safe to use \p to. If the function 0862 /// returns false, then \p to is undefined and should not be used. 0863 /// \since Crypto++ 8.8 0864 template<> 0865 inline bool SafeConvert(sword32 from, word32 &to) 0866 { 0867 if (from < 0) 0868 return false; 0869 to = static_cast<word32>(from); 0870 return true; 0871 } 0872 0873 /// \brief Perform a conversion from \p from to \p to 0874 /// \param from the first value 0875 /// \param to the second value 0876 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0877 /// \details if the function returns true, then it is safe to use \p to. If the function 0878 /// returns false, then \p to is undefined and should not be used. 0879 /// \since Crypto++ 8.8 0880 template<> 0881 inline bool SafeConvert(word64 from, sword32 &to) 0882 { 0883 if (from > static_cast<word64>((std::numeric_limits<sword32>::max)())) 0884 return false; 0885 to = static_cast<sword32>(from); 0886 return true; 0887 } 0888 0889 /// \brief Perform a conversion from \p from to \p to 0890 /// \param from the first value 0891 /// \param to the second value 0892 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0893 /// \details if the function returns true, then it is safe to use \p to. If the function 0894 /// returns false, then \p to is undefined and should not be used. 0895 /// \since Crypto++ 8.8 0896 template<> 0897 inline bool SafeConvert(sword64 from, sword32 &to) 0898 { 0899 if (from > static_cast<sword64>((std::numeric_limits<sword32>::max)())) 0900 return false; 0901 else if (from < static_cast<sword64>((std::numeric_limits<sword32>::min)())) 0902 return false; 0903 to = static_cast<sword32>(from); 0904 return true; 0905 } 0906 0907 /// \brief Perform a conversion from \p from to \p to 0908 /// \param from the first value 0909 /// \param to the second value 0910 /// \return true if its safe to convert from \p from to \p to, false otherwise. 0911 /// \details if the function returns true, then it is safe to use \p to. If the function 0912 /// returns false, then \p to is undefined and should not be used. 0913 /// \since Crypto++ 8.8 0914 template<> 0915 inline bool SafeConvert(word32 from, sword32 &to) 0916 { 0917 if (from > static_cast<word32>((std::numeric_limits<sword32>::max)())) 0918 return false; 0919 to = static_cast<sword32>(from); 0920 return true; 0921 } 0922 0923 /// \brief Converts a value to a string 0924 /// \tparam T class or type 0925 /// \param value the value to convert 0926 /// \param base the base to use during the conversion 0927 /// \return the string representation of value in base. 0928 template <class T> 0929 std::string IntToString(T value, unsigned int base = 10) 0930 { 0931 // Hack... set the high bit for uppercase. 0932 const unsigned int HIGH_BIT = (1U << 31); 0933 const char CH = !!(base & HIGH_BIT) ? 'A' : 'a'; 0934 base &= ~HIGH_BIT; 0935 0936 CRYPTOPP_ASSERT(base >= 2); 0937 if (value == 0) 0938 return "0"; 0939 0940 bool negate = false; 0941 if (value < 0) 0942 { 0943 negate = true; 0944 value = 0-value; // VC .NET does not like -a 0945 } 0946 std::string result; 0947 while (value > 0) 0948 { 0949 T digit = value % base; 0950 result = char((digit < 10 ? '0' : (CH - 10)) + digit) + result; 0951 value /= base; 0952 } 0953 if (negate) 0954 result = "-" + result; 0955 return result; 0956 } 0957 0958 /// \brief Converts an unsigned value to a string 0959 /// \param value the value to convert 0960 /// \param base the base to use during the conversion 0961 /// \return the string representation of value in base. 0962 /// \details this template function specialization was added to suppress 0963 /// Coverity findings on IntToString() with unsigned types. 0964 template <> CRYPTOPP_DLL 0965 std::string IntToString<word64>(word64 value, unsigned int base); 0966 0967 /// \brief Converts an Integer to a string 0968 /// \param value the Integer to convert 0969 /// \param base the base to use during the conversion 0970 /// \return the string representation of value in base. 0971 /// \details This is a template specialization of IntToString(). Use it 0972 /// like IntToString(): 0973 /// <pre> 0974 /// // Print integer in base 10 0975 /// Integer n... 0976 /// std::string s = IntToString(n, 10); 0977 /// </pre> 0978 /// \details The string is presented with lowercase letters by default. A 0979 /// hack is available to switch to uppercase letters without modifying 0980 /// the function signature. 0981 /// <pre> 0982 /// // Print integer in base 16, uppercase letters 0983 /// Integer n... 0984 /// const unsigned int UPPER = (1 << 31); 0985 /// std::string s = IntToString(n, (UPPER | 16));</pre> 0986 template <> CRYPTOPP_DLL 0987 std::string IntToString<Integer>(Integer value, unsigned int base); 0988 0989 #if CRYPTOPP_MSC_VERSION 0990 # pragma warning(pop) 0991 #endif 0992 0993 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 0994 # pragma GCC diagnostic pop 0995 #endif 0996 0997 #define RETURN_IF_NONZERO(x) size_t returnedValue = x; if (returnedValue) return returnedValue 0998 0999 // this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack 1000 #define GETBYTE(x, y) (unsigned int)byte((x)>>(8*(y))) 1001 // these may be faster on other CPUs/compilers 1002 // #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255) 1003 // #define GETBYTE(x, y) (((byte *)&(x))[y]) 1004 1005 #define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) byte((x)>>(8*(y))) 1006 1007 /// \brief Returns the parity of a value 1008 /// \tparam T class or type 1009 /// \param value the value to provide the parity 1010 /// \return 1 if the number 1-bits in the value is odd, 0 otherwise 1011 template <class T> 1012 unsigned int Parity(T value) 1013 { 1014 for (unsigned int i=8*sizeof(value)/2; i>0; i/=2) 1015 value ^= value >> i; 1016 return (unsigned int)value&1; 1017 } 1018 1019 /// \brief Returns the number of 8-bit bytes or octets required for a value 1020 /// \tparam T class or type 1021 /// \param value the value to test 1022 /// \return the minimum number of 8-bit bytes or octets required to represent a value 1023 template <class T> 1024 unsigned int BytePrecision(const T &value) 1025 { 1026 if (!value) 1027 return 0; 1028 1029 unsigned int l=0, h=8*sizeof(value); 1030 while (h-l > 8) 1031 { 1032 unsigned int t = (l+h)/2; 1033 if (value >> t) 1034 l = t; 1035 else 1036 h = t; 1037 } 1038 1039 return h/8; 1040 } 1041 1042 /// \brief Returns the number of bits required for a value 1043 /// \tparam T class or type 1044 /// \param value the value to test 1045 /// \return the maximum number of bits required to represent a value. 1046 template <class T> 1047 unsigned int BitPrecision(const T &value) 1048 { 1049 if (!value) 1050 return 0; 1051 1052 unsigned int l=0, h=8*sizeof(value); 1053 1054 while (h-l > 1) 1055 { 1056 unsigned int t = (l+h)/2; 1057 if (value >> t) 1058 l = t; 1059 else 1060 h = t; 1061 } 1062 1063 return h; 1064 } 1065 1066 /// Determines the number of trailing 0-bits in a value 1067 /// \param v the 32-bit value to test 1068 /// \return the number of trailing 0-bits in v, starting at the least significant bit position 1069 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least 1070 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v. 1071 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position. 1072 inline unsigned int TrailingZeros(word32 v) 1073 { 1074 // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors 1075 // We don't enable for Microsoft because it requires a runtime check. 1076 // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx 1077 CRYPTOPP_ASSERT(v != 0); 1078 #if defined(__BMI__) 1079 return (unsigned int)_tzcnt_u32(v); 1080 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400) 1081 return (unsigned int)__builtin_ctz(v); 1082 #elif defined(CRYPTOPP_MSC_VERSION) && (CRYPTOPP_MSC_VERSION >= 1400) 1083 unsigned long result; 1084 _BitScanForward(&result, v); 1085 return static_cast<unsigned int>(result); 1086 #else 1087 // from http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup 1088 static const int MultiplyDeBruijnBitPosition[32] = 1089 { 1090 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 1091 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 1092 }; 1093 return MultiplyDeBruijnBitPosition[((word32)((v & -v) * 0x077CB531U)) >> 27]; 1094 #endif 1095 } 1096 1097 /// Determines the number of trailing 0-bits in a value 1098 /// \param v the 64-bit value to test 1099 /// \return the number of trailing 0-bits in v, starting at the least significant bit position 1100 /// \details TrailingZeros returns the number of trailing 0-bits in v, starting at the least 1101 /// significant bit position. The return value is undefined if there are no 1-bits set in the value v. 1102 /// \note The function does not return 0 if no 1-bits are set because 0 collides with a 1-bit at the 0-th position. 1103 inline unsigned int TrailingZeros(word64 v) 1104 { 1105 // GCC 4.7 and VS2012 provides tzcnt on AVX2/BMI enabled processors 1106 // We don't enable for Microsoft because it requires a runtime check. 1107 // http://msdn.microsoft.com/en-us/library/hh977023%28v=vs.110%29.aspx 1108 CRYPTOPP_ASSERT(v != 0); 1109 #if defined(__BMI__) && defined(__x86_64__) 1110 return (unsigned int)_tzcnt_u64(v); 1111 #elif defined(__GNUC__) && (CRYPTOPP_GCC_VERSION >= 30400) 1112 return (unsigned int)__builtin_ctzll(v); 1113 #elif defined(CRYPTOPP_MSC_VERSION) && (CRYPTOPP_MSC_VERSION >= 1400) && (defined(_M_X64) || defined(_M_IA64)) 1114 unsigned long result; 1115 _BitScanForward64(&result, v); 1116 return static_cast<unsigned int>(result); 1117 #else 1118 return word32(v) ? TrailingZeros(word32(v)) : 32 + TrailingZeros(word32(v>>32)); 1119 #endif 1120 } 1121 1122 /// \brief Truncates the value to the specified number of bits. 1123 /// \tparam T class or type 1124 /// \param value the value to truncate or mask 1125 /// \param bits the number of bits to truncate or mask 1126 /// \return the value truncated to the specified number of bits, starting at the least 1127 /// significant bit position 1128 /// \details This function masks the low-order bits of value and returns the result. The 1129 /// mask is created with <tt>(1 << bits) - 1</tt>. 1130 template <class T> 1131 inline T Crop(T value, size_t bits) 1132 { 1133 if (bits < 8*sizeof(value)) 1134 return T(value & ((T(1) << bits) - 1)); 1135 else 1136 return value; 1137 } 1138 1139 /// \brief Returns the number of 8-bit bytes or octets required for the specified number of bits 1140 /// \param bitCount the number of bits 1141 /// \return the minimum number of 8-bit bytes or octets required by bitCount 1142 /// \details BitsToBytes is effectively a ceiling function based on 8-bit bytes. 1143 inline size_t BitsToBytes(size_t bitCount) 1144 { 1145 return ((bitCount+7)/(8)); 1146 } 1147 1148 /// \brief Returns the number of words required for the specified number of bytes 1149 /// \param byteCount the number of bytes 1150 /// \return the minimum number of words required by byteCount 1151 /// \details BytesToWords is effectively a ceiling function based on <tt>WORD_SIZE</tt>. 1152 /// <tt>WORD_SIZE</tt> is defined in config.h 1153 inline size_t BytesToWords(size_t byteCount) 1154 { 1155 return ((byteCount+WORD_SIZE-1)/WORD_SIZE); 1156 } 1157 1158 /// \brief Returns the number of words required for the specified number of bits 1159 /// \param bitCount the number of bits 1160 /// \return the minimum number of words required by bitCount 1161 /// \details BitsToWords is effectively a ceiling function based on <tt>WORD_BITS</tt>. 1162 /// <tt>WORD_BITS</tt> is defined in config.h 1163 inline size_t BitsToWords(size_t bitCount) 1164 { 1165 return ((bitCount+WORD_BITS-1)/(WORD_BITS)); 1166 } 1167 1168 /// \brief Returns the number of double words required for the specified number of bits 1169 /// \param bitCount the number of bits 1170 /// \return the minimum number of double words required by bitCount 1171 /// \details BitsToDwords is effectively a ceiling function based on <tt>2*WORD_BITS</tt>. 1172 /// <tt>WORD_BITS</tt> is defined in config.h 1173 inline size_t BitsToDwords(size_t bitCount) 1174 { 1175 return ((bitCount+2*WORD_BITS-1)/(2*WORD_BITS)); 1176 } 1177 1178 /// Performs an XOR of a buffer with a mask 1179 /// \param buf the buffer to XOR with the mask 1180 /// \param mask the mask to XOR with the buffer 1181 /// \param count the size of the buffers, in bytes 1182 /// \details The function effectively visits each element in the buffers and performs 1183 /// <tt>buf[i] ^= mask[i]</tt>. buf and mask must be of equal size. 1184 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count); 1185 1186 /// Performs an XOR of an input buffer with a mask and stores the result in an output buffer 1187 /// \param output the destination buffer 1188 /// \param input the source buffer to XOR with the mask 1189 /// \param mask the mask buffer to XOR with the input buffer 1190 /// \param count the size of the buffers, in bytes 1191 /// \details The function effectively visits each element in the buffers and performs 1192 /// <tt>output[i] = input[i] ^ mask[i]</tt>. output, input and mask must be of equal size. 1193 CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *output, const byte *input, const byte *mask, size_t count); 1194 1195 /// \brief Performs a near constant-time comparison of two equally sized buffers 1196 /// \param buf1 the first buffer 1197 /// \param buf2 the second buffer 1198 /// \param count the size of the buffers, in bytes 1199 /// \details VerifyBufsEqual performs an XOR of the elements in two equally sized 1200 /// buffers and returns a result based on the XOR operation. A count of 0 returns 1201 /// true because two empty buffers are considered equal. 1202 /// \details The function is near constant-time because CPU micro-code timings could 1203 /// affect the "constant-ness". Calling code is responsible for mitigating timing 1204 /// attacks if the buffers are not equally sized. 1205 /// \sa ModPowerOf2 1206 CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count); 1207 1208 /// \brief Tests whether a value is a power of 2 1209 /// \param value the value to test 1210 /// \return true if value is a power of 2, false otherwise 1211 /// \details The function creates a mask of <tt>value - 1</tt> and returns the result 1212 /// of an AND operation compared to 0. If value is 0 or less than 0, then the function 1213 /// returns false. 1214 template <class T> 1215 inline bool IsPowerOf2(const T &value) 1216 { 1217 return value > 0 && (value & (value-1)) == 0; 1218 } 1219 1220 #if defined(__BMI__) 1221 template <> 1222 inline bool IsPowerOf2<word32>(const word32 &value) 1223 { 1224 return value > 0 && _blsr_u32(value) == 0; 1225 } 1226 1227 # if defined(__x86_64__) 1228 template <> 1229 inline bool IsPowerOf2<word64>(const word64 &value) 1230 { 1231 return value > 0 && _blsr_u64(value) == 0; 1232 } 1233 # endif // __x86_64__ 1234 #endif // __BMI__ 1235 1236 /// \brief Provide the minimum value for a type 1237 /// \tparam T type of class 1238 /// \return the minimum value of the type or class 1239 /// \details NumericLimitsMin() was introduced for Clang at <A 1240 /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364, 1241 /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>. 1242 /// \details NumericLimitsMin() requires a specialization for <tt>T</tt>, 1243 /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return 1244 /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize 1245 /// <tt>numeric_limits</tt> for the type. 1246 /// \since Crypto++ 8.1 1247 template<class T> 1248 inline T NumericLimitsMin() 1249 { 1250 CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized); 1251 return (std::numeric_limits<T>::min)(); 1252 } 1253 1254 /// \brief Provide the maximum value for a type 1255 /// \tparam T type of class 1256 /// \return the maximum value of the type or class 1257 /// \details NumericLimitsMax() was introduced for Clang at <A 1258 /// HREF="http://github.com/weidai11/cryptopp/issues/364">Issue 364, 1259 /// Apple Clang 6.0 and numeric_limits<word128>::max() returns 0</A>. 1260 /// \details NumericLimitsMax() requires a specialization for <tt>T</tt>, 1261 /// meaning <tt>std::numeric_limits<T>::is_specialized</tt> must return 1262 /// <tt>true</tt>. In the case of <tt>word128</tt> Clang did not specialize 1263 /// <tt>numeric_limits</tt> for the type. 1264 /// \since Crypto++ 8.1 1265 template<class T> 1266 inline T NumericLimitsMax() 1267 { 1268 CRYPTOPP_ASSERT(std::numeric_limits<T>::is_specialized); 1269 return (std::numeric_limits<T>::max)(); 1270 } 1271 1272 // NumericLimitsMin and NumericLimitsMax added for word128 types, 1273 // see http://github.com/weidai11/cryptopp/issues/364 1274 #if defined(CRYPTOPP_WORD128_AVAILABLE) 1275 template<> 1276 inline word128 NumericLimitsMin() 1277 { 1278 return 0; 1279 } 1280 template<> 1281 inline word128 NumericLimitsMax() 1282 { 1283 #if defined(CRYPTOPP_APPLE_CLANG_VERSION) 1284 return (static_cast<word128>(LWORD_MAX) << 64U) | LWORD_MAX; 1285 #else 1286 return (std::numeric_limits<word128>::max)(); 1287 #endif 1288 } 1289 #endif 1290 1291 /// \brief Performs a saturating subtract clamped at 0 1292 /// \tparam T1 class or type 1293 /// \tparam T2 class or type 1294 /// \param a the minuend 1295 /// \param b the subtrahend 1296 /// \return the difference produced by the saturating subtract 1297 /// \details Saturating arithmetic restricts results to a fixed range. Results that are 1298 /// less than 0 are clamped at 0. 1299 /// \details Use of saturating arithmetic in places can be advantageous because it can 1300 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>). 1301 template <class T1, class T2> 1302 inline T1 SaturatingSubtract(const T1 &a, const T2 &b) 1303 { 1304 // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html 1305 return T1((a > b) ? (a - b) : 0); 1306 } 1307 1308 /// \brief Performs a saturating subtract clamped at 1 1309 /// \tparam T1 class or type 1310 /// \tparam T2 class or type 1311 /// \param a the minuend 1312 /// \param b the subtrahend 1313 /// \return the difference produced by the saturating subtract 1314 /// \details Saturating arithmetic restricts results to a fixed range. Results that are 1315 /// less than 1 are clamped at 1. 1316 /// \details Use of saturating arithmetic in places can be advantageous because it can 1317 /// avoid a branch by using an instruction like a conditional move (<tt>CMOVE</tt>). 1318 template <class T1, class T2> 1319 inline T1 SaturatingSubtract1(const T1 &a, const T2 &b) 1320 { 1321 // Generated ASM of a typical clamp, http://gcc.gnu.org/ml/gcc-help/2014-10/msg00112.html 1322 return T1((a > b) ? (a - b) : 1); 1323 } 1324 1325 /// \brief Reduces a value to a power of 2 1326 /// \tparam T1 class or type 1327 /// \tparam T2 class or type 1328 /// \param a the first value 1329 /// \param b the second value 1330 /// \return ModPowerOf2() returns <tt>a & (b-1)</tt>. <tt>b</tt> must be a power of 2. 1331 /// Use IsPowerOf2() to determine if <tt>b</tt> is a suitable candidate. 1332 /// \sa IsPowerOf2 1333 template <class T1, class T2> 1334 inline T2 ModPowerOf2(const T1 &a, const T2 &b) 1335 { 1336 CRYPTOPP_ASSERT(IsPowerOf2(b)); 1337 // Coverity finding CID 170383 Overflowed return value (INTEGER_OVERFLOW) 1338 // Visual Studio and /RTCc warning, https://docs.microsoft.com/en-us/cpp/build/reference/rtc-run-time-error-checks 1339 return T2(a & SaturatingSubtract(b,1U)); 1340 } 1341 1342 /// \brief Rounds a value down to a multiple of a second value 1343 /// \tparam T1 class or type 1344 /// \tparam T2 class or type 1345 /// \param n the value to reduce 1346 /// \param m the value to reduce <tt>n</tt> to a multiple 1347 /// \return the possibly unmodified value \n 1348 /// \details RoundDownToMultipleOf is effectively a floor function based on m. The function returns 1349 /// the value <tt>n - n\%m</tt>. If n is a multiple of m, then the original value is returned. 1350 /// \note <tt>T1</tt> and <tt>T2</tt> should be unsigned arithmetic types. If <tt>T1</tt> or 1351 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in 1352 /// debug builds when practical, but allows you to perform the operation in release builds. 1353 template <class T1, class T2> 1354 inline T1 RoundDownToMultipleOf(const T1 &n, const T2 &m) 1355 { 1356 // http://github.com/weidai11/cryptopp/issues/364 1357 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000) 1358 CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer); 1359 CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer); 1360 #endif 1361 1362 CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0); 1363 CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0); 1364 1365 if (IsPowerOf2(m)) 1366 return n - ModPowerOf2(n, m); 1367 else 1368 return n - n%m; 1369 } 1370 1371 /// \brief Rounds a value up to a multiple of a second value 1372 /// \tparam T1 class or type 1373 /// \tparam T2 class or type 1374 /// \param n the value to reduce 1375 /// \param m the value to reduce <tt>n</tt> to a multiple 1376 /// \return the possibly unmodified value \n 1377 /// \details RoundUpToMultipleOf is effectively a ceiling function based on m. The function 1378 /// returns the value <tt>n + n\%m</tt>. If n is a multiple of m, then the original value is 1379 /// returned. If the value n would overflow, then an InvalidArgument exception is thrown. 1380 /// \note <tt>T1</tt> and <tt>T2</tt> should be unsigned arithmetic types. If <tt>T1</tt> or 1381 /// <tt>T2</tt> is signed, then the value should be non-negative. The library asserts in 1382 /// debug builds when practical, but allows you to perform the operation in release builds. 1383 template <class T1, class T2> 1384 inline T1 RoundUpToMultipleOf(const T1 &n, const T2 &m) 1385 { 1386 // http://github.com/weidai11/cryptopp/issues/364 1387 #if !defined(CRYPTOPP_APPLE_CLANG_VERSION) || (CRYPTOPP_APPLE_CLANG_VERSION >= 80000) 1388 CRYPTOPP_ASSERT(std::numeric_limits<T1>::is_integer); 1389 CRYPTOPP_ASSERT(std::numeric_limits<T2>::is_integer); 1390 #endif 1391 1392 CRYPTOPP_ASSERT(!std::numeric_limits<T1>::is_signed || n > 0); 1393 CRYPTOPP_ASSERT(!std::numeric_limits<T2>::is_signed || m > 0); 1394 1395 if (NumericLimitsMax<T1>() - m + 1 < n) 1396 throw InvalidArgument("RoundUpToMultipleOf: integer overflow"); 1397 return RoundDownToMultipleOf(T1(n+m-1), m); 1398 } 1399 1400 /// \brief Returns the minimum alignment requirements of a type 1401 /// \tparam T class or type 1402 /// \return the minimum alignment requirements of <tt>T</tt>, in bytes 1403 /// \details Internally the function calls C++11's <tt>alignof</tt> if 1404 /// available. If not available, then the function uses compiler 1405 /// specific extensions such as <tt>__alignof</tt> and <tt>_alignof_</tt>. 1406 /// If an extension is not available, then the function uses 1407 /// <tt>sizeof(T)</tt>. 1408 template <class T> 1409 inline unsigned int GetAlignmentOf() 1410 { 1411 #if defined(CRYPTOPP_CXX11_ALIGNOF) 1412 return alignof(T); 1413 #elif (CRYPTOPP_MSC_VERSION >= 1300) 1414 return __alignof(T); 1415 #elif defined(__GNUC__) 1416 return __alignof__(T); 1417 #elif defined(__SUNPRO_CC) 1418 return __alignof__(T); 1419 #elif defined(__IBM_ALIGNOF__) 1420 return __alignof__(T); 1421 #elif CRYPTOPP_BOOL_SLOW_WORD64 1422 return UnsignedMin(4U, sizeof(T)); 1423 #else 1424 return sizeof(T); 1425 #endif 1426 } 1427 1428 /// \brief Determines whether ptr is aligned to a minimum value 1429 /// \param ptr the pointer being checked for alignment 1430 /// \param alignment the alignment value to test the pointer against 1431 /// \return true if <tt>ptr</tt> is aligned on at least <tt>alignment</tt> 1432 /// boundary, false otherwise 1433 /// \details Internally the function tests whether alignment is 1. If so, 1434 /// the function returns true. If not, then the function effectively 1435 /// performs a modular reduction and returns true if the residue is 0. 1436 inline bool IsAlignedOn(const void *ptr, unsigned int alignment) 1437 { 1438 const uintptr_t x = reinterpret_cast<uintptr_t>(ptr); 1439 return alignment==1 || (IsPowerOf2(alignment) ? ModPowerOf2(x, alignment) == 0 : x % alignment == 0); 1440 } 1441 1442 /// \brief Determines whether ptr is minimally aligned 1443 /// \tparam T class or type 1444 /// \param ptr the pointer to check for alignment 1445 /// \return true if <tt>ptr</tt> is aligned to at least <tt>T</tt> 1446 /// boundary, false otherwise 1447 /// \details Internally the function calls IsAlignedOn with a second 1448 /// parameter of GetAlignmentOf<T>. 1449 template <class T> 1450 inline bool IsAligned(const void *ptr) 1451 { 1452 return IsAlignedOn(ptr, GetAlignmentOf<T>()); 1453 } 1454 1455 #if (CRYPTOPP_LITTLE_ENDIAN) 1456 typedef LittleEndian NativeByteOrder; 1457 #elif (CRYPTOPP_BIG_ENDIAN) 1458 typedef BigEndian NativeByteOrder; 1459 #else 1460 # error "Unable to determine endianness" 1461 #endif 1462 1463 /// \brief Returns NativeByteOrder as an enumerated ByteOrder value 1464 /// \return LittleEndian if the native byte order is little-endian, 1465 /// and BigEndian if the native byte order is big-endian 1466 /// \details NativeByteOrder is a typedef depending on the platform. 1467 /// If CRYPTOPP_LITTLE_ENDIAN is set in config.h, then 1468 /// GetNativeByteOrder returns LittleEndian. If CRYPTOPP_BIG_ENDIAN 1469 /// is set, then GetNativeByteOrder returns BigEndian. 1470 /// \note There are other byte orders besides little- and big-endian, 1471 /// and they include bi-endian and PDP-endian. If a system is neither 1472 /// little-endian nor big-endian, then a compile time error occurs. 1473 inline ByteOrder GetNativeByteOrder() 1474 { 1475 return NativeByteOrder::ToEnum(); 1476 } 1477 1478 /// \brief Determines whether order follows native byte ordering 1479 /// \param order the ordering being tested against native byte ordering 1480 /// \return true if order follows native byte ordering, false otherwise 1481 inline bool NativeByteOrderIs(ByteOrder order) 1482 { 1483 return order == GetNativeByteOrder(); 1484 } 1485 1486 /// \brief Returns the direction the cipher is being operated 1487 /// \tparam T class or type 1488 /// \param obj the cipher object being queried 1489 /// \return ENCRYPTION if the cipher obj is being operated in its forward direction, 1490 /// DECRYPTION otherwise 1491 /// \details A cipher can be operated in a "forward" direction (encryption) or a "reverse" 1492 /// direction (decryption). The operations do not have to be symmetric, meaning a second 1493 /// application of the transformation does not necessarily return the original message. 1494 /// That is, <tt>E(D(m))</tt> may not equal <tt>E(E(m))</tt>; and <tt>D(E(m))</tt> may not 1495 /// equal <tt>D(D(m))</tt>. 1496 template <class T> 1497 inline CipherDir GetCipherDir(const T &obj) 1498 { 1499 return obj.IsForwardTransformation() ? ENCRYPTION : DECRYPTION; 1500 } 1501 1502 /// \brief Performs an addition with carry on a block of bytes 1503 /// \param inout the byte block 1504 /// \param size the size of the block, in bytes 1505 /// \details Performs an addition with carry by adding 1 on a block of bytes starting at the least 1506 /// significant byte. Once carry is 0, the function terminates and returns to the caller. 1507 /// \note The function is not constant time because it stops processing when the carry is 0. 1508 inline void IncrementCounterByOne(byte *inout, unsigned int size) 1509 { 1510 CRYPTOPP_ASSERT(inout != NULLPTR); 1511 1512 unsigned int carry=1; 1513 while (carry && size != 0) 1514 { 1515 // On carry inout[n] equals 0 1516 carry = ! ++inout[size-1]; 1517 size--; 1518 } 1519 } 1520 1521 /// \brief Performs an addition with carry on a block of bytes 1522 /// \param output the destination block of bytes 1523 /// \param input the source block of bytes 1524 /// \param size the size of the block 1525 /// \details Performs an addition with carry on a block of bytes starting at the least significant 1526 /// byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy. 1527 /// \details The function is close to near-constant time because it operates on all the bytes in the blocks. 1528 inline void IncrementCounterByOne(byte *output, const byte *input, unsigned int size) 1529 { 1530 CRYPTOPP_ASSERT(output != NULLPTR); 1531 CRYPTOPP_ASSERT(input != NULLPTR); 1532 1533 unsigned int carry=1; 1534 while (carry && size != 0) 1535 { 1536 // On carry output[n] equals 0 1537 carry = ! (output[size-1] = input[size-1] + 1); 1538 size--; 1539 } 1540 1541 while (size != 0) 1542 { 1543 output[size-1] = input[size-1]; 1544 size--; 1545 } 1546 } 1547 1548 /// \brief Performs a branch-less swap of values a and b if condition c is true 1549 /// \tparam T class or type 1550 /// \param c the condition to perform the swap 1551 /// \param a the first value 1552 /// \param b the second value 1553 template <class T> 1554 inline void ConditionalSwap(bool c, T &a, T &b) 1555 { 1556 T t = c * (a ^ b); 1557 a ^= t; 1558 b ^= t; 1559 } 1560 1561 /// \brief Performs a branch-less swap of pointers a and b if condition c is true 1562 /// \tparam T class or type 1563 /// \param c the condition to perform the swap 1564 /// \param a the first pointer 1565 /// \param b the second pointer 1566 template <class T> 1567 inline void ConditionalSwapPointers(bool c, T &a, T &b) 1568 { 1569 ptrdiff_t t = size_t(c) * (a - b); 1570 a -= t; 1571 b += t; 1572 } 1573 1574 // see http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/protect-secrets.html 1575 // and http://www.securecoding.cert.org/confluence/display/cplusplus/MSC06-CPP.+Be+aware+of+compiler+optimization+when+dealing+with+sensitive+data 1576 1577 /// \brief Sets each element of an array to 0 1578 /// \tparam T class or type 1579 /// \param buf an array of elements 1580 /// \param n the number of elements in the array 1581 /// \details The operation performs a wipe or zeroization. The function 1582 /// attempts to survive optimizations and dead code removal. 1583 template <class T> 1584 void SecureWipeBuffer(T *buf, size_t n) 1585 { 1586 // GCC 4.3.2 on Cygwin optimizes away the first store if this 1587 // loop is done in the forward direction 1588 volatile T *p = buf+n; 1589 while (n--) 1590 *(--p) = 0; 1591 } 1592 1593 #if !defined(CRYPTOPP_DISABLE_ASM) && \ 1594 (CRYPTOPP_MSC_VERSION >= 1400 || defined(__GNUC__)) && \ 1595 (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86) 1596 1597 /// \brief Sets each byte of an array to 0 1598 /// \param buf an array of bytes 1599 /// \param n the number of elements in the array 1600 /// \details The operation performs a wipe or zeroization. The function 1601 /// attempts to survive optimizations and dead code removal. 1602 template<> inline void SecureWipeBuffer(byte *buf, size_t n) 1603 { 1604 volatile byte *p = buf; 1605 #ifdef __GNUC__ 1606 asm volatile("rep stosb" : "+c"(n), "+D"(p) : "a"(0) : "memory"); 1607 #else 1608 __stosb(reinterpret_cast<byte *>(reinterpret_cast<size_t>(p)), 0, n); 1609 #endif 1610 } 1611 1612 /// \brief Sets each 16-bit element of an array to 0 1613 /// \param buf an array of 16-bit words 1614 /// \param n the number of elements in the array 1615 /// \details The operation performs a wipe or zeroization. The function 1616 /// attempts to survive optimizations and dead code removal. 1617 template<> inline void SecureWipeBuffer(word16 *buf, size_t n) 1618 { 1619 volatile word16 *p = buf; 1620 #ifdef __GNUC__ 1621 asm volatile("rep stosw" : "+c"(n), "+D"(p) : "a"(0) : "memory"); 1622 #else 1623 __stosw(reinterpret_cast<word16 *>(reinterpret_cast<size_t>(p)), 0, n); 1624 #endif 1625 } 1626 1627 /// \brief Sets each 32-bit element of an array to 0 1628 /// \param buf an array of 32-bit words 1629 /// \param n the number of elements in the array 1630 /// \details The operation performs a wipe or zeroization. The function 1631 /// attempts to survive optimizations and dead code removal. 1632 template<> inline void SecureWipeBuffer(word32 *buf, size_t n) 1633 { 1634 volatile word32 *p = buf; 1635 #ifdef __GNUC__ 1636 asm volatile("rep stosl" : "+c"(n), "+D"(p) : "a"(0) : "memory"); 1637 #else 1638 __stosd(reinterpret_cast<unsigned long *>(reinterpret_cast<size_t>(p)), 0, n); 1639 #endif 1640 } 1641 1642 /// \brief Sets each 64-bit element of an array to 0 1643 /// \param buf an array of 64-bit words 1644 /// \param n the number of elements in the array 1645 /// \details The operation performs a wipe or zeroization. The function 1646 /// attempts to survive optimizations and dead code removal. 1647 template<> inline void SecureWipeBuffer(word64 *buf, size_t n) 1648 { 1649 #if CRYPTOPP_BOOL_X64 1650 volatile word64 *p = buf; 1651 # ifdef __GNUC__ 1652 asm volatile("rep stosq" : "+c"(n), "+D"(p) : "a"(0) : "memory"); 1653 # else 1654 __stosq(const_cast<word64 *>(p), 0, n); 1655 # endif 1656 #else 1657 SecureWipeBuffer(reinterpret_cast<word32 *>(buf), 2*n); 1658 #endif 1659 } 1660 1661 #endif // CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 1662 1663 #if !defined(CRYPTOPP_DISABLE_ASM) && (CRYPTOPP_MSC_VERSION >= 1700) && defined(_M_ARM) 1664 template<> inline void SecureWipeBuffer(byte *buf, size_t n) 1665 { 1666 char *p = reinterpret_cast<char*>(buf+n); 1667 while (n--) 1668 __iso_volatile_store8(--p, 0); 1669 } 1670 1671 template<> inline void SecureWipeBuffer(word16 *buf, size_t n) 1672 { 1673 short *p = reinterpret_cast<short*>(buf+n); 1674 while (n--) 1675 __iso_volatile_store16(--p, 0); 1676 } 1677 1678 template<> inline void SecureWipeBuffer(word32 *buf, size_t n) 1679 { 1680 int *p = reinterpret_cast<int*>(buf+n); 1681 while (n--) 1682 __iso_volatile_store32(--p, 0); 1683 } 1684 1685 template<> inline void SecureWipeBuffer(word64 *buf, size_t n) 1686 { 1687 __int64 *p = reinterpret_cast<__int64*>(buf+n); 1688 while (n--) 1689 __iso_volatile_store64(--p, 0); 1690 } 1691 #endif 1692 1693 /// \brief Sets each element of an array to 0 1694 /// \tparam T class or type 1695 /// \param buf an array of elements 1696 /// \param n the number of elements in the array 1697 /// \details The operation performs a wipe or zeroization. The function 1698 /// attempts to survive optimizations and dead code removal. 1699 template <class T> 1700 inline void SecureWipeArray(T *buf, size_t n) 1701 { 1702 if (sizeof(T) % 8 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word64>() == 0) 1703 SecureWipeBuffer(reinterpret_cast<word64 *>(static_cast<void *>(buf)), n * (sizeof(T)/8)); 1704 else if (sizeof(T) % 4 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word32>() == 0) 1705 SecureWipeBuffer(reinterpret_cast<word32 *>(static_cast<void *>(buf)), n * (sizeof(T)/4)); 1706 else if (sizeof(T) % 2 == 0 && GetAlignmentOf<T>() % GetAlignmentOf<word16>() == 0) 1707 SecureWipeBuffer(reinterpret_cast<word16 *>(static_cast<void *>(buf)), n * (sizeof(T)/2)); 1708 else 1709 SecureWipeBuffer(reinterpret_cast<byte *>(static_cast<void *>(buf)), n * sizeof(T)); 1710 } 1711 1712 /// \brief Converts a wide character C-string to a multibyte string 1713 /// \param str C-string consisting of wide characters 1714 /// \param throwOnError flag indicating the function should throw on error 1715 /// \return str converted to a multibyte string or an empty string. 1716 /// \details StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under 1717 /// the executing thread's locale. A locale must be set before using this function, and it can be 1718 /// set with std::setlocale() if needed. Upon success, the converted string is returned. 1719 /// \details Upon failure with throwOnError as false, the function returns an empty string. If 1720 /// throwOnError as true, the function throws an InvalidArgument() exception. 1721 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8 1722 /// (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available, 1723 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception. 1724 std::string StringNarrow(const wchar_t *str, bool throwOnError = true); 1725 1726 /// \brief Converts a multibyte C-string to a wide character string 1727 /// \param str C-string consisting of wide characters 1728 /// \param throwOnError flag indicating the function should throw on error 1729 /// \return str converted to a multibyte string or an empty string. 1730 /// \details StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under 1731 /// the executing thread's locale. A locale must be set before using this function, and it can be 1732 /// set with std::setlocale() if needed. Upon success, the converted string is returned. 1733 /// \details Upon failure with throwOnError as false, the function returns an empty string. If 1734 /// throwOnError as true, the function throws an InvalidArgument() exception. 1735 /// \note If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8) 1736 /// to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available, 1737 /// then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception. 1738 std::wstring StringWiden(const char *str, bool throwOnError = true); 1739 1740 // ************** rotate functions *************** 1741 1742 /// \brief Performs a left rotate 1743 /// \tparam R the number of bit positions to rotate the value 1744 /// \tparam T the word type 1745 /// \param x the value to rotate 1746 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1747 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1748 /// Use rotlMod if the rotate amount R is outside the range. 1749 /// \details Use rotlConstant when the rotate amount is constant. The template function was added 1750 /// because Clang did not propagate the constant when passed as a function parameter. Clang's 1751 /// need for a constexpr meant rotlFixed failed to compile on occasion. 1752 /// \note rotlConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1753 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1754 /// counterparts. 1755 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1756 /// \since Crypto++ 6.0 1757 template <unsigned int R, class T> inline T rotlConstant(T x) 1758 { 1759 // Portable rotate that reduces to single instruction... 1760 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157, 1761 // http://software.intel.com/en-us/forums/topic/580884 1762 // and http://llvm.org/bugs/show_bug.cgi?id=24226 1763 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1764 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1765 CRYPTOPP_ASSERT(static_cast<int>(R) < THIS_SIZE); 1766 return T((x<<R)|(x>>(-R&MASK))); 1767 } 1768 1769 /// \brief Performs a right rotate 1770 /// \tparam R the number of bit positions to rotate the value 1771 /// \tparam T the word type 1772 /// \param x the value to rotate 1773 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1774 /// \details R must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1775 /// Use rotrMod if the rotate amount R is outside the range. 1776 /// \details Use rotrConstant when the rotate amount is constant. The template function was added 1777 /// because Clang did not propagate the constant when passed as a function parameter. Clang's 1778 /// need for a constexpr meant rotrFixed failed to compile on occasion. 1779 /// \note rotrConstant attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1780 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1781 /// counterparts. 1782 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1783 template <unsigned int R, class T> inline T rotrConstant(T x) 1784 { 1785 // Portable rotate that reduces to single instruction... 1786 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157, 1787 // http://software.intel.com/en-us/forums/topic/580884 1788 // and http://llvm.org/bugs/show_bug.cgi?id=24226 1789 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1790 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1791 CRYPTOPP_ASSERT(static_cast<int>(R) < THIS_SIZE); 1792 return T((x >> R)|(x<<(-R&MASK))); 1793 } 1794 1795 /// \brief Performs a left rotate 1796 /// \tparam T the word type 1797 /// \param x the value to rotate 1798 /// \param y the number of bit positions to rotate the value 1799 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1800 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1801 /// Use rotlMod if the rotate amount y is outside the range. 1802 /// \note rotlFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1803 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1804 /// counterparts. New code should use <tt>rotlConstant</tt>, which accepts the rotate amount as a 1805 /// template parameter. 1806 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1807 /// \since Crypto++ 6.0 1808 template <class T> inline T rotlFixed(T x, unsigned int y) 1809 { 1810 // Portable rotate that reduces to single instruction... 1811 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157, 1812 // http://software.intel.com/en-us/forums/topic/580884 1813 // and http://llvm.org/bugs/show_bug.cgi?id=24226 1814 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1815 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1816 CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE); 1817 return T((x<<y)|(x>>(-y&MASK))); 1818 } 1819 1820 /// \brief Performs a right rotate 1821 /// \tparam T the word type 1822 /// \param x the value to rotate 1823 /// \param y the number of bit positions to rotate the value 1824 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1825 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1826 /// Use rotrMod if the rotate amount y is outside the range. 1827 /// \note rotrFixed attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1828 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1829 /// counterparts. New code should use <tt>rotrConstant</tt>, which accepts the rotate amount as a 1830 /// template parameter. 1831 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1832 /// \since Crypto++ 3.0 1833 template <class T> inline T rotrFixed(T x, unsigned int y) 1834 { 1835 // Portable rotate that reduces to single instruction... 1836 // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57157, 1837 // http://software.intel.com/en-us/forums/topic/580884 1838 // and http://llvm.org/bugs/show_bug.cgi?id=24226 1839 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1840 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1841 CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE); 1842 return T((x >> y)|(x<<(-y&MASK))); 1843 } 1844 1845 /// \brief Performs a left rotate 1846 /// \tparam T the word type 1847 /// \param x the value to rotate 1848 /// \param y the number of bit positions to rotate the value 1849 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1850 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1851 /// Use rotlMod if the rotate amount y is outside the range. 1852 /// \note rotlVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1853 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1854 /// counterparts. 1855 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1856 /// \since Crypto++ 3.0 1857 template <class T> inline T rotlVariable(T x, unsigned int y) 1858 { 1859 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1860 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1861 CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE); 1862 return T((x<<y)|(x>>(-y&MASK))); 1863 } 1864 1865 /// \brief Performs a right rotate 1866 /// \tparam T the word type 1867 /// \param x the value to rotate 1868 /// \param y the number of bit positions to rotate the value 1869 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1870 /// \details y must be in the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1871 /// Use rotrMod if the rotate amount y is outside the range. 1872 /// \note rotrVariable attempts to enlist a <tt>rotate IMM</tt> instruction because its often faster 1873 /// than a <tt>rotate REG</tt>. Immediate rotates can be up to three times faster than their register 1874 /// counterparts. 1875 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1876 /// \since Crypto++ 3.0 1877 template <class T> inline T rotrVariable(T x, unsigned int y) 1878 { 1879 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1880 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1881 CRYPTOPP_ASSERT(static_cast<int>(y) < THIS_SIZE); 1882 return T((x>>y)|(x<<(-y&MASK))); 1883 } 1884 1885 /// \brief Performs a left rotate 1886 /// \tparam T the word type 1887 /// \param x the value to rotate 1888 /// \param y the number of bit positions to rotate the value 1889 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1890 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1891 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>. 1892 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1893 /// \since Crypto++ 3.0 1894 template <class T> inline T rotlMod(T x, unsigned int y) 1895 { 1896 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1897 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1898 return T((x<<(y&MASK))|(x>>(-y&MASK))); 1899 } 1900 1901 /// \brief Performs a right rotate 1902 /// \tparam T the word type 1903 /// \param x the value to rotate 1904 /// \param y the number of bit positions to rotate the value 1905 /// \details This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide. 1906 /// \details y is reduced to the range <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1907 /// \note rotrVariable will use either <tt>rotate IMM</tt> or <tt>rotate REG</tt>. 1908 /// \sa rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable 1909 /// \since Crypto++ 3.0 1910 template <class T> inline T rotrMod(T x, unsigned int y) 1911 { 1912 CRYPTOPP_CONSTANT(THIS_SIZE = sizeof(T)*8); 1913 CRYPTOPP_CONSTANT(MASK = THIS_SIZE-1); 1914 return T((x>>(y&MASK))|(x<<(-y&MASK))); 1915 } 1916 1917 #ifdef CRYPTOPP_MSC_VERSION 1918 1919 /// \brief Performs a left rotate 1920 /// \tparam T the word type 1921 /// \param x the 32-bit value to rotate 1922 /// \param y the number of bit positions to rotate the value 1923 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 1924 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 1925 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1926 /// \note rotlFixed will assert in Debug builds if is outside the allowed range. 1927 /// \since Crypto++ 3.0 1928 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y) 1929 { 1930 // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules. 1931 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 1932 return y ? _lrotl(x, static_cast<byte>(y)) : x; 1933 } 1934 1935 /// \brief Performs a right rotate 1936 /// \tparam T the word type 1937 /// \param x the 32-bit value to rotate 1938 /// \param y the number of bit positions to rotate the value 1939 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 1940 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 1941 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1942 /// \note rotrFixed will assert in Debug builds if is outside the allowed range. 1943 /// \since Crypto++ 3.0 1944 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y) 1945 { 1946 // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules. 1947 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 1948 return y ? _lrotr(x, static_cast<byte>(y)) : x; 1949 } 1950 1951 /// \brief Performs a left rotate 1952 /// \tparam T the word type 1953 /// \param x the 32-bit value to rotate 1954 /// \param y the number of bit positions to rotate the value 1955 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 1956 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 1957 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1958 /// \note rotlVariable will assert in Debug builds if is outside the allowed range. 1959 /// \since Crypto++ 3.0 1960 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y) 1961 { 1962 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 1963 return _lrotl(x, static_cast<byte>(y)); 1964 } 1965 1966 /// \brief Performs a right rotate 1967 /// \tparam T the word type 1968 /// \param x the 32-bit value to rotate 1969 /// \param y the number of bit positions to rotate the value 1970 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 1971 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 1972 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1973 /// \note rotrVariable will assert in Debug builds if is outside the allowed range. 1974 /// \since Crypto++ 3.0 1975 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y) 1976 { 1977 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 1978 return _lrotr(x, static_cast<byte>(y)); 1979 } 1980 1981 /// \brief Performs a left rotate 1982 /// \tparam T the word type 1983 /// \param x the 32-bit value to rotate 1984 /// \param y the number of bit positions to rotate the value 1985 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 1986 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 1987 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 1988 /// \since Crypto++ 3.0 1989 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y) 1990 { 1991 y %= 8*sizeof(x); 1992 return _lrotl(x, static_cast<byte>(y)); 1993 } 1994 1995 /// \brief Performs a right rotate 1996 /// \tparam T the word type 1997 /// \param x the 32-bit value to rotate 1998 /// \param y the number of bit positions to rotate the value 1999 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 2000 /// <stdlib.h>. The value x to be rotated is 32-bits. y must be in the range 2001 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2002 /// \since Crypto++ 3.0 2003 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y) 2004 { 2005 y %= 8*sizeof(x); 2006 return _lrotr(x, static_cast<byte>(y)); 2007 } 2008 2009 #endif // #ifdef CRYPTOPP_MSC_VERSION 2010 2011 #if (CRYPTOPP_MSC_VERSION >= 1400) || (defined(CRYPTOPP_MSC_VERSION) && !defined(_DLL)) 2012 // Intel C++ Compiler 10.0 calls a function instead of using the rotate instruction when using these instructions 2013 2014 /// \brief Performs a left rotate 2015 /// \tparam T the word type 2016 /// \param x the 64-bit value to rotate 2017 /// \param y the number of bit positions to rotate the value 2018 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 2019 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2020 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2021 /// \note rotrFixed will assert in Debug builds if is outside the allowed range. 2022 /// \since Crypto++ 3.0 2023 template<> inline word64 rotlFixed<word64>(word64 x, unsigned int y) 2024 { 2025 // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules. 2026 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2027 return y ? _rotl64(x, static_cast<byte>(y)) : x; 2028 } 2029 2030 /// \brief Performs a right rotate 2031 /// \tparam T the word type 2032 /// \param x the 64-bit value to rotate 2033 /// \param y the number of bit positions to rotate the value 2034 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 2035 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2036 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2037 /// \note rotrFixed will assert in Debug builds if is outside the allowed range. 2038 /// \since Crypto++ 3.0 2039 template<> inline word64 rotrFixed<word64>(word64 x, unsigned int y) 2040 { 2041 // Uses Microsoft <stdlib.h> call, bound to C/C++ language rules. 2042 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2043 return y ? _rotr64(x, static_cast<byte>(y)) : x; 2044 } 2045 2046 /// \brief Performs a left rotate 2047 /// \tparam T the word type 2048 /// \param x the 64-bit value to rotate 2049 /// \param y the number of bit positions to rotate the value 2050 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 2051 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2052 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2053 /// \note rotlVariable will assert in Debug builds if is outside the allowed range. 2054 /// \since Crypto++ 3.0 2055 template<> inline word64 rotlVariable<word64>(word64 x, unsigned int y) 2056 { 2057 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2058 return _rotl64(x, static_cast<byte>(y)); 2059 } 2060 2061 /// \brief Performs a right rotate 2062 /// \tparam T the word type 2063 /// \param x the 64-bit value to rotate 2064 /// \param y the number of bit positions to rotate the value 2065 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 2066 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2067 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2068 /// \note rotrVariable will assert in Debug builds if is outside the allowed range. 2069 /// \since Crypto++ 3.0 2070 template<> inline word64 rotrVariable<word64>(word64 x, unsigned int y) 2071 { 2072 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2073 return y ? _rotr64(x, static_cast<byte>(y)) : x; 2074 } 2075 2076 /// \brief Performs a left rotate 2077 /// \tparam T the word type 2078 /// \param x the 64-bit value to rotate 2079 /// \param y the number of bit positions to rotate the value 2080 /// \details This is a Microsoft specific implementation using <tt>_lrotl</tt> provided by 2081 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2082 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2083 /// \since Crypto++ 3.0 2084 template<> inline word64 rotlMod<word64>(word64 x, unsigned int y) 2085 { 2086 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2087 return y ? _rotl64(x, static_cast<byte>(y)) : x; 2088 } 2089 2090 /// \brief Performs a right rotate 2091 /// \tparam T the word type 2092 /// \param x the 64-bit value to rotate 2093 /// \param y the number of bit positions to rotate the value 2094 /// \details This is a Microsoft specific implementation using <tt>_lrotr</tt> provided by 2095 /// <stdlib.h>. The value x to be rotated is 64-bits. y must be in the range 2096 /// <tt>[0, sizeof(T)*8 - 1]</tt> to avoid undefined behavior. 2097 /// \since Crypto++ 3.0 2098 template<> inline word64 rotrMod<word64>(word64 x, unsigned int y) 2099 { 2100 CRYPTOPP_ASSERT(y < 8*sizeof(x)); 2101 return y ? _rotr64(x, static_cast<byte>(y)) : x; 2102 } 2103 2104 #endif // #if CRYPTOPP_MSC_VERSION >= 1310 2105 2106 #if CRYPTOPP_MSC_VERSION >= 1400 && !defined(__INTEL_COMPILER) 2107 // Intel C++ Compiler 10.0 gives undefined externals with these 2108 template<> inline word16 rotlFixed<word16>(word16 x, unsigned int y) 2109 { 2110 // Intrinsic, not bound to C/C++ language rules. 2111 return _rotl16(x, static_cast<byte>(y)); 2112 } 2113 2114 template<> inline word16 rotrFixed<word16>(word16 x, unsigned int y) 2115 { 2116 // Intrinsic, not bound to C/C++ language rules. 2117 return _rotr16(x, static_cast<byte>(y)); 2118 } 2119 2120 template<> inline word16 rotlVariable<word16>(word16 x, unsigned int y) 2121 { 2122 return _rotl16(x, static_cast<byte>(y)); 2123 } 2124 2125 template<> inline word16 rotrVariable<word16>(word16 x, unsigned int y) 2126 { 2127 return _rotr16(x, static_cast<byte>(y)); 2128 } 2129 2130 template<> inline word16 rotlMod<word16>(word16 x, unsigned int y) 2131 { 2132 return _rotl16(x, static_cast<byte>(y)); 2133 } 2134 2135 template<> inline word16 rotrMod<word16>(word16 x, unsigned int y) 2136 { 2137 return _rotr16(x, static_cast<byte>(y)); 2138 } 2139 2140 template<> inline byte rotlFixed<byte>(byte x, unsigned int y) 2141 { 2142 // Intrinsic, not bound to C/C++ language rules. 2143 return _rotl8(x, static_cast<byte>(y)); 2144 } 2145 2146 template<> inline byte rotrFixed<byte>(byte x, unsigned int y) 2147 { 2148 // Intrinsic, not bound to C/C++ language rules. 2149 return _rotr8(x, static_cast<byte>(y)); 2150 } 2151 2152 template<> inline byte rotlVariable<byte>(byte x, unsigned int y) 2153 { 2154 return _rotl8(x, static_cast<byte>(y)); 2155 } 2156 2157 template<> inline byte rotrVariable<byte>(byte x, unsigned int y) 2158 { 2159 return _rotr8(x, static_cast<byte>(y)); 2160 } 2161 2162 template<> inline byte rotlMod<byte>(byte x, unsigned int y) 2163 { 2164 return _rotl8(x, static_cast<byte>(y)); 2165 } 2166 2167 template<> inline byte rotrMod<byte>(byte x, unsigned int y) 2168 { 2169 return _rotr8(x, static_cast<byte>(y)); 2170 } 2171 2172 #endif // #if CRYPTOPP_MSC_VERSION >= 1400 2173 2174 #if (defined(__MWERKS__) && TARGET_CPU_PPC) 2175 2176 template<> inline word32 rotlFixed<word32>(word32 x, unsigned int y) 2177 { 2178 CRYPTOPP_ASSERT(y < 32); 2179 return y ? __rlwinm(x,y,0,31) : x; 2180 } 2181 2182 template<> inline word32 rotrFixed<word32>(word32 x, unsigned int y) 2183 { 2184 CRYPTOPP_ASSERT(y < 32); 2185 return y ? __rlwinm(x,32-y,0,31) : x; 2186 } 2187 2188 template<> inline word32 rotlVariable<word32>(word32 x, unsigned int y) 2189 { 2190 CRYPTOPP_ASSERT(y < 32); 2191 return (__rlwnm(x,y,0,31)); 2192 } 2193 2194 template<> inline word32 rotrVariable<word32>(word32 x, unsigned int y) 2195 { 2196 CRYPTOPP_ASSERT(y < 32); 2197 return (__rlwnm(x,32-y,0,31)); 2198 } 2199 2200 template<> inline word32 rotlMod<word32>(word32 x, unsigned int y) 2201 { 2202 return (__rlwnm(x,y,0,31)); 2203 } 2204 2205 template<> inline word32 rotrMod<word32>(word32 x, unsigned int y) 2206 { 2207 return (__rlwnm(x,32-y,0,31)); 2208 } 2209 2210 #endif // __MWERKS__ && TARGET_CPU_PPC 2211 2212 // ************** endian reversal *************** 2213 2214 /// \brief Gets a byte from a value 2215 /// \param order the ByteOrder of the value 2216 /// \param value the value to retrieve the byte 2217 /// \param index the location of the byte to retrieve 2218 template <class T> 2219 inline unsigned int GetByte(ByteOrder order, T value, unsigned int index) 2220 { 2221 if (order == LITTLE_ENDIAN_ORDER) 2222 return GETBYTE(value, index); 2223 else 2224 return GETBYTE(value, sizeof(T)-index-1); 2225 } 2226 2227 /// \brief Reverses bytes in a 8-bit value 2228 /// \param value the 8-bit value to reverse 2229 /// \note ByteReverse returns the value passed to it since there is nothing to 2230 /// reverse. 2231 inline byte ByteReverse(byte value) 2232 { 2233 return value; 2234 } 2235 2236 /// \brief Reverses bytes in a 16-bit value 2237 /// \param value the 16-bit value to reverse 2238 /// \details ByteReverse calls bswap if available. Otherwise the function 2239 /// performs a 8-bit rotate on the word16. 2240 inline word16 ByteReverse(word16 value) 2241 { 2242 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE) 2243 return bswap_16(value); 2244 #elif (CRYPTOPP_MSC_VERSION >= 1400) || (defined(CRYPTOPP_MSC_VERSION) && !defined(_DLL)) 2245 return _byteswap_ushort(value); 2246 #else 2247 return rotlFixed(value, 8U); 2248 #endif 2249 } 2250 2251 /// \brief Reverses bytes in a 32-bit value 2252 /// \param value the 32-bit value to reverse 2253 /// \details ByteReverse calls bswap if available. Otherwise the function uses 2254 /// a combination of rotates on the word32. 2255 inline word32 ByteReverse(word32 value) 2256 { 2257 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE) 2258 return bswap_32(value); 2259 #elif defined(CRYPTOPP_ARM_BYTEREV_AVAILABLE) 2260 word32 rvalue; 2261 __asm__ ("rev %0, %1" : "=r" (rvalue) : "r" (value)); 2262 return rvalue; 2263 #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) 2264 __asm__ ("bswap %0" : "=r" (value) : "0" (value)); 2265 return value; 2266 #elif defined(__MWERKS__) && TARGET_CPU_PPC 2267 return (word32)__lwbrx(&value,0); 2268 #elif (CRYPTOPP_MSC_VERSION >= 1400) || (defined(CRYPTOPP_MSC_VERSION) && !defined(_DLL)) 2269 return _byteswap_ulong(value); 2270 #elif CRYPTOPP_FAST_ROTATE(32) && !defined(__xlC__) 2271 // 5 instructions with rotate instruction, 9 without 2272 return (rotrFixed(value, 8U) & 0xff00ff00) | (rotlFixed(value, 8U) & 0x00ff00ff); 2273 #else 2274 // 6 instructions with rotate instruction, 8 without 2275 value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); 2276 return rotlFixed(value, 16U); 2277 #endif 2278 } 2279 2280 /// \brief Reverses bytes in a 64-bit value 2281 /// \param value the 64-bit value to reverse 2282 /// \details ByteReverse calls bswap if available. Otherwise the function uses 2283 /// a combination of rotates on the word64. 2284 inline word64 ByteReverse(word64 value) 2285 { 2286 #if defined(CRYPTOPP_BYTESWAP_AVAILABLE) 2287 return bswap_64(value); 2288 #elif defined(__GNUC__) && defined(CRYPTOPP_X86_ASM_AVAILABLE) && defined(__x86_64__) 2289 __asm__ ("bswap %0" : "=r" (value) : "0" (value)); 2290 return value; 2291 #elif (CRYPTOPP_MSC_VERSION >= 1400) || (defined(CRYPTOPP_MSC_VERSION) && !defined(_DLL)) 2292 return _byteswap_uint64(value); 2293 #elif CRYPTOPP_BOOL_SLOW_WORD64 2294 return (word64(ByteReverse(word32(value))) << 32) | ByteReverse(word32(value>>32)); 2295 #else 2296 value = ((value & W64LIT(0xFF00FF00FF00FF00)) >> 8) | ((value & W64LIT(0x00FF00FF00FF00FF)) << 8); 2297 value = ((value & W64LIT(0xFFFF0000FFFF0000)) >> 16) | ((value & W64LIT(0x0000FFFF0000FFFF)) << 16); 2298 return rotlFixed(value, 32U); 2299 #endif 2300 } 2301 2302 #if defined(CRYPTOPP_WORD128_AVAILABLE) 2303 /// \brief Reverses bytes in a 128-bit value 2304 /// \param value the 128-bit value to reverse 2305 /// \details ByteReverse calls bswap if available. Otherwise the function uses 2306 /// a combination of rotates on the word128. 2307 /// \note word128 is available on some 64-bit platforms when the compiler supports it. 2308 /// \since Crypto++ 8.7 2309 inline word128 ByteReverse(word128 value) 2310 { 2311 // TODO: speed this up 2312 return (word128(ByteReverse(word64(value))) << 64) | ByteReverse(word64(value>>64)); 2313 } 2314 #endif 2315 2316 /// \brief Reverses bits in a 8-bit value 2317 /// \param value the 8-bit value to reverse 2318 /// \details BitReverse performs a combination of shifts on the byte. 2319 inline byte BitReverse(byte value) 2320 { 2321 value = byte((value & 0xAA) >> 1) | byte((value & 0x55) << 1); 2322 value = byte((value & 0xCC) >> 2) | byte((value & 0x33) << 2); 2323 return rotlFixed(value, 4U); 2324 } 2325 2326 /// \brief Reverses bits in a 16-bit value 2327 /// \param value the 16-bit value to reverse 2328 /// \details BitReverse performs a combination of shifts on the word16. 2329 inline word16 BitReverse(word16 value) 2330 { 2331 #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE) 2332 // 4 instructions on ARM. 2333 word32 rvalue; 2334 __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value)); 2335 return word16(rvalue >> 16); 2336 #else 2337 // 15 instructions on ARM. 2338 value = word16((value & 0xAAAA) >> 1) | word16((value & 0x5555) << 1); 2339 value = word16((value & 0xCCCC) >> 2) | word16((value & 0x3333) << 2); 2340 value = word16((value & 0xF0F0) >> 4) | word16((value & 0x0F0F) << 4); 2341 return ByteReverse(value); 2342 #endif 2343 } 2344 2345 /// \brief Reverses bits in a 32-bit value 2346 /// \param value the 32-bit value to reverse 2347 /// \details BitReverse performs a combination of shifts on the word32. 2348 inline word32 BitReverse(word32 value) 2349 { 2350 #if defined(CRYPTOPP_ARM_BITREV_AVAILABLE) 2351 // 2 instructions on ARM. 2352 word32 rvalue; 2353 __asm__ ("rbit %0, %1" : "=r" (rvalue) : "r" (value)); 2354 return rvalue; 2355 #else 2356 // 19 instructions on ARM. 2357 value = word32((value & 0xAAAAAAAA) >> 1) | word32((value & 0x55555555) << 1); 2358 value = word32((value & 0xCCCCCCCC) >> 2) | word32((value & 0x33333333) << 2); 2359 value = word32((value & 0xF0F0F0F0) >> 4) | word32((value & 0x0F0F0F0F) << 4); 2360 return ByteReverse(value); 2361 #endif 2362 } 2363 2364 /// \brief Reverses bits in a 64-bit value 2365 /// \param value the 64-bit value to reverse 2366 /// \details BitReverse performs a combination of shifts on the word64. 2367 inline word64 BitReverse(word64 value) 2368 { 2369 #if CRYPTOPP_BOOL_SLOW_WORD64 2370 return (word64(BitReverse(word32(value))) << 32) | BitReverse(word32(value>>32)); 2371 #else 2372 value = word64((value & W64LIT(0xAAAAAAAAAAAAAAAA)) >> 1) | word64((value & W64LIT(0x5555555555555555)) << 1); 2373 value = word64((value & W64LIT(0xCCCCCCCCCCCCCCCC)) >> 2) | word64((value & W64LIT(0x3333333333333333)) << 2); 2374 value = word64((value & W64LIT(0xF0F0F0F0F0F0F0F0)) >> 4) | word64((value & W64LIT(0x0F0F0F0F0F0F0F0F)) << 4); 2375 return ByteReverse(value); 2376 #endif 2377 } 2378 2379 /// \brief Reverses bits in a value 2380 /// \param value the value to reverse 2381 /// \details The template overload of BitReverse operates on signed and unsigned values. 2382 /// Internally the size of T is checked, and then value is cast to a byte, 2383 /// word16, word32 or word64. After the cast, the appropriate BitReverse 2384 /// overload is called. 2385 /// \note word128 is available on some 64-bit platforms when the compiler supports it. 2386 /// \since Crypto++ 1.0, word128 since Crypto++ 8.7 2387 template <class T> 2388 inline T BitReverse(T value) 2389 { 2390 if (sizeof(T) == 1) 2391 return (T)BitReverse((byte)value); 2392 else if (sizeof(T) == 2) 2393 return (T)BitReverse((word16)value); 2394 else if (sizeof(T) == 4) 2395 return (T)BitReverse((word32)value); 2396 else if (sizeof(T) == 8) 2397 return (T)BitReverse((word64)value); 2398 #if defined(CRYPTOPP_WORD128_AVAILABLE) 2399 else if (sizeof(T) == 16) 2400 return (T)BitReverse((word128)value); 2401 #endif 2402 else 2403 { 2404 CRYPTOPP_ASSERT(0); 2405 return (T)BitReverse((word64)value); 2406 } 2407 } 2408 2409 /// \brief Reverses bytes in a value depending upon endianness 2410 /// \tparam T the class or type 2411 /// \param order the ByteOrder of the data 2412 /// \param value the value to conditionally reverse 2413 /// \details Internally, the ConditionalByteReverse calls NativeByteOrderIs. 2414 /// If order matches native byte order, then the original value is returned. 2415 /// If not, then ByteReverse is called on the value before returning to the caller. 2416 template <class T> 2417 inline T ConditionalByteReverse(ByteOrder order, T value) 2418 { 2419 return NativeByteOrderIs(order) ? value : ByteReverse(value); 2420 } 2421 2422 /// \brief Reverses bytes in an element from an array of elements 2423 /// \tparam T the class or type 2424 /// \param out the output array of elements 2425 /// \param in the input array of elements 2426 /// \param byteCount the total number of bytes in the array 2427 /// \details Internally, ByteReverse visits each element in the in array 2428 /// calls ByteReverse on it, and writes the result to out. 2429 /// \details ByteReverse does not process tail byes, or bytes that are 2430 /// not part of a full element. If T is int (and int is 4 bytes), then 2431 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are 2432 /// reversed. 2433 /// \details The following program should help illustrate the behavior. 2434 /// <pre>vector<word32> v1, v2; 2435 /// 2436 /// v1.push_back(1); 2437 /// v1.push_back(2); 2438 /// v1.push_back(3); 2439 /// v1.push_back(4); 2440 /// 2441 /// v2.resize(v1.size()); 2442 /// ByteReverse<word32>(&v2[0], &v1[0], 16); 2443 /// 2444 /// cout << "V1: "; 2445 /// for(unsigned int i = 0; i < v1.size(); i++) 2446 /// cout << std::hex << v1[i] << " "; 2447 /// cout << endl; 2448 /// 2449 /// cout << "V2: "; 2450 /// for(unsigned int i = 0; i < v2.size(); i++) 2451 /// cout << std::hex << v2[i] << " "; 2452 /// cout << endl;</pre> 2453 /// The program above results in the following output. 2454 /// <pre>V1: 00000001 00000002 00000003 00000004 2455 /// V2: 01000000 02000000 03000000 04000000</pre> 2456 /// \sa ConditionalByteReverse 2457 template <class T> 2458 void ByteReverse(T *out, const T *in, size_t byteCount) 2459 { 2460 // Alignment check due to Issues 690 2461 CRYPTOPP_ASSERT(byteCount % sizeof(T) == 0); 2462 CRYPTOPP_ASSERT(IsAligned<T>(in)); 2463 CRYPTOPP_ASSERT(IsAligned<T>(out)); 2464 2465 size_t count = byteCount/sizeof(T); 2466 for (size_t i=0; i<count; i++) 2467 out[i] = ByteReverse(in[i]); 2468 } 2469 2470 /// \brief Conditionally reverses bytes in an element from an array of elements 2471 /// \tparam T the class or type 2472 /// \param order the ByteOrder of the data 2473 /// \param out the output array of elements 2474 /// \param in the input array of elements 2475 /// \param byteCount the byte count of the arrays 2476 /// \details ConditionalByteReverse visits each element in the in array 2477 /// calls ByteReverse on it depending on the desired endianness, and writes the result to out. 2478 /// \details ByteReverse does not process tail byes, or bytes that are 2479 /// not part of a full element. If T is int (and int is 4 bytes), then 2480 /// <tt>byteCount = 10</tt> means only the first 2 elements or 8 bytes are 2481 /// reversed. 2482 /// \sa ByteReverse 2483 template <class T> 2484 inline void ConditionalByteReverse(ByteOrder order, T *out, const T *in, size_t byteCount) 2485 { 2486 if (!NativeByteOrderIs(order)) 2487 ByteReverse(out, in, byteCount); 2488 else if (in != out) 2489 memcpy_s(out, byteCount, in, byteCount); 2490 } 2491 2492 /// \brief Copy bytes in a buffer to an array of elements in big-endian order 2493 /// \tparam T the class or type 2494 /// \param order the ByteOrder of the data 2495 /// \param out the output array of elements 2496 /// \param outlen the byte count of the array 2497 /// \param in the input array of elements 2498 /// \param inlen the byte count of the array 2499 template <class T> 2500 inline void GetUserKey(ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen) 2501 { 2502 const size_t U = sizeof(T); 2503 CRYPTOPP_ASSERT(inlen <= outlen*U); 2504 memcpy_s(out, outlen*U, in, inlen); 2505 memset_z((byte *)out+inlen, 0, outlen*U-inlen); 2506 ConditionalByteReverse(order, out, out, RoundUpToMultipleOf(inlen, U)); 2507 } 2508 2509 /// \brief Retrieve a byte from an unaligned buffer 2510 /// \param order the ByteOrder of the data 2511 /// \param block an unaligned buffer 2512 /// \param unused dummy parameter 2513 /// \return byte value 2514 /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a byte value. 2515 /// \since Crypto++ 1.0 2516 inline byte UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const byte *unused) 2517 { 2518 CRYPTOPP_UNUSED(order); CRYPTOPP_UNUSED(unused); 2519 return block[0]; 2520 } 2521 2522 /// \brief Retrieve a word16 from an unaligned buffer 2523 /// \param order the ByteOrder of the data 2524 /// \param block an unaligned buffer 2525 /// \param unused dummy parameter 2526 /// \return byte value 2527 /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word16 value. 2528 /// \since Crypto++ 1.0 2529 inline word16 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word16 *unused) 2530 { 2531 CRYPTOPP_UNUSED(unused); 2532 return (order == BIG_ENDIAN_ORDER) 2533 ? block[1] | (block[0] << 8) 2534 : block[0] | (block[1] << 8); 2535 } 2536 2537 /// \brief Retrieve a word32 from an unaligned buffer 2538 /// \param order the ByteOrder of the data 2539 /// \param block an unaligned buffer 2540 /// \param unused dummy parameter 2541 /// \return byte value 2542 /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word32 value. 2543 /// \since Crypto++ 1.0 2544 inline word32 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word32 *unused) 2545 { 2546 CRYPTOPP_UNUSED(unused); 2547 return (order == BIG_ENDIAN_ORDER) 2548 ? word32(block[3]) | (word32(block[2]) << 8) | (word32(block[1]) << 16) | (word32(block[0]) << 24) 2549 : word32(block[0]) | (word32(block[1]) << 8) | (word32(block[2]) << 16) | (word32(block[3]) << 24); 2550 } 2551 2552 /// \brief Retrieve a word64 from an unaligned buffer 2553 /// \param order the ByteOrder of the data 2554 /// \param block an unaligned buffer 2555 /// \param unused dummy parameter 2556 /// \return byte value 2557 /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word64 value. 2558 /// \since Crypto++ 1.0 2559 inline word64 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word64 *unused) 2560 { 2561 CRYPTOPP_UNUSED(unused); 2562 return (order == BIG_ENDIAN_ORDER) 2563 ? 2564 (word64(block[7]) | 2565 (word64(block[6]) << 8) | 2566 (word64(block[5]) << 16) | 2567 (word64(block[4]) << 24) | 2568 (word64(block[3]) << 32) | 2569 (word64(block[2]) << 40) | 2570 (word64(block[1]) << 48) | 2571 (word64(block[0]) << 56)) 2572 : 2573 (word64(block[0]) | 2574 (word64(block[1]) << 8) | 2575 (word64(block[2]) << 16) | 2576 (word64(block[3]) << 24) | 2577 (word64(block[4]) << 32) | 2578 (word64(block[5]) << 40) | 2579 (word64(block[6]) << 48) | 2580 (word64(block[7]) << 56)); 2581 } 2582 2583 #if defined(CRYPTOPP_WORD128_AVAILABLE) 2584 /// \brief Retrieve a word128 from an unaligned buffer 2585 /// \param order the ByteOrder of the data 2586 /// \param block an unaligned buffer 2587 /// \param unused dummy parameter 2588 /// \return byte value 2589 /// \details UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word128 value. 2590 /// \note word128 is available on some 64-bit platforms when the compiler supports it. 2591 /// \since Crypto++ 8.7 2592 inline word128 UnalignedGetWordNonTemplate(ByteOrder order, const byte *block, const word128 *unused) 2593 { 2594 CRYPTOPP_UNUSED(unused); 2595 return (order == BIG_ENDIAN_ORDER) 2596 ? 2597 (word128(block[15]) | 2598 (word128(block[14]) << 8) | 2599 (word128(block[13]) << 16) | 2600 (word128(block[12]) << 24) | 2601 (word128(block[11]) << 32) | 2602 (word128(block[10]) << 40) | 2603 (word128(block[ 9]) << 48) | 2604 (word128(block[ 8]) << 56) | 2605 (word128(block[ 7]) << 64) | 2606 (word128(block[ 6]) << 72) | 2607 (word128(block[ 5]) << 80) | 2608 (word128(block[ 4]) << 88) | 2609 (word128(block[ 3]) << 96) | 2610 (word128(block[ 2]) << 104) | 2611 (word128(block[ 1]) << 112) | 2612 (word128(block[ 0]) << 120)) 2613 : 2614 (word128(block[ 0]) | 2615 (word128(block[ 1]) << 8) | 2616 (word128(block[ 2]) << 16) | 2617 (word128(block[ 3]) << 24) | 2618 (word128(block[ 4]) << 32) | 2619 (word128(block[ 5]) << 40) | 2620 (word128(block[ 6]) << 48) | 2621 (word128(block[ 7]) << 56) | 2622 (word128(block[ 8]) << 64) | 2623 (word128(block[ 9]) << 72) | 2624 (word128(block[10]) << 80) | 2625 (word128(block[11]) << 88) | 2626 (word128(block[12]) << 96) | 2627 (word128(block[13]) << 104) | 2628 (word128(block[14]) << 112) | 2629 (word128(block[15]) << 120)); 2630 } 2631 #endif 2632 2633 /// \brief Write a byte to an unaligned buffer 2634 /// \param order the ByteOrder of the data 2635 /// \param block an unaligned output buffer 2636 /// \param value byte value 2637 /// \param xorBlock optional unaligned xor buffer 2638 /// \details UnalignedbyteNonTemplate writes a byte value to an unaligned buffer. 2639 /// \since Crypto++ 1.0 2640 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, byte value, const byte *xorBlock) 2641 { 2642 CRYPTOPP_UNUSED(order); 2643 block[0] = static_cast<byte>(xorBlock ? (value ^ xorBlock[0]) : value); 2644 } 2645 2646 /// \brief Write a word16 to an unaligned buffer 2647 /// \param order the ByteOrder of the data 2648 /// \param block an unaligned output buffer 2649 /// \param value word16 value 2650 /// \param xorBlock optional unaligned xor buffer 2651 /// \details UnalignedbyteNonTemplate writes a word16 value to an unaligned buffer. 2652 /// \since Crypto++ 1.0 2653 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word16 value, const byte *xorBlock) 2654 { 2655 if (order == BIG_ENDIAN_ORDER) 2656 { 2657 if (xorBlock) 2658 { 2659 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2660 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2661 } 2662 else 2663 { 2664 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2665 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2666 } 2667 } 2668 else 2669 { 2670 if (xorBlock) 2671 { 2672 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2673 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2674 } 2675 else 2676 { 2677 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2678 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2679 } 2680 } 2681 } 2682 2683 /// \brief Write a word32 to an unaligned buffer 2684 /// \param order the ByteOrder of the data 2685 /// \param block an unaligned output buffer 2686 /// \param value word32 value 2687 /// \param xorBlock optional unaligned xor buffer 2688 /// \details UnalignedbyteNonTemplate writes a word32 value to an unaligned buffer. 2689 /// \since Crypto++ 1.0 2690 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word32 value, const byte *xorBlock) 2691 { 2692 if (order == BIG_ENDIAN_ORDER) 2693 { 2694 if (xorBlock) 2695 { 2696 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2697 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2698 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2699 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2700 } 2701 else 2702 { 2703 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2704 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2705 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2706 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2707 } 2708 } 2709 else 2710 { 2711 if (xorBlock) 2712 { 2713 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2714 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2715 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2716 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2717 } 2718 else 2719 { 2720 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2721 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2722 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2723 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2724 } 2725 } 2726 } 2727 2728 /// \brief Write a word64 to an unaligned buffer 2729 /// \param order the ByteOrder of the data 2730 /// \param block an unaligned output buffer 2731 /// \param value word64 value 2732 /// \param xorBlock optional unaligned xor buffer 2733 /// \details UnalignedbyteNonTemplate writes a word64 value to an unaligned buffer. 2734 /// \since Crypto++ 1.0 2735 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word64 value, const byte *xorBlock) 2736 { 2737 if (order == BIG_ENDIAN_ORDER) 2738 { 2739 if (xorBlock) 2740 { 2741 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2742 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2743 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2744 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2745 block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2746 block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2747 block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2748 block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2749 } 2750 else 2751 { 2752 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2753 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2754 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2755 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2756 block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2757 block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2758 block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2759 block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2760 } 2761 } 2762 else 2763 { 2764 if (xorBlock) 2765 { 2766 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2767 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2768 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2769 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2770 block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2771 block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2772 block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2773 block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2774 } 2775 else 2776 { 2777 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2778 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2779 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2780 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2781 block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2782 block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2783 block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2784 block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2785 } 2786 } 2787 } 2788 2789 #if defined(CRYPTOPP_WORD128_AVAILABLE) 2790 /// \brief Write a word128 to an unaligned buffer 2791 /// \param order the ByteOrder of the data 2792 /// \param block an unaligned output buffer 2793 /// \param value word128 value 2794 /// \param xorBlock optional unaligned xor buffer 2795 /// \details UnalignedbyteNonTemplate writes a word128 value to an unaligned buffer. 2796 /// \note word128 is available on some 64-bit platforms when the compiler supports it. 2797 /// \since Crypto++ 8.7 2798 inline void UnalignedbyteNonTemplate(ByteOrder order, byte *block, word128 value, const byte *xorBlock) 2799 { 2800 if (order == BIG_ENDIAN_ORDER) 2801 { 2802 if (xorBlock) 2803 { 2804 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 15); 2805 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 14); 2806 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 13); 2807 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 12); 2808 block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 11); 2809 block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 10); 2810 block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 9); 2811 block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 8); 2812 2813 block[ 8] = xorBlock[ 8] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2814 block[ 9] = xorBlock[ 9] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2815 block[10] = xorBlock[10] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2816 block[11] = xorBlock[11] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2817 block[12] = xorBlock[12] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2818 block[13] = xorBlock[13] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2819 block[14] = xorBlock[14] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2820 block[15] = xorBlock[15] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2821 } 2822 else 2823 { 2824 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 15); 2825 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 14); 2826 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 13); 2827 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 12); 2828 block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 11); 2829 block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 10); 2830 block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 9); 2831 block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 8); 2832 2833 block[ 8] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2834 block[ 9] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2835 block[10] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2836 block[11] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2837 block[12] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2838 block[13] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2839 block[14] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2840 block[15] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2841 } 2842 } 2843 else 2844 { 2845 if (xorBlock) 2846 { 2847 block[0] = xorBlock[0] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2848 block[1] = xorBlock[1] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2849 block[2] = xorBlock[2] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2850 block[3] = xorBlock[3] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2851 block[4] = xorBlock[4] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2852 block[5] = xorBlock[5] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2853 block[6] = xorBlock[6] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2854 block[7] = xorBlock[7] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2855 2856 block[ 8] = xorBlock[ 8] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 8); 2857 block[ 9] = xorBlock[ 9] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 9); 2858 block[10] = xorBlock[10] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 10); 2859 block[11] = xorBlock[11] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 11); 2860 block[12] = xorBlock[12] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 12); 2861 block[13] = xorBlock[13] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 13); 2862 block[14] = xorBlock[14] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 14); 2863 block[15] = xorBlock[15] ^ CRYPTOPP_GET_BYTE_AS_BYTE(value, 15); 2864 } 2865 else 2866 { 2867 block[0] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 0); 2868 block[1] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 1); 2869 block[2] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 2); 2870 block[3] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 3); 2871 block[4] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 4); 2872 block[5] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 5); 2873 block[6] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 6); 2874 block[7] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 7); 2875 2876 block[ 8] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 8); 2877 block[ 9] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 9); 2878 block[10] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 10); 2879 block[11] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 11); 2880 block[12] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 12); 2881 block[13] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 13); 2882 block[14] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 14); 2883 block[15] = CRYPTOPP_GET_BYTE_AS_BYTE(value, 15); 2884 } 2885 } 2886 } 2887 #endif 2888 2889 /// \brief Access a block of memory 2890 /// \tparam T class or type 2891 /// \param assumeAligned flag indicating alignment 2892 /// \param order the ByteOrder of the data 2893 /// \param block the byte buffer to be processed 2894 /// \return the word in the specified byte order 2895 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates 2896 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or 2897 /// LITTLE_ENDIAN_ORDER. 2898 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt> 2899 /// will be <tt>0x03020100</tt>. 2900 /// <pre> 2901 /// word32 w; 2902 /// byte buffer[4] = {0,1,2,3}; 2903 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer); 2904 /// </pre> 2905 template <class T> 2906 inline T GetWord(bool assumeAligned, ByteOrder order, const byte *block) 2907 { 2908 CRYPTOPP_UNUSED(assumeAligned); 2909 2910 T temp = 0; 2911 if (block != NULLPTR) {std::memcpy(&temp, block, sizeof(T));} 2912 return ConditionalByteReverse(order, temp); 2913 } 2914 2915 /// \brief Access a block of memory 2916 /// \tparam T class or type 2917 /// \param assumeAligned flag indicating alignment 2918 /// \param order the ByteOrder of the data 2919 /// \param result the word in the specified byte order 2920 /// \param block the byte buffer to be processed 2921 /// \details GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates 2922 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or 2923 /// LITTLE_ENDIAN_ORDER. 2924 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w</tt> 2925 /// will be <tt>0x03020100</tt>. 2926 /// <pre> 2927 /// word32 w; 2928 /// byte buffer[4] = {0,1,2,3}; 2929 /// w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer); 2930 /// </pre> 2931 template <class T> 2932 inline void GetWord(bool assumeAligned, ByteOrder order, T &result, const byte *block) 2933 { 2934 result = GetWord<T>(assumeAligned, order, block); 2935 } 2936 2937 /// \brief Access a block of memory 2938 /// \tparam T class or type 2939 /// \param assumeAligned flag indicating alignment 2940 /// \param order the ByteOrder of the data 2941 /// \param block the destination byte buffer 2942 /// \param value the word in the specified byte order 2943 /// \param xorBlock an optional byte buffer to xor 2944 /// \details PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates 2945 /// if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or 2946 /// LITTLE_ENDIAN_ORDER. 2947 template <class T> 2948 inline void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock = NULLPTR) 2949 { 2950 CRYPTOPP_UNUSED(assumeAligned); 2951 2952 T t1, t2; 2953 t1 = ConditionalByteReverse(order, value); 2954 if (xorBlock != NULLPTR) {std::memcpy(&t2, xorBlock, sizeof(T)); t1 ^= t2;} 2955 if (block != NULLPTR) {std::memcpy(block, &t1, sizeof(T));} 2956 } 2957 2958 /// \brief Access a block of memory 2959 /// \tparam T class or type 2960 /// \tparam B enumeration indicating endianness 2961 /// \tparam A flag indicating alignment 2962 /// \details GetBlock() provides alternate read access to a block of memory. The enumeration B is 2963 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T. 2964 /// Repeatedly applying operator() results in advancing in the block of memory. 2965 /// \details An example of reading two word32 values from a block of memory is shown below. <tt>w1</tt> 2966 /// will be <tt>0x03020100</tt> and <tt>w1</tt> will be <tt>0x07060504</tt>. 2967 /// <pre> 2968 /// word32 w1, w2; 2969 /// byte buffer[8] = {0,1,2,3,4,5,6,7}; 2970 /// GetBlock<word32, LittleEndian> block(buffer); 2971 /// block(w1)(w2); 2972 /// </pre> 2973 template <class T, class B, bool A=false> 2974 class GetBlock 2975 { 2976 public: 2977 /// \brief Construct a GetBlock 2978 /// \param block the memory block 2979 GetBlock(const void *block) 2980 : m_block((const byte *)block) {} 2981 2982 /// \brief Access a block of memory 2983 /// \tparam U class or type 2984 /// \param x the value to read 2985 /// \return pointer to the remainder of the block after reading x 2986 template <class U> 2987 inline GetBlock<T, B, A> & operator()(U &x) 2988 { 2989 CRYPTOPP_COMPILE_ASSERT(sizeof(U) >= sizeof(T)); 2990 x = GetWord<T>(A, B::ToEnum(), m_block); 2991 m_block += sizeof(T); 2992 return *this; 2993 } 2994 2995 private: 2996 const byte *m_block; 2997 }; 2998 2999 /// \brief Access a block of memory 3000 /// \tparam T class or type 3001 /// \tparam B enumeration indicating endianness 3002 /// \tparam A flag indicating alignment 3003 /// \details PutBlock() provides alternate write access to a block of memory. The enumeration B is 3004 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T. 3005 /// Repeatedly applying operator() results in advancing in the block of memory. 3006 /// \details An example of writing two word32 values from a block of memory is shown below. After the code 3007 /// executes, the byte buffer will be <tt>{0,1,2,3,4,5,6,7}</tt>. 3008 /// <pre> 3009 /// word32 w1=0x03020100, w2=0x07060504; 3010 /// byte buffer[8]; 3011 /// PutBlock<word32, LittleEndian> block(NULLPTR, buffer); 3012 /// block(w1)(w2); 3013 /// </pre> 3014 template <class T, class B, bool A=false> 3015 class PutBlock 3016 { 3017 public: 3018 /// \brief Construct a PutBlock 3019 /// \param block the memory block 3020 /// \param xorBlock optional mask 3021 PutBlock(const void *xorBlock, void *block) 3022 : m_xorBlock((const byte *)xorBlock), m_block((byte *)block) {} 3023 3024 /// \brief Access a block of memory 3025 /// \tparam U class or type 3026 /// \param x the value to write 3027 /// \return pointer to the remainder of the block after writing x 3028 template <class U> 3029 inline PutBlock<T, B, A> & operator()(U x) 3030 { 3031 PutWord(A, B::ToEnum(), m_block, (T)x, m_xorBlock); 3032 m_block += sizeof(T); 3033 if (m_xorBlock) 3034 m_xorBlock += sizeof(T); 3035 return *this; 3036 } 3037 3038 private: 3039 const byte *m_xorBlock; 3040 byte *m_block; 3041 }; 3042 3043 /// \brief Access a block of memory 3044 /// \tparam T class or type 3045 /// \tparam B enumeration indicating endianness 3046 /// \tparam GA flag indicating alignment for the Get operation 3047 /// \tparam PA flag indicating alignment for the Put operation 3048 /// \details GetBlock() provides alternate write access to a block of memory. The enumeration B is 3049 /// BigEndian or LittleEndian. The flag A indicates if the memory block is aligned for class or type T. 3050 /// \sa GetBlock() and PutBlock(). 3051 template <class T, class B, bool GA=false, bool PA=false> 3052 struct BlockGetAndPut 3053 { 3054 // function needed because of C++ grammatical ambiguity between expression-statements and declarations 3055 static inline GetBlock<T, B, GA> Get(const void *block) {return GetBlock<T, B, GA>(block);} 3056 typedef PutBlock<T, B, PA> Put; 3057 }; 3058 3059 /// \brief Convert a word to a string 3060 /// \tparam T class or type 3061 /// \param value the word to convert 3062 /// \param order byte order 3063 /// \return a string representing the value of the word 3064 template <class T> 3065 std::string WordToString(T value, ByteOrder order = BIG_ENDIAN_ORDER) 3066 { 3067 if (!NativeByteOrderIs(order)) 3068 value = ByteReverse(value); 3069 3070 return std::string((char *)&value, sizeof(value)); 3071 } 3072 3073 /// \brief Convert a string to a word 3074 /// \tparam T class or type 3075 /// \param str the string to convert 3076 /// \param order byte order 3077 /// \return a word representing the value of the string 3078 template <class T> 3079 T StringToWord(const std::string &str, ByteOrder order = BIG_ENDIAN_ORDER) 3080 { 3081 T value = 0; 3082 memcpy_s(&value, sizeof(value), str.data(), UnsignedMin(str.size(), sizeof(value))); 3083 return NativeByteOrderIs(order) ? value : ByteReverse(value); 3084 } 3085 3086 // ************** help remove warning on g++ *************** 3087 3088 /// \brief Safely shift values when undefined behavior could occur 3089 /// \tparam overflow boolean flag indicating if overflow is present 3090 /// \details SafeShifter safely shifts values when undefined behavior could occur under C/C++ rules. 3091 /// The class behaves much like a saturating arithmetic class, clamping values rather than allowing 3092 /// the compiler to remove undefined behavior. 3093 /// \sa SafeShifter<true>, SafeShifter<false> 3094 template <bool overflow> struct SafeShifter; 3095 3096 /// \brief Shifts a value in the presence of overflow 3097 /// \details the true template parameter indicates overflow would occur. 3098 /// In this case, SafeShifter clamps the value and returns 0. 3099 template<> struct SafeShifter<true> 3100 { 3101 /// \brief Right shifts a value that overflows 3102 /// \tparam T class or type 3103 /// \return 0 3104 /// \details Since <tt>overflow == true</tt>, the value 0 is always returned. 3105 /// \sa SafeLeftShift 3106 template <class T> 3107 static inline T RightShift(T value, unsigned int bits) 3108 { 3109 CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits); 3110 return 0; 3111 } 3112 3113 /// \brief Left shifts a value that overflows 3114 /// \tparam T class or type 3115 /// \return 0 3116 /// \details Since <tt>overflow == true</tt>, the value 0 is always returned. 3117 /// \sa SafeRightShift 3118 template <class T> 3119 static inline T LeftShift(T value, unsigned int bits) 3120 { 3121 CRYPTOPP_UNUSED(value); CRYPTOPP_UNUSED(bits); 3122 return 0; 3123 } 3124 }; 3125 3126 /// \brief Shifts a value in the absence of overflow 3127 /// \details the false template parameter indicates overflow would not occur. 3128 /// In this case, SafeShifter returns the shfted value. 3129 template<> struct SafeShifter<false> 3130 { 3131 /// \brief Right shifts a value that does not overflow 3132 /// \tparam T class or type 3133 /// \return the shifted value 3134 /// \details Since <tt>overflow == false</tt>, the shifted value is returned. 3135 /// \sa SafeLeftShift 3136 template <class T> 3137 static inline T RightShift(T value, unsigned int bits) 3138 { 3139 return value >> bits; 3140 } 3141 3142 /// \brief Left shifts a value that does not overflow 3143 /// \tparam T class or type 3144 /// \return the shifted value 3145 /// \details Since <tt>overflow == false</tt>, the shifted value is returned. 3146 /// \sa SafeRightShift 3147 template <class T> 3148 static inline T LeftShift(T value, unsigned int bits) 3149 { 3150 return value << bits; 3151 } 3152 }; 3153 3154 /// \brief Safely right shift values when undefined behavior could occur 3155 /// \tparam bits the number of bit positions to shift the value 3156 /// \tparam T class or type 3157 /// \param value the value to right shift 3158 /// \result the shifted value or 0 3159 /// \details SafeRightShift safely shifts the value to the right when undefined behavior 3160 /// could occur under C/C++ rules. SafeRightShift will return the shifted value or 0 3161 /// if undefined behavior would occur. 3162 template <unsigned int bits, class T> 3163 inline T SafeRightShift(T value) 3164 { 3165 return SafeShifter<(bits>=(8*sizeof(T)))>::RightShift(value, bits); 3166 } 3167 3168 /// \brief Safely left shift values when undefined behavior could occur 3169 /// \tparam bits the number of bit positions to shift the value 3170 /// \tparam T class or type 3171 /// \param value the value to left shift 3172 /// \result the shifted value or 0 3173 /// \details SafeLeftShift safely shifts the value to the left when undefined behavior 3174 /// could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0 3175 /// if undefined behavior would occur. 3176 template <unsigned int bits, class T> 3177 inline T SafeLeftShift(T value) 3178 { 3179 return SafeShifter<(bits>=(8*sizeof(T)))>::LeftShift(value, bits); 3180 } 3181 3182 /// \brief Finds first element not in a range 3183 /// \tparam InputIt Input iterator type 3184 /// \tparam T class or type 3185 /// \param first iterator to first element 3186 /// \param last iterator to last element 3187 /// \param value the value used as a predicate 3188 /// \return iterator to the first element in the range that is not value 3189 template<typename InputIt, typename T> 3190 inline InputIt FindIfNot(InputIt first, InputIt last, const T &value) { 3191 #ifdef CRYPTOPP_CXX11_LAMBDA 3192 return std::find_if(first, last, [&value](const T &o) { 3193 return value!=o; 3194 }); 3195 #else 3196 return std::find_if(first, last, std::bind2nd(std::not_equal_to<T>(), value)); 3197 #endif 3198 } 3199 3200 // ************** use one buffer for multiple data members *************** 3201 3202 #define CRYPTOPP_BLOCK_1(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3203 #define CRYPTOPP_BLOCK_2(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3204 #define CRYPTOPP_BLOCK_3(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3205 #define CRYPTOPP_BLOCK_4(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3206 #define CRYPTOPP_BLOCK_5(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3207 #define CRYPTOPP_BLOCK_6(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3208 #define CRYPTOPP_BLOCK_7(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3209 #define CRYPTOPP_BLOCK_8(n, t, s) t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);} 3210 #define CRYPTOPP_BLOCKS_END(i) size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate; 3211 3212 NAMESPACE_END 3213 3214 #if (CRYPTOPP_MSC_VERSION) 3215 # pragma warning(pop) 3216 #endif 3217 3218 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 3219 # pragma GCC diagnostic pop 3220 #endif 3221 3222 #endif
[ Source navigation ] | [ Diff markup ] | [ Identifier search ] | [ general search ] |
This page was automatically generated by the 2.3.7 LXR engine. The LXR team |