Security Scol plugin
Classes | Macros | Typedefs | Functions
misc.h File Reference

Utility functions for the Crypto++ library. More...

#include "config.h"
#include "cryptlib.h"
#include "secblockfwd.h"
#include "smartptr.h"
#include "stdcpp.h"
#include "trap.h"

Go to the source code of this file.

Classes

struct  CompileAssert< b >
 
class  Empty
 An Empty class. More...
 
class  TwoBases< BASE1, BASE2 >
 
class  ThreeBases< BASE1, BASE2, BASE3 >
 
class  ObjectHolder< T >
 Uses encapsulation to hide an object in derived classes. More...
 
class  NotCopyable
 Ensures an object is not copyable. More...
 
struct  NewObject< T >
 An object factory function. More...
 
class  Singleton< T, F, instance >
 Restricts the instantiation of a class to one static object without locks. More...
 
class  GetBlock< T, B, A >
 Access a block of memory. More...
 
class  PutBlock< T, B, A >
 Access a block of memory. More...
 
struct  BlockGetAndPut< T, B, GA, PA >
 Access a block of memory. More...
 
struct  SafeShifter< true >
 Shifts a value in the presence of overflow. More...
 
struct  SafeShifter< false >
 Shifts a value in the absence of overflow. More...
 

Macros

#define CRYPTOPP_FAST_ROTATE(x)   0
 
#define SIZE_MAX   ((std::numeric_limits<size_t>::max)())
 
#define CRYPTOPP_COMPILE_ASSERT(assertion)   CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)
 
#define CRYPTOPP_ASSERT_JOIN(X, Y)   CRYPTOPP_DO_ASSERT_JOIN(X, Y)
 
#define CRYPTOPP_DO_ASSERT_JOIN(X, Y)   X##Y
 
#define CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, instance)
 
#define COUNTOF(x)   (sizeof(x)/sizeof(x[0]))
 
#define MEMORY_BARRIER()
 
#define EnumToInt(v)   static_cast<int>(v)
 Integer value.
 
#define RETURN_IF_NONZERO(x)   size_t returnedValue = x; if (returnedValue) return returnedValue
 
#define GETBYTE(x, y)   (unsigned int)byte((x)>>(8*(y)))
 
#define CRYPTOPP_GET_BYTE_AS_BYTE(x, y)   byte((x)>>(8*(y)))
 
#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);}
 
#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);}
 
#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);}
 
#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);}
 
#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);}
 
#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);}
 
#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);}
 
#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);}
 
#define CRYPTOPP_BLOCKS_END(i)   size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;
 

Typedefs

typedef LittleEndian NativeByteOrder
 

Functions

template<typename PTR , typename OFF >
PTR PtrAdd (PTR pointer, OFF offset)
 Create a pointer with an offset.
 
template<typename PTR , typename OFF >
PTR PtrSub (PTR pointer, OFF offset)
 Create a pointer with an offset.
 
template<typename PTR >
ptrdiff_t PtrDiff (const PTR pointer1, const PTR pointer2)
 Determine pointer difference.
 
template<typename PTR >
size_t PtrByteDiff (const PTR pointer1, const PTR pointer2)
 Determine pointer difference.
 
byteBytePtr (std::string &str)
 Pointer to the first element of a string.
 
byteBytePtr (SecByteBlock &str)
 Pointer to the first element of a string.
 
const byteConstBytePtr (const std::string &str)
 Const pointer to the first element of a string.
 
const byteConstBytePtr (const SecByteBlock &str)
 Const pointer to the first element of a string.
 
size_t BytePtrSize (const std::string &str)
 Size of a string.
 
size_t BytePtrSize (const SecByteBlock &str)
 Size of a string.
 
void memcpy_s (void *dest, size_t sizeInBytes, const void *src, size_t count)
 Bounds checking replacement for memcpy()
 
void memmove_s (void *dest, size_t sizeInBytes, const void *src, size_t count)
 Bounds checking replacement for memmove()
 
template<class T >
void vec_swap (T &a, T &b)
 Swaps two variables which are arrays.
 
void * memset_z (void *ptr, int val, size_t num)
 Memory block initializer.
 
template<class T >
const T & STDMIN (const T &a, const T &b)
 Replacement function for std::min.
 
template<class T >
const T & STDMAX (const T &a, const T &b)
 Replacement function for std::max.
 
template<class T1 , class T2 >
const T1 UnsignedMin (const T1 &a, const T2 &b)
 Safe comparison of values that could be negative and incorrectly promoted.
 
template<class T1 , class T2 >
bool SafeConvert (T1 from, T2 &to)
 Tests whether a conversion from -> to is safe to perform.
 
template<class T >
std::string IntToString (T value, unsigned int base=10)
 Converts a value to a string.
 
template<>
CRYPTOPP_DLL std::string IntToString< word64 > (word64 value, unsigned int base)
 Converts an unsigned value to a string.
 
template<>
CRYPTOPP_DLL std::string IntToString< Integer > (Integer value, unsigned int base)
 Converts an Integer to a string.
 
template<class T >
unsigned int Parity (T value)
 Returns the parity of a value.
 
template<class T >
unsigned int BytePrecision (const T &value)
 Returns the number of 8-bit bytes or octets required for a value.
 
template<class T >
unsigned int BitPrecision (const T &value)
 Returns the number of bits required for a value.
 
unsigned int TrailingZeros (word32 v)
 
unsigned int TrailingZeros (word64 v)
 
template<class T >
Crop (T value, size_t bits)
 Truncates the value to the specified number of bits.
 
size_t BitsToBytes (size_t bitCount)
 Returns the number of 8-bit bytes or octets required for the specified number of bits.
 
size_t BytesToWords (size_t byteCount)
 Returns the number of words required for the specified number of bytes.
 
size_t BitsToWords (size_t bitCount)
 Returns the number of words required for the specified number of bits.
 
size_t BitsToDwords (size_t bitCount)
 Returns the number of double words required for the specified number of bits.
 
CRYPTOPP_DLL void CRYPTOPP_API xorbuf (byte *buf, const byte *mask, size_t count)
 
CRYPTOPP_DLL void CRYPTOPP_API xorbuf (byte *output, const byte *input, const byte *mask, size_t count)
 
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual (const byte *buf1, const byte *buf2, size_t count)
 Performs a near constant-time comparison of two equally sized buffers.
 
template<class T >
bool IsPowerOf2 (const T &value)
 Tests whether a value is a power of 2.
 
template<class T >
NumericLimitsMin ()
 Provide the minimum value for a type.
 
template<class T >
NumericLimitsMax ()
 Provide the maximum value for a type.
 
template<class T1 , class T2 >
T1 SaturatingSubtract (const T1 &a, const T2 &b)
 Performs a saturating subtract clamped at 0.
 
template<class T1 , class T2 >
T1 SaturatingSubtract1 (const T1 &a, const T2 &b)
 Performs a saturating subtract clamped at 1.
 
template<class T1 , class T2 >
T2 ModPowerOf2 (const T1 &a, const T2 &b)
 Reduces a value to a power of 2.
 
template<class T1 , class T2 >
T1 RoundDownToMultipleOf (const T1 &n, const T2 &m)
 Rounds a value down to a multiple of a second value.
 
template<class T1 , class T2 >
T1 RoundUpToMultipleOf (const T1 &n, const T2 &m)
 Rounds a value up to a multiple of a second value.
 
template<class T >
unsigned int GetAlignmentOf ()
 Returns the minimum alignment requirements of a type.
 
bool IsAlignedOn (const void *ptr, unsigned int alignment)
 Determines whether ptr is aligned to a minimum value.
 
template<class T >
bool IsAligned (const void *ptr)
 Determines whether ptr is minimally aligned.
 
ByteOrder GetNativeByteOrder ()
 Returns NativeByteOrder as an enumerated ByteOrder value.
 
