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

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