misc.h File Reference

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

Go to the source code of this file.

Classes

class  ObjectHolder< T >
 Uses encapsulation to hide an object in derived classes. More...
class  NotCopyable
 Ensures an object is not copyable. More...
class  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 >
class  PutBlock< T, B, A >
struct  BlockGetAndPut< T, B, GA, PA >
struct  SafeShifter< true >
struct  SafeShifter< false >

Defines

#define SIZE_MAX   ...
 The maximum value of a machine word.
#define CRYPTOPP_COMPILE_ASSERT(expr)   ...
 Compile time assertion.
#define COUNTOF(arr)
 Counts elements in an array.
#define MEMORY_BARRIER   ...
 A memory barrier.
#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 *)(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 *)(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 *)(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 *)(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 *)(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 *)(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 *)(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 *)(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

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().
void * memset_z (void *ptr, int value, size_t num)
 Memory block initializer and eraser that attempts to survive optimizations.
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 neagtive 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<>
std::string IntToString< unsigned long long > (unsigned long long value, unsigned int base)
 Converts an unsigned value to a string.
template<>
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)
 Determines the number of trailing 0-bits in a value.
unsigned int TrailingZeros (word64 v)
 Determines the number of trailing 0-bits in a value.
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.
void xorbuf (byte *buf, const byte *mask, size_t count)
 Performs an XOR of a buffer with a mask.
void 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.
bool 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 T1 , class T2 >
T2 ModPowerOf2 (const T1 &a, const T2 &b)
 Tests whether the residue of a value is 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 (T *dummy=NULL)
 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, T *dummy=NULL)
 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 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 T >
CipherDir GetCipherDir (const T &obj)
 Returns the direction the cipher is being operated.
void CallNewHandler ()
 Attempts to reclaim unused memory.
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 branchless swap of values a and b if condition c is true.
template<class T >
void ConditionalSwapPointers (bool c, T &a, T &b)
 Performs a branchless 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.
void * AlignedAllocate (size_t size)
 Allocates a buffer on 16-byte boundary.
void AlignedDeallocate (void *ptr)
 Frees a buffer allocated with AlignedAllocate.
void * UnalignedAllocate (size_t size)
 Allocates a buffer.
void UnalignedDeallocate (void *ptr)
 Frees a buffer allocated with UnalignedAllocate.
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 endianess.
template<class T >
void ByteReverse (T *out, const T *in, size_t byteCount)
 Reverses bytes in an element among an array of elements.
template<class T >
void ConditionalByteReverse (ByteOrder order, T *out, const T *in, size_t byteCount)
 Reverses bytes in an element among an array of elements depending upon endianess.