bool NativeByteOrderIs (ByteOrder order)
 Determines whether order follows native byte ordering.
 
template<class T >
CipherDir GetCipherDir (const T &obj)
 Returns the direction the cipher is being operated.
 
void IncrementCounterByOne (byte *inout, unsigned int size)
 Performs an addition with carry on a block of bytes.
 
void IncrementCounterByOne (byte *output, const byte *input, unsigned int size)
 Performs an addition with carry on a block of bytes.
 
template<class T >
void ConditionalSwap (bool c, T &a, T &b)
 Performs a branch-less swap of values a and b if condition c is true.
 
template<class T >
void ConditionalSwapPointers (bool c, T &a, T &b)
 Performs a branch-less swap of pointers a and b if condition c is true.
 
template<class T >
void SecureWipeBuffer (T *buf, size_t n)
 Sets each element of an array to 0.
 
template<class T >
void SecureWipeArray (T *buf, size_t n)
 Sets each element of an array to 0.
 
std::string StringNarrow (const wchar_t *str, bool throwOnError=true)
 Converts a wide character C-string to a multibyte string.
 
std::wstring StringWiden (const char *str, bool throwOnError=true)
 Converts a multibyte C-string to a wide character string.
 
template<unsigned int R, class T >
rotlConstant (T x)
 Performs a left rotate.
 
template<unsigned int R, class T >
rotrConstant (T x)
 Performs a right rotate.
 
template<class T >
rotlFixed (T x, unsigned int y)
 Performs a left rotate.
 
template<class T >
rotrFixed (T x, unsigned int y)
 Performs a right rotate.
 
template<class T >
rotlVariable (T x, unsigned int y)
 Performs a left rotate.
 
template<class T >
rotrVariable (T x, unsigned int y)
 Performs a right rotate.
 
template<class T >
rotlMod (T x, unsigned int y)
 Performs a left rotate.
 
template<class T >
rotrMod (T x, unsigned int y)
 Performs a right rotate.
 
template<class T >
unsigned int GetByte (ByteOrder order, T value, unsigned int index)
 Gets a byte from a value.
 
byte ByteReverse (byte value)
 Reverses bytes in a 8-bit value.
 
word16 ByteReverse (word16 value)
 Reverses bytes in a 16-bit value.
 
word32 ByteReverse (word32 value)
 Reverses bytes in a 32-bit value.
 
word64 ByteReverse (word64 value)
 Reverses bytes in a 64-bit value.
 
byte BitReverse (byte value)
 Reverses bits in a 8-bit value.
 
word16 BitReverse (word16 value)
 Reverses bits in a 16-bit value.
 
word32 BitReverse (word32 value)
 Reverses bits in a 32-bit value.
 
word64 BitReverse (word64 value)
 Reverses bits in a 64-bit value.
 
template<class T >
BitReverse (T value)
 Reverses bits in a value.
 
template<class T >
ConditionalByteReverse (ByteOrder order, T value)
 Reverses bytes in a value depending upon endianness.
 
template<class T >
void ByteReverse (T *out, const T *in, size_t byteCount)
 Reverses bytes in an element from an array of elements.
 
template<class T >
void ConditionalByteReverse (ByteOrder order, T *out, const T *in, size_t byteCount)
 Conditionally reverses bytes in an element from an array of elements.
 
template<class T >
void GetUserKey (ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
 Copy bytes in a buffer to an array of elements in big-endian order.
 
byte UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const byte *unused)
 Retrieve a byte from an unaligned buffer.
 
word16 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word16 *unused)
 Retrieve a word16 from an unaligned buffer.
 
word32 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word32 *unused)
 Retrieve a word32 from an unaligned buffer.
 
word64 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word64 *unused)
 Retrieve a word64 from an unaligned buffer.
 
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, byte value, const byte *xorBlock)
 Write a byte to an unaligned buffer.
 
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word16 value, const byte *xorBlock)
 Write a word16 to an unaligned buffer.
 
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word32 value, const byte *xorBlock)
 Write a word32 to an unaligned buffer.
 
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word64 value, const byte *xorBlock)
 Write a word64 to an unaligned buffer.
 
template<class T >
GetWord (bool assumeAligned, ByteOrder order, const byte *block)
 Access a block of memory.
 
template<class T >
void GetWord (bool assumeAligned, ByteOrder order, T &result, const byte *block)
 Access a block of memory.
 
template<class T >
void PutWord (bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULLPTR)
 Access a block of memory.
 
template<class T >
std::string WordToString (T value, ByteOrder order=BIG_ENDIAN_ORDER)
 Convert a word to a string.
 
template<class T >
StringToWord (const std::string &str, ByteOrder order=BIG_ENDIAN_ORDER)
 Convert a string to a word.
 
template<unsigned int bits, class T >
SafeRightShift (T value)
 Safely right shift values when undefined behavior could occur.
 
template<unsigned int bits, class T >
SafeLeftShift (T value)
 Safely left shift values when undefined behavior could occur.
 
template<typename InputIt , typename T >
InputIt FindIfNot (InputIt first, InputIt last, const T &value)
 Finds first element not in a range.
 

Detailed Description

Utility functions for the Crypto++ library.

Definition in file misc.h.

Macro Definition Documentation

◆ COUNTOF

#define COUNTOF (   x)    (sizeof(x)/sizeof(x[0]))

Definition at line 198 of file misc.h.

◆ CRYPTOPP_ASSERT_JOIN

#define CRYPTOPP_ASSERT_JOIN (   X,
 
)    CRYPTOPP_DO_ASSERT_JOIN(X, Y)

Definition at line 162 of file misc.h.

◆ CRYPTOPP_BLOCK_1

#define CRYPTOPP_BLOCK_1 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+0);} size_t SS1() {return sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2993 of file misc.h.

◆ CRYPTOPP_BLOCK_2

#define CRYPTOPP_BLOCK_2 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS1());} size_t SS2() {return SS1()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2994 of file misc.h.

◆ CRYPTOPP_BLOCK_3

#define CRYPTOPP_BLOCK_3 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS2());} size_t SS3() {return SS2()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2995 of file misc.h.

◆ CRYPTOPP_BLOCK_4

#define CRYPTOPP_BLOCK_4 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS3());} size_t SS4() {return SS3()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2996 of file misc.h.

◆ CRYPTOPP_BLOCK_5

#define CRYPTOPP_BLOCK_5 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS4());} size_t SS5() {return SS4()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2997 of file misc.h.

◆ CRYPTOPP_BLOCK_6

#define CRYPTOPP_BLOCK_6 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS5());} size_t SS6() {return SS5()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2998 of file misc.h.

◆ CRYPTOPP_BLOCK_7

#define CRYPTOPP_BLOCK_7 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS6());} size_t SS7() {return SS6()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 2999 of file misc.h.

◆ CRYPTOPP_BLOCK_8

#define CRYPTOPP_BLOCK_8 (   n,
  t,
 
)    t* m_##n() {return (t *)(void *)(m_aggregate+SS7());} size_t SS8() {return SS7()+sizeof(t)*(s);} size_t m_##n##Size() {return (s);}

Definition at line 3000 of file misc.h.

◆ CRYPTOPP_BLOCKS_END

#define CRYPTOPP_BLOCKS_END (   i)    size_t SST() {return SS##i();} void AllocateBlocks() {m_aggregate.New(SST());} AlignedSecByteBlock m_aggregate;

Definition at line 3001 of file misc.h.

◆ CRYPTOPP_COMPILE_ASSERT

#define CRYPTOPP_COMPILE_ASSERT (   assertion)    CRYPTOPP_COMPILE_ASSERT_INSTANCE(assertion, __LINE__)

Definition at line 161 of file misc.h.

◆ CRYPTOPP_COMPILE_ASSERT_INSTANCE

#define CRYPTOPP_COMPILE_ASSERT_INSTANCE (   assertion,
  instance 
)
Value:
static CompileAssert<(assertion)> \
CRYPTOPP_ASSERT_JOIN(cryptopp_CRYPTOPP_ASSERT_, instance)

Definition at line 173 of file misc.h.

◆ CRYPTOPP_DO_ASSERT_JOIN

#define CRYPTOPP_DO_ASSERT_JOIN (   X,
 
)    X##Y

Definition at line 163 of file misc.h.

◆ CRYPTOPP_FAST_ROTATE

#define CRYPTOPP_FAST_ROTATE (   x)    0

Definition at line 59 of file misc.h.

◆ CRYPTOPP_GET_BYTE_AS_BYTE

#define CRYPTOPP_GET_BYTE_AS_BYTE (   x,
 
)    byte((x)>>(8*(y)))

Definition at line 800 of file misc.h.

◆ EnumToInt

#define EnumToInt (   v)    static_cast<int>(v)

Integer value.

EnumToInt avoids C++20 enum-enum conversion warnings under GCC and Clang. C++11 and above use a constexpr function. C++03 and below use a macro due to [lack of] constexpr-ness in early versions of C++.

Since
Crypto++ 8.6

Definition at line 502 of file misc.h.

◆ GETBYTE

#define GETBYTE (   x,
 
)    (unsigned int)byte((x)>>(8*(y)))

Definition at line 795 of file misc.h.

◆ MEMORY_BARRIER

#define MEMORY_BARRIER ( )

Definition at line 282 of file misc.h.

◆ RETURN_IF_NONZERO

#define RETURN_IF_NONZERO (   x)    size_t returnedValue = x; if (returnedValue) return returnedValue

Definition at line 792 of file misc.h.

◆ SIZE_MAX

#define SIZE_MAX   ((std::numeric_limits<size_t>::max)())

Definition at line 131 of file misc.h.

Typedef Documentation

◆ NativeByteOrder

Definition at line 1247 of file misc.h.

Function Documentation

◆ BitPrecision()

template<class T >
unsigned int BitPrecision ( const T &  value)

Returns the number of bits required for a value.

Template Parameters
Tclass or type
Parameters
valuethe value to test
Returns
the maximum number of bits required to represent a value.

Definition at line 842 of file misc.h.

◆ BitReverse() [1/5]

byte BitReverse ( byte  value)
inline

Reverses bits in a 8-bit value.

Parameters
valuethe 8-bit value to reverse

BitReverse performs a combination of shifts on the byte.

Definition at line 2110 of file misc.h.

◆ BitReverse() [2/5]

template<class T >
T BitReverse ( value)
inline

Reverses bits in a value.

Parameters
valuethe value to reverse

The template overload of BitReverse operates on signed and unsigned values. Internally the size of T is checked, and then value is cast to a byte, word16, word32 or word64. After the cast, the appropriate BitReverse overload is called.

Note
word128 is available on some 64-bit platforms when the compiler supports it.
Since
Crypto++ 1.0, word128 since Crypto++ 8.7

Definition at line 2179 of file misc.h.

◆ BitReverse() [3/5]

word16 BitReverse ( word16  value)
inline

Reverses bits in a 16-bit value.

Parameters
valuethe 16-bit value to reverse

BitReverse performs a combination of shifts on the word16.

Definition at line 2120 of file misc.h.

◆ BitReverse() [4/5]

word32 BitReverse ( word32  value)
inline

Reverses bits in a 32-bit value.

Parameters
valuethe 32-bit value to reverse

BitReverse performs a combination of shifts on the word32.

Definition at line 2139 of file misc.h.

◆ BitReverse() [5/5]

word64 BitReverse ( word64  value)
inline

Reverses bits in a 64-bit value.

Parameters
valuethe 64-bit value to reverse

BitReverse performs a combination of shifts on the word64.

Definition at line 2158 of file misc.h.

◆ BitsToBytes()

size_t BitsToBytes ( size_t  bitCount)
inline

Returns the number of 8-bit bytes or octets required for the specified number of bits.

Parameters
bitCountthe number of bits
Returns
the minimum number of 8-bit bytes or octets required by bitCount

BitsToBytes is effectively a ceiling function based on 8-bit bytes.

Definition at line 938 of file misc.h.

◆ BitsToDwords()

size_t BitsToDwords ( size_t  bitCount)
inline

Returns the number of double words required for the specified number of bits.

Parameters
bitCountthe number of bits
Returns
the minimum number of double words required by bitCount

BitsToDwords is effectively a ceiling function based on 2*WORD_BITS. WORD_BITS is defined in config.h

Definition at line 968 of file misc.h.

◆ BitsToWords()

size_t BitsToWords ( size_t  bitCount)
inline

Returns the number of words required for the specified number of bits.

Parameters
bitCountthe number of bits
Returns
the minimum number of words required by bitCount

BitsToWords is effectively a ceiling function based on WORD_BITS. WORD_BITS is defined in config.h

Definition at line 958 of file misc.h.

◆ BytePrecision()

template<class T >
unsigned int BytePrecision ( const T &  value)

Returns the number of 8-bit bytes or octets required for a value.

Template Parameters
Tclass or type
Parameters
valuethe value to test
Returns
the minimum number of 8-bit bytes or octets required to represent a value

Definition at line 819 of file misc.h.

◆ BytePtr() [1/2]

byte * BytePtr ( SecByteBlock str)

Pointer to the first element of a string.

Parameters
strSecByteBlock

BytePtr returns NULL pointer for an empty string.

Returns
Pointer to the first element of a string
Since
Crypto++ 8.3

Definition at line 47 of file misc.cpp.

◆ BytePtr() [2/2]

byte * BytePtr ( std::string &  str)
inline

Pointer to the first element of a string.

Parameters
strstd::string

BytePtr returns NULL pointer for an empty string.

Returns
Pointer to the first element of a string
Since
Crypto++ 8.0

Definition at line 439 of file misc.h.

◆ BytePtrSize() [1/2]

size_t BytePtrSize ( const SecByteBlock str)

Size of a string.

Parameters
strSecByteBlock
Returns
size of a string
Since
Crypto++ 8.3

Definition at line 64 of file misc.cpp.

◆ BytePtrSize() [2/2]

size_t BytePtrSize ( const std::string &  str)
inline

Size of a string.

Parameters
strstd::string
Returns
size of a string
Since
Crypto++ 8.3

Definition at line 479 of file misc.h.

◆ ByteReverse() [1/5]

byte ByteReverse ( byte  value)
inline

Reverses bytes in a 8-bit value.

Parameters
valuethe 8-bit value to reverse
Note
ByteReverse returns the value passed to it since there is nothing to reverse.

Definition at line 2022 of file misc.h.

◆ ByteReverse() [2/5]

template<class T >
void ByteReverse ( T *  out,
const T *  in,
size_t  byteCount 
)

Reverses bytes in an element from an array of elements.

Template Parameters
Tthe class or type
Parameters
outthe output array of elements
inthe input array of elements
byteCountthe total number of bytes in the array

Internally, ByteReverse visits each element in the in array calls ByteReverse on it, and writes the result to out.

ByteReverse does not process tail byes, or bytes that are not part of a full element. If T is int (and int is 4 bytes), then byteCount = 10 means only the first 2 elements or 8 bytes are reversed.

The following program should help illustrate the behavior.

vector<word32> v1, v2;

v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v1.push_back(4);

v2.resize(v1.size());
ByteReverse<word32>(&v2[0], &v1[0], 16);

cout << "V1: ";
for(unsigned int i = 0; i < v1.size(); i++)
  cout << std::hex << v1[i] << " ";
cout << endl;

cout << "V2: ";
for(unsigned int i = 0; i < v2.size(); i++)
  cout << std::hex << v2[i] << " ";
cout << endl;

The program above results in the following output.

V1: 00000001 00000002 00000003 00000004
V2: 01000000 02000000 03000000 04000000
See also
ConditionalByteReverse