template<class T >
void GetUserKey (ByteOrder order, T *out, size_t outlen, const byte *in, size_t inlen)
byte UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const byte *)
word16 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word16 *)
word32 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word32 *)
word64 UnalignedGetWordNonTemplate (ByteOrder order, const byte *block, const word64 *)
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, byte value, const byte *xorBlock)
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word16 value, const byte *xorBlock)
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word32 value, const byte *xorBlock)
void UnalignedbyteNonTemplate (ByteOrder order, byte *block, word64 value, const byte *xorBlock)
template<class T >
GetWord (bool assumeAligned, ByteOrder order, const byte *block)
template<class T >
void GetWord (bool assumeAligned, ByteOrder order, T &result, const byte *block)
template<class T >
void PutWord (bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
template<class T >
std::string WordToString (T value, ByteOrder order=BIG_ENDIAN_ORDER)
template<class T >
StringToWord (const std::string &str, ByteOrder order=BIG_ENDIAN_ORDER)
template<unsigned int bits, class T >
SafeRightShift (T value)
template<unsigned int bits, class T >
SafeLeftShift (T value)

Detailed Description

Utility functions for the Crypto++ library.

Definition in file misc.h.


Define Documentation

#define SIZE_MAX   ...

The maximum value of a machine word.

SIZE_MAX provides the maximum value of a machine word. The value is 0xffffffff on 32-bit machines, and 0xffffffffffffffff on 64-bit machines. Internally, SIZE_MAX is defined as __SIZE_MAX__ if __SIZE_MAX__ is defined. If not defined, then SIZE_T_MAX is tried. If neither __SIZE_MAX__ nor SIZE_T_MAX is is defined, the library uses std::numeric_limits<size_t>::max(). The library prefers __SIZE_MAX__ because its a constexpr that is optimized well by all compilers. std::numeric_limits<size_t>::max() is not a constexpr, and it is not always optimized well.

Definition at line 73 of file misc.h.

Referenced by PolynomialMod2::AllOnes(), FilterWithBufferedInput::FilterWithBufferedInput(), FilterWithBufferedInput::IsolatedInitialize(), AllocatorBase< word32 >::max_size(), and RoundUpToMultipleOf().

#define CRYPTOPP_COMPILE_ASSERT ( expr   )     ...

Compile time assertion.

Parameters:
expr the expression to evaluate

Asserts the expression expr though a dummy struct.

Definition at line 101 of file misc.h.

Referenced by RandomPool::GenerateIntoBufferedTransformation(), and UnsignedMin().

#define COUNTOF ( arr   ) 

Counts elements in an array.

Parameters:
arr an array of elements

COUNTOF counts elements in an array. On Windows COUNTOF(x) is deinfed to _countof(x) to ensure correct results for pointers. Since the library code is cross-platform, Windows will ensure the safety on non-Windows platforms.

Note:
COUNTOF does not produce correct results with pointers, and an array must be used. The library ensures correct application of COUNTOF by enlisting _countof on Windows platforms. Microsoft's _countof fails to compile using pointers.

Definition at line 140 of file misc.h.

#define MEMORY_BARRIER   ...

A memory barrier.

MEMORY_BARRIER attempts to ensure reads and writes are completed in the absence of a language synchronization point. It is used by the Singleton class if the compiler supports it. The use is provided at the customary check points in a double-checked initialization.

Internally, MEMORY_BARRIER uses intrinsic(_ReadWriteBarrier), _ReadWriteBarrier() or __asm__("" ::: "memory").

Definition at line 213 of file misc.h.

Referenced by Singleton< T, F, instance >::Ref().


Function Documentation

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

Bounds checking replacement for memcpy().

Parameters:
dest pointer to the desination memory block
sizeInBytes the size of the desination memory block, in bytes
src pointer to the source memory block
count the size of the source memory block, in bytes
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 299 of file misc.h.

Referenced by SecBlock< word32 >::Assign(), ConditionalByteReverse(), PKCS12_PBKDF< T >::DeriveKey(), PKCS5_PBKDF2_HMAC< T >::DeriveKey(), HKDF< T >::DeriveKey(), IncrementCounterByOne(), SecBlock< word32 >::operator+(), SecBlock< word32 >::operator+=(), FixedSizeAllocatorWithCleanup< unsigned int, S >::reallocate(), BlockOrientedCipherModeBase::Resynchronize(), SecBlock< word32 >::SecBlock(), and StandardReallocate().

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

Bounds checking replacement for memmove().

Parameters:
dest pointer to the desination memory block
sizeInBytes the size of the desination memory block, in bytes
src pointer to the source memory block
count the size of the source memory block, in bytes
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 341 of file misc.h.

void* memset_z ( void *  ptr,
int  value,
size_t  num 
) [inline]

Memory block initializer and eraser that attempts to survive optimizations.

Parameters:
ptr pointer to the memory block being written
value the integer value to write for each byte
num the size of the source memory block, in bytes

Internally the function calls memset with the value value, and receives the return value from memset as a volatile pointer.

Definition at line 379 of file misc.h.

Referenced by SecBlock< word32 >::CleanGrow(), and SecBlock< word32 >::CleanNew().

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

Replacement function for std::min.

Parameters:
a the first value
b the second value
Returns:
the minimum value based on a comparison of b < a using operator<

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

Definition at line 395 of file misc.h.

Referenced by ESIGNFunction::ApplyFunction(), EqualityComparisonFilter::ChannelPut2(), PKCS12_PBKDF< T >::DeriveKey(), PKCS5_PBKDF2_HMAC< T >::DeriveKey(), HKDF< T >::DeriveKey(), AdditiveCipherTemplate< BASE >::GenerateBlock(), NetworkSink::GetMaxObservedSpeed(), IntegrityCheckModule(), MaurerProvablePrime(), MihailescuProvablePrime(), ArrayXorSink::Put2(), ArraySink::Put2(), Grouper::Put2(), FixedSizeAllocatorWithCleanup< unsigned int, S >::reallocate(), AutoSeededX917RNG< BLOCK_CIPHER >::Reseed(), and StandardReallocate().

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

Replacement function for std::max.

Parameters:
a the first value
b the second value
Returns:
the minimum value based on a comparison of a < b using operator<

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

Definition at line 405 of file misc.h.

Referenced by NetworkSink::ComputeCurrentSpeed(), ByteQueue::CreatePutSpace(), PolynomialOver< T >::Divide(), Integer::Encode(), FixedSizeAllocatorWithCleanup< unsigned int, S >::max_size(), Integer::MinEncodedSize(), PolynomialMod2::MinEncodedSize(), and ByteQueue::Put2().

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

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

Parameters:
a the first value
b the 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 431 of file misc.h.

References CRYPTOPP_COMPILE_ASSERT.

Referenced by NonblockingSource::GeneralPump2(), X917RNG::GenerateIntoBufferedTransformation(), RandomPool::GenerateIntoBufferedTransformation(), RandomNumberGenerator::GenerateIntoBufferedTransformation(), GetAlignmentOf(), NetworkSink::Put2(), WindowsPipeReceiver::Receive(), SocketReceiver::Receive(), AutoSeededX917RNG< BLOCK_CIPHER >::Reseed(), NonblockingSink::TimedFlush(), DMAC_Base< T >::UncheckedSetKey(), Weak::MD2::Update(), CMAC_Base::Update(), and X917RNG::X917RNG().

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

Tests whether a conversion from → to is safe to perform.

Parameters:
from the first value
to the second value
Returns:
true if its safe to convert from into to, false otherwise.

Definition at line 445 of file misc.h.

Referenced by FileSink::Put2(), PK_DefaultDecryptionFilter::Put2(), PK_DefaultEncryptionFilter::Put2(), and FileStore::Skip().

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

Converts a value to a string.

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

Definition at line 458 of file misc.h.

Referenced by VMAC_Base::AlgorithmName(), SHA3::AlgorithmName(), TF_DecryptorBase::Decrypt(), TF_EncryptorBase::Encrypt(), Deflator::IsolatedInitialize(), Socket::PortNameToNumber(), Deflator::SetDeflateLevel(), AuthenticatedSymmetricCipher::SpecifyDataLengths(), TTMAC_Base::TruncatedFinal(), and AuthenticatedSymmetricCipherBase::TruncatedFinal().

template<>
std::string IntToString< unsigned long long > ( unsigned long long  value,
unsigned int  base 
) [inline]

Converts an unsigned value to a string.

Parameters:
value the value to convert
base the 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.

template<>
std::string IntToString< Integer > ( Integer  value,
unsigned int  base 
) [inline]

Converts an Integer to a string.

Parameters:
value the Integer to convert
base the 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.sha

Print integer in base 10, uppercase letters
      Integer n...
      const unsigned int UPPER = (1 << 31);
      std::string s = IntToString(n, (UPPER | 10));
    
template<class T >
unsigned int Parity ( value  )  [inline]

Returns the parity of a value.

Parameters:
value the value to provide the parity
Returns:
1 if the number 1-bits in the value is odd, 0 otherwise

Definition at line 541 of file misc.h.

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

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

Parameters:
value the value to test
Returns:
the minimum number of 8-bit bytes or octets required to represent a value

Definition at line 552 of file misc.h.

Referenced by Integer::ByteCount(), PolynomialMod2::ByteCount(), and DERLengthEncode().

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

Returns the number of bits required for a value.

Parameters:
value the value to test
Returns:
the maximum number of bits required to represent a value.

Definition at line 574 of file misc.h.

Referenced by Integer::BitCount(), PolynomialMod2::BitCount(), Integer::Divide(), MersenneTwister< K, M, N, F, S >::GenerateWord32(), and RandomNumberGenerator::GenerateWord32().

unsigned int TrailingZeros ( word32  v  )  [inline]

Determines the number of trailing 0-bits in a value.

Parameters:
v the 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 599 of file misc.h.

Referenced by TrailingZeros().

unsigned int TrailingZeros ( word64  v  )  [inline]

Determines the number of trailing 0-bits in a value.

Parameters:
v the 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 625 of file misc.h.

References TrailingZeros().

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

Truncates the value to the specified number of bits.

Parameters:
value the value to truncate or mask
bits the 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 647 of file misc.h.

Referenced by PolynomialMod2::AllOnes(), MersenneTwister< K, M, N, F, S >::GenerateWord32(), RandomNumberGenerator::GenerateWord32(), and Integer::Randomize().

size_t BitsToBytes ( size_t  bitCount  )  [inline]

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

Parameters:
bitCount the 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 659 of file misc.h.

Referenced by Integer::OpenPGPDecode(), and Integer::OpenPGPEncode().

size_t BytesToWords ( size_t  byteCount  )  [inline]

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

Parameters:
byteCount the 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 669 of file misc.h.

Referenced by Integer::Decode(), Integer::SetByte(), and PolynomialMod2::SetByte().

size_t BitsToWords ( size_t  bitCount  )  [inline]

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

Parameters:
bitCount the 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 679 of file misc.h.

Referenced by PolynomialMod2::Divide(), Integer::DivideByPowerOf2(), Integer::Power2(), and Integer::SetBit().

size_t BitsToDwords ( size_t  bitCount  )  [inline]

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

Parameters:
bitCount the 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 689 of file misc.h.

void xorbuf ( byte *  buf,
const byte *  mask,
size_t  count 
)

Performs an XOR of a buffer with a mask.

Parameters:
buf the buffer to XOR with the mask
mask the mask to XOR with the buffer
count the 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 28 of file misc.cpp.

void 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:
output the destination buffer
input the source buffer to XOR with the mask
mask the mask buffer to XOR with the input buffer
count the 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 61 of file misc.cpp.

bool VerifyBufsEqual ( const byte *  buf1,
const byte *  buf2,
size_t  count 
)

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

Parameters:
buf1 the first buffer
buf2 the second buffer
count the size of the buffers, in bytes

The function effectively performs an XOR of the elements in two equally sized buffers and retruns a result based on the XOR operation. 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.

Definition at line 96 of file misc.cpp.

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

Tests whether a value is a power of 2.

Parameters:
value the 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 727 of file misc.h.

Referenced by IsAlignedOn(), ModPowerOf2(), and RoundDownToMultipleOf().

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

Tests whether the residue of a value is a power of 2.

Parameters:
a the value to test
b the value to use to reduce to its residue
Returns:
true if a%b is a power of 2, false otherwise

The function effectively creates a mask of b - 1 and returns the result of an AND operation compared to 0. b must be a power of 2 or the result is undefined.

Definition at line 739 of file misc.h.

References IsPowerOf2().

Referenced by IsAlignedOn(), RoundDownToMultipleOf(), and VMAC_Base::TruncatedFinal().

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.

Parameters:
n the value to reduce
m the value to reduce
to 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.

Definition at line 752 of file misc.h.

References IsPowerOf2(), and ModPowerOf2().

Referenced by 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.

Parameters:
n the value to reduce
m the value to reduce
to 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.

Definition at line 768 of file misc.h.

References RoundDownToMultipleOf(), and SIZE_MAX.

Referenced by PKCS12_PBKDF< T >::DeriveKey(), MersenneTwister< K, M, N, F, S >::DiscardBytes(), and AdditiveCipherTemplate< BASE >::GenerateBlock().

template<class T >
unsigned int GetAlignmentOf ( T *  dummy = NULL  )  [inline]

Returns the minimum alignment requirements of a type.

Parameters:
dummy an unused Visual C++ 6.0 workaround
Returns:
the minimum alignment requirements of a type, in bytes

Internally the function calls C++11's alignof if available. If not available, the function uses compiler specific extensions such as __alignof and _alignof_. sizeof(T) is used if the others are not available. In all cases, if CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS is defined, then the function returns 1.

Definition at line 783 of file misc.h.

References UnsignedMin().

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

Determines whether ptr is aligned to a minimum value.

Parameters:
ptr the pointer being checked for alignment
alignment the alignment value to test the pointer against
Returns:
true if ptr is aligned on at least align boundary

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 810 of file misc.h.

References IsPowerOf2(), and ModPowerOf2().

Referenced by FixedSizeAllocatorWithCleanup< unsigned int, S >::allocate(), and IsAligned().

template<class T >
bool IsAligned ( const void *  ptr,
T *  dummy = NULL 
) [inline]

Determines whether ptr is minimally aligned.

Parameters:
ptr the pointer to check for alignment
dummy an unused Visual C++ 6.0 workaround
Returns:
true if ptr follows native byte ordering, false otherwise

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

Definition at line 821 of file misc.h.

References IsAlignedOn().

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 IS_LITTLE_ENDIAN is set in GetNativeByteOrder returns LittleEndian. If IS_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 843 of file misc.h.

Referenced by NativeByteOrderIs().

bool NativeByteOrderIs ( ByteOrder  order  )  [inline]

Determines whether order follows native byte ordering.

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

Definition at line 851 of file misc.h.

References GetNativeByteOrder().

Referenced by ConditionalByteReverse().

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

Performs a saturating subtract clamped at 0.

Parameters:
a the minuend
b the 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 864 of file misc.h.

Referenced by ArraySink::CreatePutSpace(), NonblockingSource::GeneralPump2(), PKCS_EncryptionPaddingScheme::MaxUnpaddedLength(), OAEP_Base::MaxUnpaddedLength(), ArrayXorSink::Put2(), ArraySink::Put2(), and NonblockingSink::TimedFlush().

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

Performs a saturating subtract clamped at 1.

Parameters:
a the minuend
b the 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 878 of file misc.h.

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

Returns the direction the cipher is being operated.

Parameters:
obj the cipher object being queried
Returns:
/p ENCRYPTION if the cipher obj is being operated in its forward direction, DECRYPTION otherwise

ciphers can be operated in a "forward" direction (encryption) and a "reverse" direction (decryption). The operations do not have to be symmetric, meaning a second application of the transformation does not necessariy 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 893 of file misc.h.

void CallNewHandler (  ) 

Attempts to reclaim unused memory.

Exceptions:
bad_alloc 

In the normal course of running a program, a request for memory normally succeeds. If a call to AlignedAllocate or UnalignedAllocate fails, then CallNewHandler is called in an effort to recover. Internally, CallNewHandler calls set_new_handler(NULL) in an effort to free memory. There is no guarantee CallNewHandler will be able to procure more memory so an allocation succeeds. If the call to set_new_handler fails, then CallNewHandler throws a bad_alloc exception.

Definition at line 141 of file misc.cpp.

void IncrementCounterByOne ( byte *  inout,
unsigned int  size 
) [inline]

Performs an addition with carry on a block of bytes.

Parameters:
inout the byte block
size the 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 914 of file misc.h.

Referenced by X917RNG::GenerateIntoBufferedTransformation().

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

Performs an addition with carry on a block of bytes.

Parameters:
output the destination block of bytes
input the source block of bytes
size the 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 928 of file misc.h.

References memcpy_s().

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

Performs a branchless swap of values a and b if condition c is true.

Parameters:
c the condition to perform the swap
a the first value
b the second value

Definition at line 943 of file misc.h.

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

Performs a branchless swap of pointers a and b if condition c is true.

Parameters:
c the condition to perform the swap
a the first pointer
b the second pointer

Definition at line 955 of file misc.h.

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

Sets each element of an array to 0.

Parameters:
buf an array of elements
n the number of elements in the array

The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal

Definition at line 970 of file misc.h.

Referenced by SecureWipeArray().

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

Sets each element of an array to 0.

Parameters:
buf an array of elements
n the number of elements in the array

The operation is effectively a wipe or zeroization. The operation attempts to survive optimizations and dead code removal

Definition at line 1047 of file misc.h.

References SecureWipeBuffer().

Referenced by FixedSizeAllocatorWithCleanup< unsigned int, S >::deallocate(), AllocatorWithCleanup< word32 >::deallocate(), and FixedSizeAllocatorWithCleanup< unsigned int, S >::reallocate().

void* AlignedAllocate ( size_t  size  ) 

Allocates a buffer on 16-byte boundary.

Parameters:
size the size of the buffer

AlignedAllocate is primarily used when the data will be proccessed by MMX and SSE2 instructions. The assembly language routines rely on the alignment. If the alignment is not respected, then a SIGBUS is generated under Unix and an EXCEPTION_DATATYPE_MISALIGNMENT is generated under Windows.

Note:
AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h

Referenced by AllocatorWithCleanup< word32 >::allocate().

void AlignedDeallocate ( void *  ptr  ) 

Frees a buffer allocated with AlignedAllocate.

Parameters:
ptr the buffer to free
Note:
AlignedAllocate and AlignedDeallocate are available when CRYPTOPP_BOOL_ALIGN16 is defined. CRYPTOPP_BOOL_ALIGN16 is defined in config.h

Referenced by AllocatorWithCleanup< word32 >::deallocate().

void* UnalignedAllocate ( size_t  size  ) 

Allocates a buffer.

Parameters:
size the size of the buffer

Definition at line 195 of file misc.cpp.

void UnalignedDeallocate ( void *  ptr  ) 

Frees a buffer allocated with UnalignedAllocate.

Parameters:
ptr the buffer to free

Definition at line 203 of file misc.cpp.

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

Performs a left rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1175 of file misc.h.

Referenced by BitReverse(), ByteReverse(), and SAFER::Base::UncheckedSetKey().

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

Performs a right rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1198 of file misc.h.

Referenced by ByteReverse().

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

Performs a left rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1219 of file misc.h.

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

Performs a right rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1236 of file misc.h.

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

Performs a left rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1250 of file misc.h.

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

Performs a right rotate.

Parameters:
x the value to rotate
y the 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.

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.

Definition at line 1263 of file misc.h.

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

Gets a byte from a value.

Parameters:
order the ByteOrder of the value
value the value to retrieve the byte
index the location of the byte to retrieve

Definition at line 1549 of file misc.h.

byte ByteReverse ( byte  value  )  [inline]

Reverses bytes in a 8-bit value.

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

Definition at line 1560 of file misc.h.

Referenced by BitReverse(), ByteReverse(), ConditionalByteReverse(), and MersenneTwister< K, M, N, F, S >::GenerateBlock().

word16 ByteReverse ( word16  value  )  [inline]

Reverses bytes in a 16-bit value.

Performs an endian reversal

Parameters:
value the 16-bit value to reverse

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

Definition at line 1569 of file misc.h.

References rotlFixed().

word32 ByteReverse ( word32  value  )  [inline]

Reverses bytes in a 32-bit value.

Performs an endian reversal

Parameters:
value the 32-bit value to reverse

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

Definition at line 1584 of file misc.h.

References rotlFixed(), and rotrFixed().

word64 ByteReverse ( word64  value  )  [inline]

Reverses bytes in a 64-bit value.

Performs an endian reversal

Parameters:
value the 64-bit value to reverse

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

Definition at line 1609 of file misc.h.

References ByteReverse(), and rotlFixed().

byte BitReverse ( byte  value  )  [inline]

Reverses bits in a 8-bit value.

Parameters:
value the 8-bit value to reverse

BitReverse performs a combination of shifts on the byte

Definition at line 1630 of file misc.h.

References rotlFixed().

Referenced by BitReverse(), and HuffmanEncoder::Initialize().

word16 BitReverse ( word16  value  )  [inline]

Reverses bits in a 16-bit value.

Parameters:
value the 16-bit value to reverse

BitReverse performs a combination of shifts on the word16

Definition at line 1640 of file misc.h.

References ByteReverse().

word32 BitReverse ( word32  value  )  [inline]

Reverses bits in a 32-bit value.

Parameters:
value the 32-bit value to reverse

BitReverse performs a combination of shifts on the word32

Definition at line 1651 of file misc.h.

References ByteReverse().

word64 BitReverse ( word64  value  )  [inline]

Reverses bits in a 64-bit value.

Parameters:
value the 64-bit value to reverse

BitReverse performs a combination of shifts on the word64

Definition at line 1662 of file misc.h.

References BitReverse(), and ByteReverse().

template<class T >
T BitReverse ( value  )  [inline]

Reverses bits in a value.

Parameters:
value the 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.

Definition at line 1681 of file misc.h.

References BitReverse().

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

Reverses bytes in a value depending upon endianess.

Template Parameters:
T the class or type
Parameters:
order the ByteOrder the data is represented
value the 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 1704 of file misc.h.

References ByteReverse(), and NativeByteOrderIs().

Referenced by VMAC_Base::TruncatedFinal().

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

Reverses bytes in an element among an array of elements.

Template Parameters:
T the class or type
Parameters:
out the output array of elements
in the input array of elements
byteCount the byte count of the arrays

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 8 bytes are reversed.

Note:
ByteReverse uses the number of bytes in the arrays, and not the count of elements in the arrays.

Definition at line 1722 of file misc.h.

References ByteReverse().

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

Reverses bytes in an element among an array of elements depending upon endianess.

Template Parameters:
T the class or type
Parameters:
order the ByteOrder the data is represented
out the output array of elements
in the input array of elements
byteCount the byte count of the arrays

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 8 bytes are reversed.

Note:
ByteReverse uses the number of bytes in the arrays, and not the count of elements in the arrays.

Definition at line 1744 of file misc.h.

References ByteReverse(), memcpy_s(), and NativeByteOrderIs().


Generated on 24 Mar 2016 for Crypto++ by  doxygen 1.6.1