Definition at line 2249 of file misc.h.

◆ ByteReverse() [3/5]

word16 ByteReverse ( word16  value)
inline

Reverses bytes in a 16-bit value.

Parameters
valuethe 16-bit value to reverse

ByteReverse calls bswap if available. Otherwise the function performs a 8-bit rotate on the word16.

Definition at line 2031 of file misc.h.

◆ ByteReverse() [4/5]

word32 ByteReverse ( word32  value)
inline

Reverses bytes in a 32-bit value.

Parameters
valuethe 32-bit value to reverse

ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word32.

Definition at line 2046 of file misc.h.

◆ ByteReverse() [5/5]

word64 ByteReverse ( word64  value)
inline

Reverses bytes in a 64-bit value.

Parameters
valuethe 64-bit value to reverse

ByteReverse calls bswap if available. Otherwise the function uses a combination of rotates on the word64.

Definition at line 2075 of file misc.h.

◆ BytesToWords()

size_t BytesToWords ( size_t  byteCount)
inline

Returns the number of words required for the specified number of bytes.

Parameters
byteCountthe number of bytes
Returns
the minimum number of words required by byteCount

BytesToWords is effectively a ceiling function based on WORD_SIZE. WORD_SIZE is defined in config.h

Definition at line 948 of file misc.h.

◆ ConditionalByteReverse() [1/2]

template<class T >
void ConditionalByteReverse ( ByteOrder  order,
T *  out,
const T *  in,
size_t  byteCount 
)
inline

Conditionally reverses bytes in an element from an array of elements.

Template Parameters
Tthe class or type
Parameters
orderthe ByteOrder of the data
outthe output array of elements
inthe input array of elements
byteCountthe byte count of the arrays

ConditionalByteReverse visits each element in the in array calls ByteReverse on it depending on the desired endianness, and writes the result to out.

ByteReverse does not process tail byes, or bytes that are not part of a full element. If T is int (and int is 4 bytes), then byteCount = 10 means only the first 2 elements or 8 bytes are reversed.

See also
ByteReverse

Definition at line 2275 of file misc.h.

◆ ConditionalByteReverse() [2/2]

template<class T >
T ConditionalByteReverse ( ByteOrder  order,
value 
)
inline

Reverses bytes in a value depending upon endianness.

Template Parameters
Tthe class or type
Parameters
orderthe ByteOrder of the data
valuethe value to conditionally reverse

Internally, the ConditionalByteReverse calls NativeByteOrderIs. If order matches native byte order, then the original value is returned. If not, then ByteReverse is called on the value before returning to the caller.

Definition at line 2208 of file misc.h.

◆ ConditionalSwap()

template<class T >
void ConditionalSwap ( bool  c,
T &  a,
T &  b 
)
inline

Performs a branch-less swap of values a and b if condition c is true.

Template Parameters
Tclass or type
Parameters
cthe condition to perform the swap
athe first value
bthe second value

Definition at line 1345 of file misc.h.

◆ ConditionalSwapPointers()

template<class T >
void ConditionalSwapPointers ( bool  c,
T &  a,
T &  b 
)
inline

Performs a branch-less swap of pointers a and b if condition c is true.

Template Parameters
Tclass or type
Parameters
cthe condition to perform the swap
athe first pointer
bthe second pointer

Definition at line 1358 of file misc.h.

◆ ConstBytePtr() [1/2]

const byte * ConstBytePtr ( const SecByteBlock str)

Const pointer to the first element of a string.

Parameters
strSecByteBlock

ConstBytePtr returns non-NULL pointer for an empty string.

Returns
Pointer to the first element of a string
Since
Crypto++ 8.3

Definition at line 57 of file misc.cpp.

◆ ConstBytePtr() [2/2]

const byte * ConstBytePtr ( const std::string &  str)
inline

Const pointer to the first element of a string.

Parameters
strstd::string

ConstBytePtr returns non-NULL pointer for an empty string.

Returns
Pointer to the first element of a string
Since
Crypto++ 8.0

Definition at line 461 of file misc.h.

◆ Crop()

template<class T >
T Crop ( value,
size_t  bits 
)
inline

Truncates the value to the specified number of bits.

Template Parameters
Tclass or type
Parameters
valuethe value to truncate or mask
bitsthe number of bits to truncate or mask
Returns
the value truncated to the specified number of bits, starting at the least significant bit position

This function masks the low-order bits of value and returns the result. The mask is created with (1 << bits) - 1.

Definition at line 926 of file misc.h.

◆ FindIfNot()

template<typename InputIt , typename T >
InputIt FindIfNot ( InputIt  first,
InputIt  last,
const T &  value 
)
inline

Finds first element not in a range.

Template Parameters
InputItInput iterator type
Tclass or type
Parameters
firstiterator to first element
lastiterator to last element
valuethe value used as a predicate
Returns
iterator to the first element in the range that is not value

Definition at line 2981 of file misc.h.

◆ GetAlignmentOf()

template<class T >
unsigned int GetAlignmentOf ( )
inline

Returns the minimum alignment requirements of a type.

Template Parameters
Tclass or type
Returns
the minimum alignment requirements of T, in bytes

Internally the function calls C++11's alignof if available. If not available, then the function uses compiler specific extensions such as __alignof and alignof. If an extension is not available, then the function uses sizeof(T).

Definition at line 1200 of file misc.h.

◆ GetByte()

template<class T >
unsigned int GetByte ( ByteOrder  order,
value,
unsigned int  index 
)
inline

Gets a byte from a value.

Parameters
orderthe ByteOrder of the value
valuethe value to retrieve the byte
indexthe location of the byte to retrieve

Definition at line 2010 of file misc.h.

◆ GetCipherDir()

template<class T >
CipherDir GetCipherDir ( const T &  obj)
inline

Returns the direction the cipher is being operated.

Template Parameters
Tclass or type
Parameters
objthe cipher object being queried
Returns
ENCRYPTION if the cipher obj is being operated in its forward direction, DECRYPTION otherwise

A cipher can be operated in a "forward" direction (encryption) or a "reverse" direction (decryption). The operations do not have to be symmetric, meaning a second application of the transformation does not necessarily return the original message. That is, E(D(m)) may not equal E(E(m)); and D(E(m)) may not equal D(D(m)).

Definition at line 1288 of file misc.h.

◆ GetNativeByteOrder()

ByteOrder GetNativeByteOrder ( )
inline

Returns NativeByteOrder as an enumerated ByteOrder value.

Returns
LittleEndian if the native byte order is little-endian, and BigEndian if the native byte order is big-endian

NativeByteOrder is a typedef depending on the platform. If CRYPTOPP_LITTLE_ENDIAN is set in config.h, then GetNativeByteOrder returns LittleEndian. If CRYPTOPP_BIG_ENDIAN is set, then GetNativeByteOrder returns BigEndian.

Note
There are other byte orders besides little- and big-endian, and they include bi-endian and PDP-endian. If a system is neither little-endian nor big-endian, then a compile time error occurs.

Definition at line 1264 of file misc.h.

◆ GetUserKey()

template<class T >
void GetUserKey ( ByteOrder  order,
T *  out,
size_t  outlen,
const byte in,
size_t  inlen 
)
inline

Copy bytes in a buffer to an array of elements in big-endian order.

Template Parameters
Tthe class or type
Parameters
orderthe ByteOrder of the data
outthe output array of elements
outlenthe byte count of the array
inthe input array of elements
inlenthe byte count of the array

Definition at line 2291 of file misc.h.

◆ GetWord() [1/2]

template<class T >
T GetWord ( bool  assumeAligned,
ByteOrder  order,
const byte block 
)
inline

Access a block of memory.

Template Parameters
Tclass or type
Parameters
assumeAlignedflag indicating alignment
orderthe ByteOrder of the data
blockthe byte buffer to be processed
Returns
the word in the specified byte order

GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or LITTLE_ENDIAN_ORDER.

An example of reading two word32 values from a block of memory is shown below. w will be 0x03020100.

  word32 w;
  byte buffer[4] = {0,1,2,3};
  w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);

Definition at line 2697 of file misc.h.

◆ GetWord() [2/2]

template<class T >
void GetWord ( bool  assumeAligned,
ByteOrder  order,
T &  result,
const byte block 
)
inline

Access a block of memory.

Template Parameters
Tclass or type
Parameters
assumeAlignedflag indicating alignment
orderthe ByteOrder of the data
resultthe word in the specified byte order
blockthe byte buffer to be processed

GetWord() provides alternate read access to a block of memory. The flag assumeAligned indicates if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or LITTLE_ENDIAN_ORDER.

An example of reading two word32 values from a block of memory is shown below. w will be 0x03020100.

  word32 w;
  byte buffer[4] = {0,1,2,3};
  w = GetWord<word32>(false, LITTLE_ENDIAN_ORDER, buffer);

Definition at line 2723 of file misc.h.

◆ IncrementCounterByOne() [1/2]

void IncrementCounterByOne ( byte inout,
unsigned int  size 
)
inline

Performs an addition with carry on a block of bytes.

Parameters
inoutthe byte block
sizethe size of the block, in bytes

Performs an addition with carry by adding 1 on a block of bytes starting at the least significant byte. Once carry is 0, the function terminates and returns to the caller.

Note
The function is not constant time because it stops processing when the carry is 0.

Definition at line 1299 of file misc.h.

◆ IncrementCounterByOne() [2/2]

void IncrementCounterByOne ( byte output,
const byte input,
unsigned int  size 
)
inline

Performs an addition with carry on a block of bytes.

Parameters
outputthe destination block of bytes
inputthe source block of bytes
sizethe size of the block

Performs an addition with carry on a block of bytes starting at the least significant byte. Once carry is 0, the remaining bytes from input are copied to output using memcpy.

The function is close to near-constant time because it operates on all the bytes in the blocks.

Definition at line 1319 of file misc.h.

◆ IntToString()

template<class T >
std::string IntToString ( value,
unsigned int  base = 10 
)

Converts a value to a string.

Template Parameters
Tclass or type
Parameters
valuethe value to convert
basethe base to use during the conversion
Returns
the string representation of value in base.

Definition at line 724 of file misc.h.

◆ IntToString< Integer >()

template<>
CRYPTOPP_DLL std::string IntToString< Integer > ( Integer  value,
unsigned int  base 
)

Converts an Integer to a string.

Parameters
valuethe Integer to convert
basethe base to use during the conversion
Returns
the string representation of value in base.

This is a template specialization of IntToString(). Use it like IntToString():

 // Print integer in base 10
 Integer n...
 std::string s = IntToString(n, 10);

The string is presented with lowercase letters by default. A hack is available to switch to uppercase letters without modifying the function signature.

 // Print integer in base 16, uppercase letters
 Integer n...
 const unsigned int UPPER = (1 << 31);
 std::string s = IntToString(n, (UPPER | 16));

Definition at line 4767 of file integer.cpp.

◆ IntToString< word64 >()

template<>
CRYPTOPP_DLL std::string IntToString< word64 > ( word64  value,
unsigned int  base 
)

Converts an unsigned value to a string.

Parameters
valuethe value to convert
basethe base to use during the conversion
Returns
the string representation of value in base.

this template function specialization was added to suppress Coverity findings on IntToString() with unsigned types.

Definition at line 4833 of file integer.cpp.

◆ IsAligned()

template<class T >
bool IsAligned ( const void *  ptr)
inline

Determines whether ptr is minimally aligned.

Template Parameters
Tclass or type
Parameters
ptrthe pointer to check for alignment
Returns
true if ptr is aligned to at least T boundary, false otherwise

Internally the function calls IsAlignedOn with a second parameter of GetAlignmentOf<T>.

Definition at line 1241 of file misc.h.

◆ IsAlignedOn()

bool IsAlignedOn ( const void *  ptr,
unsigned int  alignment 
)
inline

Determines whether ptr is aligned to a minimum value.

Parameters
ptrthe pointer being checked for alignment
alignmentthe alignment value to test the pointer against
Returns
true if ptr is aligned on at least alignment boundary, false otherwise

Internally the function tests whether alignment is 1. If so, the function returns true. If not, then the function effectively performs a modular reduction and returns true if the residue is 0.

Definition at line 1227 of file misc.h.

◆ IsPowerOf2()

template<class T >
bool IsPowerOf2 ( const T &  value)
inline

Tests whether a value is a power of 2.

Parameters
valuethe value to test
Returns
true if value is a power of 2, false otherwise

The function creates a mask of value - 1 and returns the result of an AND operation compared to 0. If value is 0 or less than 0, then the function returns false.

Definition at line 1010 of file misc.h.

◆ memcpy_s()

void memcpy_s ( void *  dest,
size_t  sizeInBytes,
const void *  src,
size_t  count 
)
inline

Bounds checking replacement for memcpy()

Parameters
destpointer to the destination memory block
sizeInBytessize of the destination memory block, in bytes
srcpointer to the source memory block
countthe number of bytes to copy
Exceptions
InvalidArgument

ISO/IEC TR-24772 provides bounds checking interfaces for potentially unsafe functions like memcpy(), strcpy() and memmove(). However, not all standard libraries provides them, like Glibc. The library's memcpy_s() is a near-drop in replacement. Its only a near-replacement because the library's version throws an InvalidArgument on a bounds violation.

memcpy_s() and memmove_s() are guarded by STDC_WANT_SECURE_LIB. If STDC_WANT_SECURE_LIB is not defined or defined to 0, then the library makes memcpy_s() and memmove_s() available. The library will also optionally make the symbols available if CRYPTOPP_WANT_SECURE_LIB is defined. CRYPTOPP_WANT_SECURE_LIB is in config.h, but it is disabled by default.

memcpy_s() will assert the pointers src and dest are not NULL in debug builds. Passing NULL for either pointer is undefined behavior.

Definition at line 525 of file misc.h.

◆ memmove_s()

void memmove_s ( void *  dest,
size_t  sizeInBytes,
const void *  src,
size_t  count 
)
inline

Bounds checking replacement for memmove()

Parameters
destpointer to the destination memory block
sizeInBytessize of the destination memory block, in bytes
srcpointer to the source memory block
countthe number of bytes to copy
Exceptions
InvalidArgument

ISO/IEC TR-24772 provides bounds checking interfaces for potentially unsafe functions like memcpy(), strcpy() and memmove(). However, not all standard libraries provides them, like Glibc. The library's memmove_s() is a near-drop in replacement. Its only a near-replacement because the library's version throws an InvalidArgument on a bounds violation.

memcpy_s() and memmove_s() are guarded by STDC_WANT_SECURE_LIB. If STDC_WANT_SECURE_LIB is not defined or defined to 0, then the library makes memcpy_s() and memmove_s() available. The library will also optionally make the symbols available if CRYPTOPP_WANT_SECURE_LIB is defined. CRYPTOPP_WANT_SECURE_LIB is in config.h, but it is disabled by default.

memmove_s() will assert the pointers src and dest are not NULL in debug builds. Passing NULL for either pointer is undefined behavior.

Definition at line 571 of file misc.h.

◆ memset_z()

void * memset_z ( void *  ptr,
int  val,
size_t  num 
)
inline

Memory block initializer.

Parameters
ptrpointer to the memory block being written
valthe integer value to write for each byte
numthe size of the source memory block, in bytes

Internally the function calls memset with the value val. memset_z can be used to initialize a freshly allocated memory block. To zeroize a memory block on destruction use SecureWipeBuffer.

Returns
the pointer to the memory block
See also
SecureWipeBuffer

Definition at line 638 of file misc.h.

◆ ModPowerOf2()

template<class T1 , class T2 >
T2 ModPowerOf2 ( const T1 &  a,
const T2 &  b 
)
inline

Reduces a value to a power of 2.

Template Parameters
T1class or type
T2class or type
Parameters
athe first value
bthe second value
Returns
ModPowerOf2() returns a & (b-1). b must be a power of 2. Use IsPowerOf2() to determine if b is a suitable candidate.
See also
IsPowerOf2

Definition at line 1125 of file misc.h.

◆ NativeByteOrderIs()

bool NativeByteOrderIs ( ByteOrder  order)
inline

Determines whether order follows native byte ordering.

Parameters
orderthe ordering being tested against native byte ordering
Returns
true if order follows native byte ordering, false otherwise

Definition at line 1272 of file misc.h.

◆ NumericLimitsMax()

template<class T >
T NumericLimitsMax ( )
inline

Provide the maximum value for a type.

Template Parameters
Ttype of class
Returns
the maximum value of the type or class

NumericLimitsMax() was introduced for Clang at Issue 364, Apple Clang 6.0 and numeric_limits<word128>::max() returns 0.

NumericLimitsMax() requires a specialization for T, meaning std::numeric_limits<T>::is_specialized must return true. In the case of word128 Clang did not specialize numeric_limits for the type.

Since
Crypto++ 8.1

Definition at line 1061 of file misc.h.

◆ NumericLimitsMin()

template<class T >
T NumericLimitsMin ( )
inline

Provide the minimum value for a type.

Template Parameters
Ttype of class
Returns
the minimum value of the type or class

NumericLimitsMin() was introduced for Clang at Issue 364, Apple Clang 6.0 and numeric_limits<word128>::max() returns 0.

NumericLimitsMin() requires a specialization for T, meaning std::numeric_limits<T>::is_specialized must return true. In the case of word128 Clang did not specialize numeric_limits for the type.

Since
Crypto++ 8.1

Definition at line 1043 of file misc.h.

◆ Parity()

template<class T >
unsigned int Parity ( value)

Returns the parity of a value.

Template Parameters
Tclass or type
Parameters
valuethe value to provide the parity
Returns
1 if the number 1-bits in the value is odd, 0 otherwise

Definition at line 807 of file misc.h.

◆ PtrAdd()

template<typename PTR , typename OFF >
PTR PtrAdd ( PTR  pointer,
OFF  offset 
)
inline

Create a pointer with an offset.

Template Parameters
PTRa pointer type
OFFa size type
Parameters
pointera pointer
offseta offset into the pointer

PtrAdd can be used to squash Clang and GCC UBsan findings for pointer addition and subtraction.

Definition at line 386 of file misc.h.

◆ PtrByteDiff()

template<typename PTR >
size_t PtrByteDiff ( const PTR  pointer1,
const PTR  pointer2 
)
inline

Determine pointer difference.

Template Parameters
PTRa pointer type
Parameters
pointer1the first pointer
pointer2the second pointer

PtrByteDiff can be used to squash Clang and GCC UBsan findings for pointer addition and subtraction. pointer1 and pointer2 must point to the same object or array (or one past the end), and yields the number of bytes (not elements) difference.

Definition at line 429 of file misc.h.

◆ PtrDiff()

template<typename PTR >
ptrdiff_t PtrDiff ( const PTR  pointer1,
const PTR  pointer2 
)
inline

Determine pointer difference.

Template Parameters
PTRa pointer type
Parameters
pointer1the first pointer
pointer2the second pointer

PtrDiff can be used to squash Clang and GCC UBsan findings for pointer addition and subtraction. pointer1 and pointer2 must point to the same object or array (or one past the end), and yields the number of elements (not bytes) difference.

Definition at line 414 of file misc.h.

◆ PtrSub()

template<typename PTR , typename OFF >
PTR PtrSub ( PTR  pointer,
OFF  offset 
)
inline

Create a pointer with an offset.

Template Parameters
PTRa pointer type
OFFa size type
Parameters
pointera pointer
offseta offset into the pointer

PtrSub can be used to squash Clang and GCC UBsan findings for pointer addition and subtraction.

Definition at line 399 of file misc.h.

◆ PutWord()

template<class T >
void PutWord ( bool  assumeAligned,
ByteOrder  order,
byte block,
value,
const byte xorBlock = NULLPTR 
)
inline

Access a block of memory.

Template Parameters
Tclass or type
Parameters
assumeAlignedflag indicating alignment
orderthe ByteOrder of the data
blockthe destination byte buffer
valuethe word in the specified byte order
xorBlockan optional byte buffer to xor

PutWord() provides alternate write access to a block of memory. The flag assumeAligned indicates if the memory block is aligned for class or type T. The enumeration ByteOrder is BIG_ENDIAN_ORDER or LITTLE_ENDIAN_ORDER.

Definition at line 2739 of file misc.h.

◆ rotlConstant()

template<unsigned int R, class T >
T rotlConstant ( x)
inline

Performs a left rotate.

Template Parameters
Rthe number of bit positions to rotate the value
Tthe word type
Parameters
xthe value to rotate

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

R must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotlMod if the rotate amount R is outside the range.

Use rotlConstant when the rotate amount is constant. The template function was added because Clang did not propagate the constant when passed as a function parameter. Clang's need for a constexpr meant rotlFixed failed to compile on occasion.

Note
rotlConstant attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 6.0

Definition at line 1548 of file misc.h.

◆ rotlFixed()

template<class T >
T rotlFixed ( x,
unsigned int  y 
)
inline

Performs a left rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotlMod if the rotate amount y is outside the range.

Note
rotlFixed attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts. New code should use rotlConstant, which accepts the rotate amount as a template parameter.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 6.0

Definition at line 1599 of file misc.h.

◆ rotlMod()

template<class T >
T rotlMod ( x,
unsigned int  y 
)
inline

Performs a left rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y is reduced to the range [0, sizeof(T)*8 - 1] to avoid undefined behavior.

Note
rotrVariable will use either rotate IMM or rotate REG.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 3.0

Definition at line 1685 of file misc.h.

◆ rotlVariable()

template<class T >
T rotlVariable ( x,
unsigned int  y 
)
inline

Performs a left rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotlMod if the rotate amount y is outside the range.

Note
rotlVariable attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 3.0

Definition at line 1648 of file misc.h.

◆ rotrConstant()

template<unsigned int R, class T >
T rotrConstant ( x)
inline

Performs a right rotate.

Template Parameters
Rthe number of bit positions to rotate the value
Tthe word type
Parameters
xthe value to rotate

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

R must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotrMod if the rotate amount R is outside the range.

Use rotrConstant when the rotate amount is constant. The template function was added because Clang did not propagate the constant when passed as a function parameter. Clang's need for a constexpr meant rotrFixed failed to compile on occasion.

Note
rotrConstant attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable

Definition at line 1574 of file misc.h.

◆ rotrFixed()

template<class T >
T rotrFixed ( x,
unsigned int  y 
)
inline

Performs a right rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotrMod if the rotate amount y is outside the range.

Note
rotrFixed attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts. New code should use rotrConstant, which accepts the rotate amount as a template parameter.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 3.0

Definition at line 1624 of file misc.h.

◆ rotrMod()

template<class T >
T rotrMod ( x,
unsigned int  y 
)
inline

Performs a right rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y is reduced to the range [0, sizeof(T)*8 - 1] to avoid undefined behavior.

Note
rotrVariable will use either rotate IMM or rotate REG.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 3.0

Definition at line 1701 of file misc.h.

◆ rotrVariable()

template<class T >
T rotrVariable ( x,
unsigned int  y 
)
inline

Performs a right rotate.

Template Parameters
Tthe word type
Parameters
xthe value to rotate
ythe number of bit positions to rotate the value

This is a portable C/C++ implementation. The value x to be rotated can be 8 to 64-bits wide.

y must be in the range [0, sizeof(T)*8 - 1] to avoid undefined behavior. Use rotrMod if the rotate amount y is outside the range.

Note
rotrVariable attempts to enlist a rotate IMM instruction because its often faster than a rotate REG. Immediate rotates can be up to three times faster than their register counterparts.
See also
rotlConstant, rotrConstant, rotlFixed, rotrFixed, rotlVariable, rotrVariable
Since
Crypto++ 3.0

Definition at line 1668 of file misc.h.

◆ RoundDownToMultipleOf()

template<class T1 , class T2 >
T1 RoundDownToMultipleOf ( const T1 &  n,
const T2 &  m 
)
inline

Rounds a value down to a multiple of a second value.

Template Parameters
T1class or type
T2class or type
Parameters
nthe value to reduce
mthe value to reduce n to a multiple
Returns
the possibly unmodified value

RoundDownToMultipleOf is effectively a floor function based on m. The function returns the value n - n%m. If n is a multiple of m, then the original value is returned.

Note
T1 and T2 should be unsigned arithmetic types. If T1 or T2 is signed, then the value should be non-negative. The library asserts in debug builds when practical, but allows you to perform the operation in release builds.

Definition at line 1145 of file misc.h.

◆ RoundUpToMultipleOf()

template<class T1 , class T2 >
T1 RoundUpToMultipleOf ( const T1 &  n,
const T2 &  m 
)
inline

Rounds a value up to a multiple of a second value.

Template Parameters
T1class or type
T2class or type
Parameters
nthe value to reduce
mthe value to reduce n to a multiple
Returns
the possibly unmodified value

RoundUpToMultipleOf is effectively a ceiling function based on m. The function returns the value n + n%m. If n is a multiple of m, then the original value is returned. If the value n would overflow, then an InvalidArgument exception is thrown.

Note
T1 and T2 should be unsigned arithmetic types. If T1 or T2 is signed, then the value should be non-negative. The library asserts in debug builds when practical, but allows you to perform the operation in release builds.

Definition at line 1175 of file misc.h.

◆ SafeConvert()

template<class T1 , class T2 >
bool SafeConvert ( T1  from,
T2 &  to 
)
inline

Tests whether a conversion from -> to is safe to perform.

Template Parameters
T1class or type
T2class or type
Parameters
fromthe first value
tothe second value
Returns
true if its safe to convert from into to, false otherwise.

Definition at line 710 of file misc.h.

◆ SafeLeftShift()

template<unsigned int bits, class T >
T SafeLeftShift ( value)
inline

Safely left shift values when undefined behavior could occur.

Template Parameters
bitsthe number of bit positions to shift the value
Tclass or type
Parameters
valuethe value to left shift
Returns
the shifted value or 0

SafeLeftShift safely shifts the value to the left when undefined behavior could occur under C/C++ rules. SafeLeftShift will return the shifted value or 0 if undefined behavior would occur.

Definition at line 2968 of file misc.h.

◆ SafeRightShift()

template<unsigned int bits, class T >
T SafeRightShift ( value)
inline

Safely right shift values when undefined behavior could occur.

Template Parameters
bitsthe number of bit positions to shift the value
Tclass or type
Parameters
valuethe value to right shift
Returns
the shifted value or 0

SafeRightShift safely shifts the value to the right when undefined behavior could occur under C/C++ rules. SafeRightShift will return the shifted value or 0 if undefined behavior would occur.

Definition at line 2954 of file misc.h.

◆ SaturatingSubtract()

template<class T1 , class T2 >
T1 SaturatingSubtract ( const T1 &  a,
const T2 &  b 
)
inline

Performs a saturating subtract clamped at 0.

Template Parameters
T1class or type
T2class or type
Parameters
athe minuend
bthe subtrahend
Returns
the difference produced by the saturating subtract

Saturating arithmetic restricts results to a fixed range. Results that are less than 0 are clamped at 0.

Use of saturating arithmetic in places can be advantageous because it can avoid a branch by using an instruction like a conditional move (CMOVE).

Definition at line 1093 of file misc.h.

◆ SaturatingSubtract1()

template<class T1 , class T2 >
T1 SaturatingSubtract1 ( const T1 &  a,
const T2 &  b 
)
inline

Performs a saturating subtract clamped at 1.

Template Parameters
T1class or type
T2class or type
Parameters
athe minuend
bthe subtrahend
Returns
the difference produced by the saturating subtract

Saturating arithmetic restricts results to a fixed range. Results that are less than 1 are clamped at 1.

Use of saturating arithmetic in places can be advantageous because it can avoid a branch by using an instruction like a conditional move (CMOVE).

Definition at line 1110 of file misc.h.

◆ SecureWipeArray()

template<class T >
void SecureWipeArray ( T *  buf,
size_t  n 
)
inline

Sets each element of an array to 0.

Template Parameters
Tclass or type
Parameters
bufan array of elements
nthe number of elements in the array

The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.

Definition at line 1491 of file misc.h.

◆ SecureWipeBuffer()

template<class T >
void SecureWipeBuffer ( T *  buf,
size_t  n 
)

Sets each element of an array to 0.

Template Parameters
Tclass or type
Parameters
bufan array of elements
nthe number of elements in the array

The operation performs a wipe or zeroization. The function attempts to survive optimizations and dead code removal.

Definition at line 1375 of file misc.h.

◆ STDMAX()

template<class T >
const T & STDMAX ( const T &  a,
const T &  b 
)
inline

Replacement function for std::max.

Template Parameters
Tclass or type
Parameters
athe first value
bthe second value
Returns
the minimum value based on a comparison of a < b using operator<

STDMAX was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0

Definition at line 666 of file misc.h.

◆ STDMIN()

template<class T >
const T & STDMIN ( const T &  a,
const T &  b 
)
inline

Replacement function for std::min.

Template Parameters
Tclass or type
Parameters
athe first value
bthe second value
Returns
the minimum value based on a comparison of b < a using operator<

STDMIN was provided because the library could not easily use std::min or std::max in Windows or Cygwin 1.1.0

Definition at line 655 of file misc.h.

◆ StringNarrow()

std::string StringNarrow ( const wchar_t *  str,
bool  throwOnError = true 
)

Converts a wide character C-string to a multibyte string.

Parameters
strC-string consisting of wide characters
throwOnErrorflag indicating the function should throw on error
Returns
str converted to a multibyte string or an empty string.

StringNarrow() converts a wide string to a narrow string using C++ std::wcstombs() under the executing thread's locale. A locale must be set before using this function, and it can be set with std::setlocale() if needed. Upon success, the converted string is returned.

Upon failure with throwOnError as false, the function returns an empty string. If throwOnError as true, the function throws an InvalidArgument() exception.

Note
If you try to convert, say, the Chinese character for "bone" from UTF-16 (0x9AA8) to UTF-8 (0xE9 0xAA 0xA8), then you must ensure the locale is available. If the locale is not available, then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.

Definition at line 264 of file misc.cpp.

◆ StringToWord()

template<class T >
T StringToWord ( const std::string &  str,
ByteOrder  order = BIG_ENDIAN_ORDER 
)

Convert a string to a word.

Template Parameters
Tclass or type
Parameters
strthe string to convert
orderbyte order
Returns
a word representing the value of the string

Definition at line 2870 of file misc.h.

◆ StringWiden()

std::wstring StringWiden ( const char *  str,
bool  throwOnError = true 
)

Converts a multibyte C-string to a wide character string.

Parameters
strC-string consisting of wide characters
throwOnErrorflag indicating the function should throw on error
Returns
str converted to a multibyte string or an empty string.

StringWiden() converts a narrow string to a wide string using C++ std::mbstowcs() under the executing thread's locale. A locale must be set before using this function, and it can be set with std::setlocale() if needed. Upon success, the converted string is returned.

Upon failure with throwOnError as false, the function returns an empty string. If throwOnError as true, the function throws an InvalidArgument() exception.

Note
If you try to convert, say, the Chinese character for "bone" from UTF-8 (0xE9 0xAA 0xA8) to UTF-16 (0x9AA8), then you must ensure the locale is available. If the locale is not available, then a 0x21 error is returned on Windows which eventually results in an InvalidArgument() exception.

Definition at line 328 of file misc.cpp.

◆ TrailingZeros() [1/2]

unsigned int TrailingZeros ( word32  v)
inline

Determines the number of trailing 0-bits in a value

Parameters
vthe 32-bit value to test
Returns
the number of trailing 0-bits in v, starting at the least significant bit position

TrailingZeros returns the number of trailing 0-bits in v, starting at the least significant bit position. The return value is undefined if there are no 1-bits set in the value v.

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.

Definition at line 867 of file misc.h.

◆ TrailingZeros() [2/2]

unsigned int TrailingZeros ( word64  v)
inline

Determines the number of trailing 0-bits in a value

Parameters
vthe 64-bit value to test
Returns
the number of trailing 0-bits in v, starting at the least significant bit position

TrailingZeros returns the number of trailing 0-bits in v, starting at the least significant bit position. The return value is undefined if there are no 1-bits set in the value v.

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.

Definition at line 898 of file misc.h.

◆ UnalignedbyteNonTemplate() [1/4]

void UnalignedbyteNonTemplate ( ByteOrder  order,
byte block,
byte  value,
const byte xorBlock 
)
inline

Write a byte to an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned output buffer
valuebyte value
xorBlockoptional unaligned xor buffer

UnalignedbyteNonTemplate writes a byte value to an unaligned buffer.

Since
Crypto++ 1.0

Definition at line 2431 of file misc.h.

◆ UnalignedbyteNonTemplate() [2/4]

void UnalignedbyteNonTemplate ( ByteOrder  order,
byte block,
word16  value,
const byte xorBlock 
)
inline

Write a word16 to an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned output buffer
valueword16 value
xorBlockoptional unaligned xor buffer

UnalignedbyteNonTemplate writes a word16 value to an unaligned buffer.

Since
Crypto++ 1.0

Definition at line 2444 of file misc.h.

◆ UnalignedbyteNonTemplate() [3/4]

void UnalignedbyteNonTemplate ( ByteOrder  order,
byte block,
word32  value,
const byte xorBlock 
)
inline

Write a word32 to an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned output buffer
valueword32 value
xorBlockoptional unaligned xor buffer

UnalignedbyteNonTemplate writes a word32 value to an unaligned buffer.

Since
Crypto++ 1.0

Definition at line 2481 of file misc.h.

◆ UnalignedbyteNonTemplate() [4/4]

void UnalignedbyteNonTemplate ( ByteOrder  order,
byte block,
word64  value,
const byte xorBlock 
)
inline

Write a word64 to an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned output buffer
valueword64 value
xorBlockoptional unaligned xor buffer

UnalignedbyteNonTemplate writes a word64 value to an unaligned buffer.

Since
Crypto++ 1.0

Definition at line 2526 of file misc.h.

◆ UnalignedGetWordNonTemplate() [1/4]

byte UnalignedGetWordNonTemplate ( ByteOrder  order,
const byte block,
const byte unused 
)
inline

Retrieve a byte from an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned buffer
unuseddummy parameter
Returns
byte value

UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a byte value.

Since
Crypto++ 1.0

Definition at line 2307 of file misc.h.

◆ UnalignedGetWordNonTemplate() [2/4]

word16 UnalignedGetWordNonTemplate ( ByteOrder  order,
const byte block,
const word16 unused 
)
inline

Retrieve a word16 from an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned buffer
unuseddummy parameter
Returns
byte value

UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word16 value.

Since
Crypto++ 1.0

Definition at line 2320 of file misc.h.

◆ UnalignedGetWordNonTemplate() [3/4]

word32 UnalignedGetWordNonTemplate ( ByteOrder  order,
const byte block,
const word32 unused 
)
inline

Retrieve a word32 from an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned buffer
unuseddummy parameter
Returns
byte value

UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word32 value.

Since
Crypto++ 1.0

Definition at line 2335 of file misc.h.

◆ UnalignedGetWordNonTemplate() [4/4]

word64 UnalignedGetWordNonTemplate ( ByteOrder  order,
const byte block,
const word64 *  unused 
)
inline

Retrieve a word64 from an unaligned buffer.

Parameters
orderthe ByteOrder of the data
blockan unaligned buffer
unuseddummy parameter
Returns
byte value

UnalignedGetWordNonTemplate accesses an unaligned buffer and returns a word64 value.

Since
Crypto++ 1.0

Definition at line 2350 of file misc.h.

◆ UnsignedMin()

template<class T1 , class T2 >
const T1 UnsignedMin ( const T1 &  a,
const T2 &  b 
)
inline

Safe comparison of values that could be negative and incorrectly promoted.

Template Parameters
T1class or type
T2class or type
Parameters
athe first value
bthe second value
Returns
the minimum value based on a comparison a and b using operator<.

The comparison b < a is performed and the value returned is a's type T1.

Definition at line 694 of file misc.h.

◆ vec_swap()

template<class T >
void vec_swap ( T &  a,
T &  b 
)
inline

Swaps two variables which are arrays.

Template Parameters
Tclass or type
Parameters
athe first value
bthe second value

C++03 does not provide support for std::swap(__m128i a, __m128i b) because __m128i is an unsigned long long[2]. Most compilers support it out of the box, but Sun Studio C++ compilers 12.2 and 12.3 do not.

See also
How to swap two __m128i variables in C++03 given its an opaque type and an array? on Stack Overflow.

Definition at line 616 of file misc.h.

◆ VerifyBufsEqual()

CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual ( const byte buf1,
const byte buf2,
size_t  count 
)

Performs a near constant-time comparison of two equally sized buffers.

Parameters
buf1the first buffer
buf2the second buffer
countthe size of the buffers, in bytes

VerifyBufsEqual performs an XOR of the elements in two equally sized buffers and returns a result based on the XOR operation. A count of 0 returns true because two empty buffers are considered equal.

The function is near constant-time because CPU micro-code timings could affect the "constant-ness". Calling code is responsible for mitigating timing attacks if the buffers are not equally sized.

See also
ModPowerOf2

Definition at line 218 of file misc.cpp.

◆ WordToString()

template<class T >
std::string WordToString ( value,
ByteOrder  order = BIG_ENDIAN_ORDER 
)

Convert a word to a string.

Template Parameters
Tclass or type
Parameters
valuethe word to convert
orderbyte order
Returns
a string representing the value of the word

Definition at line 2856 of file misc.h.

◆ xorbuf() [1/2]

CRYPTOPP_DLL void CRYPTOPP_API xorbuf ( byte buf,
const byte mask,
size_t  count 
)

Performs an XOR of a buffer with a mask

Parameters
bufthe buffer to XOR with the mask
maskthe mask to XOR with the buffer
countthe size of the buffers, in bytes

The function effectively visits each element in the buffers and performs buf[i] ^= mask[i]. buf and mask must be of equal size.

Definition at line 70 of file misc.cpp.

◆ xorbuf() [2/2]

CRYPTOPP_DLL void CRYPTOPP_API xorbuf ( byte output,
const byte input,
const byte mask,
size_t  count 
)

Performs an XOR of an input buffer with a mask and stores the result in an output buffer

Parameters
outputthe destination buffer
inputthe source buffer to XOR with the mask
maskthe mask buffer to XOR with the input buffer
countthe size of the buffers, in bytes

The function effectively visits each element in the buffers and performs output[i] = input[i] ^ mask[i]. output, input and mask must be of equal size.

Definition at line 144 of file misc.cpp.