Change Doxygen comment style from //! to ///

Also see https://groups.google.com/forum/#!topic/cryptopp-users/A7-Xt5Knlzw
pull/548/head
Jeffrey Walton 2017-11-29 10:54:33 -05:00
parent 16ebfa72bf
commit 61ec50dabe
No known key found for this signature in database
GPG Key ID: B36AB348921B1838
151 changed files with 11089 additions and 11091 deletions

32
3way.h
View File

@ -1,7 +1,7 @@
// 3way.h - originally written and placed in the public domain by Wei Dai // 3way.h - originally written and placed in the public domain by Wei Dai
//! \file 3way.h /// \file 3way.h
//! \brief Classes for the 3-Way block cipher /// \brief Classes for the 3-Way block cipher
#ifndef CRYPTOPP_THREEWAY_H #ifndef CRYPTOPP_THREEWAY_H
#define CRYPTOPP_THREEWAY_H #define CRYPTOPP_THREEWAY_H
@ -12,21 +12,21 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ThreeWay_Info /// \class ThreeWay_Info
//! \brief ThreeWay block cipher information /// \brief ThreeWay block cipher information
struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, public VariableRounds<11> struct ThreeWay_Info : public FixedBlockSize<12>, public FixedKeyLength<12>, public VariableRounds<11>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "3-Way";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "3-Way";}
}; };
//! \class ThreeWay /// \class ThreeWay
//! \brief ThreeWay block cipher /// \brief ThreeWay block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/3-Way">3-Way</a> /// \sa <a href="http://www.cryptopp.com/wiki/3-Way">3-Way</a>
class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief Class specific implementation and overrides used to operate the cipher. /// \brief Class specific implementation and overrides used to operate the cipher.
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions /// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<ThreeWay_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<ThreeWay_Info>
{ {
public: public:
@ -37,18 +37,18 @@ class ThreeWay : public ThreeWay_Info, public BlockCipherDocumentation
FixedSizeSecBlock<word32, 3> m_k; FixedSizeSecBlock<word32, 3> m_k;
}; };
//! \class Enc /// \class Enc
//! \brief Class specific methods used to operate the cipher in the forward direction. /// \brief Class specific methods used to operate the cipher in the forward direction.
//! \details Implementations and overrides in \p Enc apply to \p ENCRYPTION. /// \details Implementations and overrides in \p Enc apply to \p ENCRYPTION.
class CRYPTOPP_NO_VTABLE Enc : public Base class CRYPTOPP_NO_VTABLE Enc : public Base
{ {
public: public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
}; };
//! \class Dec /// \class Dec
//! \brief Class specific methods used to operate the cipher in the reverse direction. /// \brief Class specific methods used to operate the cipher in the reverse direction.
//! \details Implementations and overrides in \p Dec apply to \p DECRYPTION. /// \details Implementations and overrides in \p Dec apply to \p DECRYPTION.
class CRYPTOPP_NO_VTABLE Dec : public Base class CRYPTOPP_NO_VTABLE Dec : public Base
{ {
public: public:

View File

@ -1,8 +1,8 @@
// adler32.h - originally written and placed in the public domain by Wei Dai // adler32.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile adler32.h /// \headerfile adler32.h
//! \brief Class file for ADLER-32 checksum calculations /// \brief Class file for ADLER-32 checksum calculations
#ifndef CRYPTOPP_ADLER32_H #ifndef CRYPTOPP_ADLER32_H
#define CRYPTOPP_ADLER32_H #define CRYPTOPP_ADLER32_H
@ -11,7 +11,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! ADLER-32 checksum calculations /// ADLER-32 checksum calculations
class Adler32 : public HashTransformation class Adler32 : public HashTransformation
{ {
public: public:

22
aes.h
View File

@ -1,10 +1,10 @@
// aes.h - originally written and placed in the public domain by Wei Dai // aes.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \brief Class file for the AES cipher (Rijndael) /// \brief Class file for the AES cipher (Rijndael)
//! \details AES is a typdef for Rijndael classes. All key sizes are supported. /// \details AES is a typdef for Rijndael classes. All key sizes are supported.
//! The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks /// The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks
//! \since Rijndael since Crypto++ 3.2, Intel AESNI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0 /// \since Rijndael since Crypto++ 3.2, Intel AESNI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0
#ifndef CRYPTOPP_AES_H #ifndef CRYPTOPP_AES_H
#define CRYPTOPP_AES_H #define CRYPTOPP_AES_H
@ -13,12 +13,12 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class AES /// \class AES
//! \brief AES block cipher (Rijndael) /// \brief AES block cipher (Rijndael)
//! \details AES is a typdef for Rijndael classes. All key sizes are supported. /// \details AES is a typdef for Rijndael classes. All key sizes are supported.
//! The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks /// The library only provides Rijndael with 128-bit blocks, and not 192-bit or 256-bit blocks
//! \sa <a href="http://www.cryptolounge.org/wiki/AES">AES</a> winner, announced on 10/2/2000 /// \sa <a href="http://www.cryptolounge.org/wiki/AES">AES</a> winner, announced on 10/2/2000
//! \since Rijndael since Crypto++ 3.2, Intel AESNI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0 /// \since Rijndael since Crypto++ 3.2, Intel AESNI since Crypto++ 5.6.1, ARMv8 AES since Crypto++ 6.0
DOCUMENTED_TYPEDEF(Rijndael, AES) DOCUMENTED_TYPEDEF(Rijndael, AES)
typedef RijndaelEncryption AESEncryption; typedef RijndaelEncryption AESEncryption;

318
algebra.h
View File

@ -1,7 +1,7 @@
// algebra.h - originally written and placed in the public domain by Wei Dai // algebra.h - originally written and placed in the public domain by Wei Dai
//! \file algebra.h /// \file algebra.h
//! \brief Classes for performing mathematics over different fields /// \brief Classes for performing mathematics over different fields
#ifndef CRYPTOPP_ALGEBRA_H #ifndef CRYPTOPP_ALGEBRA_H
#define CRYPTOPP_ALGEBRA_H #define CRYPTOPP_ALGEBRA_H
@ -14,15 +14,15 @@ NAMESPACE_BEGIN(CryptoPP)
class Integer; class Integer;
//! \brief Abstract group /// \brief Abstract group
//! \tparam T element class or type /// \tparam T element class or type
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
template <class T> class CRYPTOPP_NO_VTABLE AbstractGroup template <class T> class CRYPTOPP_NO_VTABLE AbstractGroup
{ {
public: public:
@ -30,167 +30,167 @@ public:
virtual ~AbstractGroup() {} virtual ~AbstractGroup() {}
//! \brief Compare two elements for equality /// \brief Compare two elements for equality
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns true if the elements are equal, false otherwise /// \returns true if the elements are equal, false otherwise
//! \details Equal() tests the elements for equality using <tt>a==b</tt> /// \details Equal() tests the elements for equality using <tt>a==b</tt>
virtual bool Equal(const Element &a, const Element &b) const =0; virtual bool Equal(const Element &a, const Element &b) const =0;
//! \brief Provides the Identity element /// \brief Provides the Identity element
//! \returns the Identity element /// \returns the Identity element
virtual const Element& Identity() const =0; virtual const Element& Identity() const =0;
//! \brief Adds elements in the group /// \brief Adds elements in the group
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns the sum of <tt>a</tt> and <tt>b</tt> /// \returns the sum of <tt>a</tt> and <tt>b</tt>
virtual const Element& Add(const Element &a, const Element &b) const =0; virtual const Element& Add(const Element &a, const Element &b) const =0;
//! \brief Inverts the element in the group /// \brief Inverts the element in the group
//! \param a first element /// \param a first element
//! \returns the inverse of the element /// \returns the inverse of the element
virtual const Element& Inverse(const Element &a) const =0; virtual const Element& Inverse(const Element &a) const =0;
//! \brief Determine if inversion is fast /// \brief Determine if inversion is fast
//! \returns true if inversion is fast, false otherwise /// \returns true if inversion is fast, false otherwise
virtual bool InversionIsFast() const {return false;} virtual bool InversionIsFast() const {return false;}
//! \brief Doubles an element in the group /// \brief Doubles an element in the group
//! \param a the element /// \param a the element
//! \returns the element doubled /// \returns the element doubled
virtual const Element& Double(const Element &a) const; virtual const Element& Double(const Element &a) const;
//! \brief Subtracts elements in the group /// \brief Subtracts elements in the group
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function. /// \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function.
virtual const Element& Subtract(const Element &a, const Element &b) const; virtual const Element& Subtract(const Element &a, const Element &b) const;
//! \brief TODO /// \brief TODO
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns TODO /// \returns TODO
virtual Element& Accumulate(Element &a, const Element &b) const; virtual Element& Accumulate(Element &a, const Element &b) const;
//! \brief Reduces an element in the congruence class /// \brief Reduces an element in the congruence class
//! \param a element to reduce /// \param a element to reduce
//! \param b the congruence class /// \param b the congruence class
//! \returns the reduced element /// \returns the reduced element
virtual Element& Reduce(Element &a, const Element &b) const; virtual Element& Reduce(Element &a, const Element &b) const;
//! \brief Performs a scalar multiplication /// \brief Performs a scalar multiplication
//! \param a multiplicand /// \param a multiplicand
//! \param e multiplier /// \param e multiplier
//! \returns the product /// \returns the product
virtual Element ScalarMultiply(const Element &a, const Integer &e) const; virtual Element ScalarMultiply(const Element &a, const Integer &e) const;
//! \brief TODO /// \brief TODO
//! \param x first multiplicand /// \param x first multiplicand
//! \param e1 the first multiplier /// \param e1 the first multiplier
//! \param y second multiplicand /// \param y second multiplicand
//! \param e2 the second multiplier /// \param e2 the second multiplier
//! \returns TODO /// \returns TODO
virtual Element CascadeScalarMultiply(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const; virtual Element CascadeScalarMultiply(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const;
//! \brief Multiplies a base to multiple exponents in a group /// \brief Multiplies a base to multiple exponents in a group
//! \param results an array of Elements /// \param results an array of Elements
//! \param base the base to raise to the exponents /// \param base the base to raise to the exponents
//! \param exponents an array of exponents /// \param exponents an array of exponents
//! \param exponentsCount the number of exponents in the array /// \param exponentsCount the number of exponents in the array
//! \details SimultaneousMultiply() multiplies the base to each exponent in the exponents array and stores the /// \details SimultaneousMultiply() multiplies the base to each exponent in the exponents array and stores the
//! result at the respective position in the results array. /// result at the respective position in the results array.
//! \details SimultaneousMultiply() must be implemented in a derived class. /// \details SimultaneousMultiply() must be implemented in a derived class.
//! \pre <tt>COUNTOF(results) == exponentsCount</tt> /// \pre <tt>COUNTOF(results) == exponentsCount</tt>
//! \pre <tt>COUNTOF(exponents) == exponentsCount</tt> /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
virtual void SimultaneousMultiply(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const; virtual void SimultaneousMultiply(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
}; };
//! \brief Abstract ring /// \brief Abstract ring
//! \tparam T element class or type /// \tparam T element class or type
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
template <class T> class CRYPTOPP_NO_VTABLE AbstractRing : public AbstractGroup<T> template <class T> class CRYPTOPP_NO_VTABLE AbstractRing : public AbstractGroup<T>
{ {
public: public:
typedef T Element; typedef T Element;
//! \brief Construct an AbstractRing /// \brief Construct an AbstractRing
AbstractRing() {m_mg.m_pRing = this;} AbstractRing() {m_mg.m_pRing = this;}
//! \brief Copy construct an AbstractRing /// \brief Copy construct an AbstractRing
//! \param source other AbstractRing /// \param source other AbstractRing
AbstractRing(const AbstractRing &source) AbstractRing(const AbstractRing &source)
{CRYPTOPP_UNUSED(source); m_mg.m_pRing = this;} {CRYPTOPP_UNUSED(source); m_mg.m_pRing = this;}
//! \brief Assign an AbstractRing /// \brief Assign an AbstractRing
//! \param source other AbstractRing /// \param source other AbstractRing
AbstractRing& operator=(const AbstractRing &source) AbstractRing& operator=(const AbstractRing &source)
{CRYPTOPP_UNUSED(source); return *this;} {CRYPTOPP_UNUSED(source); return *this;}
//! \brief Determines whether an element is a unit in the group /// \brief Determines whether an element is a unit in the group
//! \param a the element /// \param a the element
//! \returns true if the element is a unit after reduction, false otherwise. /// \returns true if the element is a unit after reduction, false otherwise.
virtual bool IsUnit(const Element &a) const =0; virtual bool IsUnit(const Element &a) const =0;
//! \brief Retrieves the multiplicative identity /// \brief Retrieves the multiplicative identity
//! \returns the multiplicative identity /// \returns the multiplicative identity
virtual const Element& MultiplicativeIdentity() const =0; virtual const Element& MultiplicativeIdentity() const =0;
//! \brief Multiplies elements in the group /// \brief Multiplies elements in the group
//! \param a the multiplicand /// \param a the multiplicand
//! \param b the multiplier /// \param b the multiplier
//! \returns the product of a and b /// \returns the product of a and b
virtual const Element& Multiply(const Element &a, const Element &b) const =0; virtual const Element& Multiply(const Element &a, const Element &b) const =0;
//! \brief Calculate the multiplicative inverse of an element in the group /// \brief Calculate the multiplicative inverse of an element in the group
//! \param a the element /// \param a the element
virtual const Element& MultiplicativeInverse(const Element &a) const =0; virtual const Element& MultiplicativeInverse(const Element &a) const =0;
//! \brief Square an element in the group /// \brief Square an element in the group
//! \param a the element /// \param a the element
//! \returns the element squared /// \returns the element squared
virtual const Element& Square(const Element &a) const; virtual const Element& Square(const Element &a) const;
//! \brief Divides elements in the group /// \brief Divides elements in the group
//! \param a the dividend /// \param a the dividend
//! \param b the divisor /// \param b the divisor
//! \returns the quotient /// \returns the quotient
virtual const Element& Divide(const Element &a, const Element &b) const; virtual const Element& Divide(const Element &a, const Element &b) const;
//! \brief Raises a base to an exponent in the group /// \brief Raises a base to an exponent in the group
//! \param a the base /// \param a the base
//! \param e the exponent /// \param e the exponent
//! \returns the exponentiation /// \returns the exponentiation
virtual Element Exponentiate(const Element &a, const Integer &e) const; virtual Element Exponentiate(const Element &a, const Integer &e) const;
//! \brief TODO /// \brief TODO
//! \param x first element /// \param x first element
//! \param e1 first exponent /// \param e1 first exponent
//! \param y second element /// \param y second element
//! \param e2 second exponent /// \param e2 second exponent
//! \returns TODO /// \returns TODO
virtual Element CascadeExponentiate(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const; virtual Element CascadeExponentiate(const Element &x, const Integer &e1, const Element &y, const Integer &e2) const;
//! \brief Exponentiates a base to multiple exponents in the Ring /// \brief Exponentiates a base to multiple exponents in the Ring
//! \param results an array of Elements /// \param results an array of Elements
//! \param base the base to raise to the exponents /// \param base the base to raise to the exponents
//! \param exponents an array of exponents /// \param exponents an array of exponents
//! \param exponentsCount the number of exponents in the array /// \param exponentsCount the number of exponents in the array
//! \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the /// \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the
//! result at the respective position in the results array. /// result at the respective position in the results array.
//! \details SimultaneousExponentiate() must be implemented in a derived class. /// \details SimultaneousExponentiate() must be implemented in a derived class.
//! \pre <tt>COUNTOF(results) == exponentsCount</tt> /// \pre <tt>COUNTOF(results) == exponentsCount</tt>
//! \pre <tt>COUNTOF(exponents) == exponentsCount</tt> /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const; virtual void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
//! \brief Retrieves the multiplicative group /// \brief Retrieves the multiplicative group
//! \returns the multiplicative group /// \returns the multiplicative group
virtual const AbstractGroup<T>& MultiplicativeGroup() const virtual const AbstractGroup<T>& MultiplicativeGroup() const
{return m_mg;} {return m_mg;}
@ -242,9 +242,9 @@ private:
// ******************************************************** // ********************************************************
//! \brief Base and exponent /// \brief Base and exponent
//! \tparam T base class or type /// \tparam T base class or type
//! \tparam E exponent class or type /// \tparam E exponent class or type
template <class T, class E = Integer> template <class T, class E = Integer>
struct BaseAndExponent struct BaseAndExponent
{ {
@ -264,37 +264,37 @@ template <class Element, class Iterator>
// ******************************************************** // ********************************************************
//! \brief Abstract Euclidean domain /// \brief Abstract Euclidean domain
//! \tparam T element class or type /// \tparam T element class or type
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
template <class T> class CRYPTOPP_NO_VTABLE AbstractEuclideanDomain : public AbstractRing<T> template <class T> class CRYPTOPP_NO_VTABLE AbstractEuclideanDomain : public AbstractRing<T>
{ {
public: public:
typedef T Element; typedef T Element;
//! \brief Performs the division algorithm on two elements in the ring /// \brief Performs the division algorithm on two elements in the ring
//! \param r the remainder /// \param r the remainder
//! \param q the quotient /// \param q the quotient
//! \param a the dividend /// \param a the dividend
//! \param d the divisor /// \param d the divisor
virtual void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const =0; virtual void DivisionAlgorithm(Element &r, Element &q, const Element &a, const Element &d) const =0;
//! \brief Performs a modular reduction in the ring /// \brief Performs a modular reduction in the ring
//! \param a the element /// \param a the element
//! \param b the modulus /// \param b the modulus
//! \returns the result of <tt>a%b</tt>. /// \returns the result of <tt>a%b</tt>.
virtual const Element& Mod(const Element &a, const Element &b) const =0; virtual const Element& Mod(const Element &a, const Element &b) const =0;
//! \brief Calculates the greatest common denominator in the ring /// \brief Calculates the greatest common denominator in the ring
//! \param a the first element /// \param a the first element
//! \param b the second element /// \param b the second element
//! \returns the the greatest common denominator of a and b. /// \returns the the greatest common denominator of a and b.
virtual const Element& Gcd(const Element &a, const Element &b) const; virtual const Element& Gcd(const Element &a, const Element &b) const;
protected: protected:
@ -303,15 +303,15 @@ protected:
// ******************************************************** // ********************************************************
//! \brief Euclidean domain /// \brief Euclidean domain
//! \tparam T element class or type /// \tparam T element class or type
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
template <class T> class EuclideanDomainOf : public AbstractEuclideanDomain<T> template <class T> class EuclideanDomainOf : public AbstractEuclideanDomain<T>
{ {
public: public:
@ -374,15 +374,15 @@ private:
mutable Element result; mutable Element result;
}; };
//! \brief Quotient ring /// \brief Quotient ring
//! \tparam T element class or type /// \tparam T element class or type
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
template <class T> class QuotientRing : public AbstractRing<typename T::Element> template <class T> class QuotientRing : public AbstractRing<typename T::Element>
{ {
public: public:

View File

@ -1,8 +1,8 @@
// algparam.h - originally written and placed in the public domain by Wei Dai // algparam.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile algparam.h /// \headerfile algparam.h
//! \brief Classes for working with NameValuePairs /// \brief Classes for working with NameValuePairs
#ifndef CRYPTOPP_ALGPARAM_H #ifndef CRYPTOPP_ALGPARAM_H
@ -26,40 +26,40 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ConstByteArrayParameter /// \class ConstByteArrayParameter
//! \brief Used to pass byte array input as part of a NameValuePairs object /// \brief Used to pass byte array input as part of a NameValuePairs object
class ConstByteArrayParameter class ConstByteArrayParameter
{ {
public: public:
//! \brief Construct a ConstByteArrayParameter /// \brief Construct a ConstByteArrayParameter
//! \param data a C-String /// \param data a C-String
//! \param deepCopy flag indicating whether the data should be copied /// \param deepCopy flag indicating whether the data should be copied
//! \details The deepCopy option is used when the NameValuePairs object can't /// \details The deepCopy option is used when the NameValuePairs object can't
//! keep a copy of the data available /// keep a copy of the data available
ConstByteArrayParameter(const char *data = NULLPTR, bool deepCopy = false) ConstByteArrayParameter(const char *data = NULLPTR, bool deepCopy = false)
: m_deepCopy(false), m_data(NULLPTR), m_size(0) : m_deepCopy(false), m_data(NULLPTR), m_size(0)
{ {
Assign((const byte *)data, data ? strlen(data) : 0, deepCopy); Assign((const byte *)data, data ? strlen(data) : 0, deepCopy);
} }
//! \brief Construct a ConstByteArrayParameter /// \brief Construct a ConstByteArrayParameter
//! \param data a memory buffer /// \param data a memory buffer
//! \param size the length of the memory buffer /// \param size the length of the memory buffer
//! \param deepCopy flag indicating whether the data should be copied /// \param deepCopy flag indicating whether the data should be copied
//! \details The deepCopy option is used when the NameValuePairs object can't /// \details The deepCopy option is used when the NameValuePairs object can't
//! keep a copy of the data available /// keep a copy of the data available
ConstByteArrayParameter(const byte *data, size_t size, bool deepCopy = false) ConstByteArrayParameter(const byte *data, size_t size, bool deepCopy = false)
: m_deepCopy(false), m_data(NULLPTR), m_size(0) : m_deepCopy(false), m_data(NULLPTR), m_size(0)
{ {
Assign(data, size, deepCopy); Assign(data, size, deepCopy);
} }
//! \brief Construct a ConstByteArrayParameter /// \brief Construct a ConstByteArrayParameter
//! \tparam T a std::basic_string<char> class /// \tparam T a std::basic_string<char> class
//! \param string a std::basic_string<char> class /// \param string a std::basic_string<char> class
//! \param deepCopy flag indicating whether the data should be copied /// \param deepCopy flag indicating whether the data should be copied
//! \details The deepCopy option is used when the NameValuePairs object can't /// \details The deepCopy option is used when the NameValuePairs object can't
//! keep a copy of the data available /// keep a copy of the data available
template <class T> ConstByteArrayParameter(const T &string, bool deepCopy = false) template <class T> ConstByteArrayParameter(const T &string, bool deepCopy = false)
: m_deepCopy(false), m_data(NULLPTR), m_size(0) : m_deepCopy(false), m_data(NULLPTR), m_size(0)
{ {
@ -67,12 +67,12 @@ public:
Assign((const byte *)string.data(), string.size(), deepCopy); Assign((const byte *)string.data(), string.size(), deepCopy);
} }
//! \brief Assign contents from a memory buffer /// \brief Assign contents from a memory buffer
//! \param data a memory buffer /// \param data a memory buffer
//! \param size the length of the memory buffer /// \param size the length of the memory buffer
//! \param deepCopy flag indicating whether the data should be copied /// \param deepCopy flag indicating whether the data should be copied
//! \details The deepCopy option is used when the NameValuePairs object can't /// \details The deepCopy option is used when the NameValuePairs object can't
//! keep a copy of the data available /// keep a copy of the data available
void Assign(const byte *data, size_t size, bool deepCopy) void Assign(const byte *data, size_t size, bool deepCopy)
{ {
// This fires, which means: no data with a size, or data with no size. // This fires, which means: no data with a size, or data with no size.
@ -87,11 +87,11 @@ public:
m_deepCopy = deepCopy; m_deepCopy = deepCopy;
} }
//! \brief Pointer to the first byte in the memory block /// \brief Pointer to the first byte in the memory block
const byte *begin() const {return m_deepCopy ? m_block.begin() : m_data;} const byte *begin() const {return m_deepCopy ? m_block.begin() : m_data;}
//! \brief Pointer beyond the last byte in the memory block /// \brief Pointer beyond the last byte in the memory block
const byte *end() const {return m_deepCopy ? m_block.end() : m_data + m_size;} const byte *end() const {return m_deepCopy ? m_block.end() : m_data + m_size;}
//! \brief Length of the memory block /// \brief Length of the memory block
size_t size() const {return m_deepCopy ? m_block.size() : m_size;} size_t size() const {return m_deepCopy ? m_block.size() : m_size;}
private: private:
@ -101,27 +101,27 @@ private:
SecByteBlock m_block; SecByteBlock m_block;
}; };
//! \class ByteArrayParameter /// \class ByteArrayParameter
//! \brief Used to pass byte array input as part of a NameValuePairs object /// \brief Used to pass byte array input as part of a NameValuePairs object
class ByteArrayParameter class ByteArrayParameter
{ {
public: public:
//! \brief Construct a ByteArrayParameter /// \brief Construct a ByteArrayParameter
//! \param data a memory buffer /// \param data a memory buffer
//! \param size the length of the memory buffer /// \param size the length of the memory buffer
ByteArrayParameter(byte *data = NULLPTR, unsigned int size = 0) ByteArrayParameter(byte *data = NULLPTR, unsigned int size = 0)
: m_data(data), m_size(size) {} : m_data(data), m_size(size) {}
//! \brief Construct a ByteArrayParameter /// \brief Construct a ByteArrayParameter
//! \param block a SecByteBlock /// \param block a SecByteBlock
ByteArrayParameter(SecByteBlock &block) ByteArrayParameter(SecByteBlock &block)
: m_data(block.begin()), m_size(block.size()) {} : m_data(block.begin()), m_size(block.size()) {}
//! \brief Pointer to the first byte in the memory block /// \brief Pointer to the first byte in the memory block
byte *begin() const {return m_data;} byte *begin() const {return m_data;}
//! \brief Pointer beyond the last byte in the memory block /// \brief Pointer beyond the last byte in the memory block
byte *end() const {return m_data + m_size;} byte *end() const {return m_data + m_size;}
//! \brief Length of the memory block /// \brief Length of the memory block
size_t size() const {return m_size;} size_t size() const {return m_size;}
private: private:
@ -129,17 +129,17 @@ private:
size_t m_size; size_t m_size;
}; };
//! \class CombinedNameValuePairs /// \class CombinedNameValuePairs
//! \brief Combines two sets of NameValuePairs /// \brief Combines two sets of NameValuePairs
//! \details CombinedNameValuePairs allows you to provide two sets of of NameValuePairs. /// \details CombinedNameValuePairs allows you to provide two sets of of NameValuePairs.
//! If a name is not found in the first set, then the second set is searched for the /// If a name is not found in the first set, then the second set is searched for the
//! name and value pair. The second set of NameValuePairs often provides default values. /// name and value pair. The second set of NameValuePairs often provides default values.
class CRYPTOPP_DLL CombinedNameValuePairs : public NameValuePairs class CRYPTOPP_DLL CombinedNameValuePairs : public NameValuePairs
{ {
public: public:
//! \brief Construct a CombinedNameValuePairs /// \brief Construct a CombinedNameValuePairs
//! \param pairs1 reference to the first set of NameValuePairs /// \param pairs1 reference to the first set of NameValuePairs
//! \param pairs2 reference to the second set of NameValuePairs /// \param pairs2 reference to the second set of NameValuePairs
CombinedNameValuePairs(const NameValuePairs &pairs1, const NameValuePairs &pairs2) CombinedNameValuePairs(const NameValuePairs &pairs1, const NameValuePairs &pairs2)
: m_pairs1(pairs1), m_pairs2(pairs2) {} : m_pairs1(pairs1), m_pairs2(pairs2) {}
@ -308,13 +308,13 @@ CRYPTOPP_DLL bool AssignIntToInteger(const std::type_info &valueType, void *pInt
CRYPTOPP_DLL const std::type_info & CRYPTOPP_API IntegerTypeId(); CRYPTOPP_DLL const std::type_info & CRYPTOPP_API IntegerTypeId();
//! \class AlgorithmParametersBase /// \class AlgorithmParametersBase
//! \brief Base class for AlgorithmParameters /// \brief Base class for AlgorithmParameters
class CRYPTOPP_DLL AlgorithmParametersBase class CRYPTOPP_DLL AlgorithmParametersBase
{ {
public: public:
//! \class ParameterNotUsed /// \class ParameterNotUsed
//! \brief Exception thrown when an AlgorithmParameter is unused /// \brief Exception thrown when an AlgorithmParameter is unused
class ParameterNotUsed : public Exception class ParameterNotUsed : public Exception
{ {
public: public:
@ -347,11 +347,11 @@ public:
x.m_used = true; x.m_used = true;
} }
//! \brief Construct a AlgorithmParametersBase /// \brief Construct a AlgorithmParametersBase
//! \param name the parameter name /// \param name the parameter name
//! \param throwIfNotUsed flags indicating whether an exception should be thrown /// \param throwIfNotUsed flags indicating whether an exception should be thrown
//! \details If throwIfNotUsed is true, then a ParameterNotUsed exception /// \details If throwIfNotUsed is true, then a ParameterNotUsed exception
//! will be thrown in the destructor if the parameter is not not retrieved. /// will be thrown in the destructor if the parameter is not not retrieved.
AlgorithmParametersBase(const char *name, bool throwIfNotUsed) AlgorithmParametersBase(const char *name, bool throwIfNotUsed)
: m_name(name), m_throwIfNotUsed(throwIfNotUsed), m_used(false) {} : m_name(name), m_throwIfNotUsed(throwIfNotUsed), m_used(false) {}
@ -370,19 +370,19 @@ protected:
member_ptr<AlgorithmParametersBase> m_next; member_ptr<AlgorithmParametersBase> m_next;
}; };
//! \class AlgorithmParametersTemplate /// \class AlgorithmParametersTemplate
//! \brief Template base class for AlgorithmParameters /// \brief Template base class for AlgorithmParameters
//! \tparam T the class or type /// \tparam T the class or type
template <class T> template <class T>
class AlgorithmParametersTemplate : public AlgorithmParametersBase class AlgorithmParametersTemplate : public AlgorithmParametersBase
{ {
public: public:
//! \brief Construct an AlgorithmParametersTemplate /// \brief Construct an AlgorithmParametersTemplate
//! \param name the name of the value /// \param name the name of the value
//! \param value a reference to the value /// \param value a reference to the value
//! \param throwIfNotUsed flags indicating whether an exception should be thrown /// \param throwIfNotUsed flags indicating whether an exception should be thrown
//! \details If throwIfNotUsed is true, then a ParameterNotUsed exception /// \details If throwIfNotUsed is true, then a ParameterNotUsed exception
//! will be thrown in the destructor if the parameter is not not retrieved. /// will be thrown in the destructor if the parameter is not not retrieved.
AlgorithmParametersTemplate(const char *name, const T &value, bool throwIfNotUsed) AlgorithmParametersTemplate(const char *name, const T &value, bool throwIfNotUsed)
: AlgorithmParametersBase(name, throwIfNotUsed), m_value(value) : AlgorithmParametersBase(name, throwIfNotUsed), m_value(value)
{ {
@ -423,37 +423,37 @@ CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<bool>;
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<int>; CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<int>;
CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<ConstByteArrayParameter>; CRYPTOPP_DLL_TEMPLATE_CLASS AlgorithmParametersTemplate<ConstByteArrayParameter>;
//! \class AlgorithmParameters /// \class AlgorithmParameters
//! \brief An object that implements NameValuePairs /// \brief An object that implements NameValuePairs
//! \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by /// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
//! repeatedly using operator() on the object returned by MakeParameters, for example: /// repeatedly using operator() on the object returned by MakeParameters, for example:
//! <pre> /// <pre>
//! AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3); /// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
//! </pre> /// </pre>
class CRYPTOPP_DLL AlgorithmParameters : public NameValuePairs class CRYPTOPP_DLL AlgorithmParameters : public NameValuePairs
{ {
public: public:
//! \brief Construct a AlgorithmParameters /// \brief Construct a AlgorithmParameters
//! \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by /// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
//! repeatedly using operator() on the object returned by MakeParameters, for example: /// repeatedly using operator() on the object returned by MakeParameters, for example:
//! <pre> /// <pre>
//! AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3); /// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
//! </pre> /// </pre>
AlgorithmParameters(); AlgorithmParameters();
#ifdef __BORLANDC__ #ifdef __BORLANDC__
//! \brief Construct a AlgorithmParameters /// \brief Construct a AlgorithmParameters
//! \tparam T the class or type /// \tparam T the class or type
//! \param name the name of the object or value to retrieve /// \param name the name of the object or value to retrieve
//! \param value reference to a variable that receives the value /// \param value reference to a variable that receives the value
//! \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed /// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
//! \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(), /// \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(),
//! such as MSVC 7.0 and earlier. /// such as MSVC 7.0 and earlier.
//! \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by /// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
//! repeatedly using operator() on the object returned by MakeParameters, for example: /// repeatedly using operator() on the object returned by MakeParameters, for example:
//! <pre> /// <pre>
//! AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3); /// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
//! </pre> /// </pre>
template <class T> template <class T>
AlgorithmParameters(const char *name, const T &value, bool throwIfNotUsed=true) AlgorithmParameters(const char *name, const T &value, bool throwIfNotUsed=true)
: m_next(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed)) : m_next(new AlgorithmParametersTemplate<T>(name, value, throwIfNotUsed))
@ -466,10 +466,10 @@ public:
AlgorithmParameters & operator=(const AlgorithmParameters &x); AlgorithmParameters & operator=(const AlgorithmParameters &x);
//! \tparam T the class or type /// \tparam T the class or type
//! \param name the name of the object or value to retrieve /// \param name the name of the object or value to retrieve
//! \param value reference to a variable that receives the value /// \param value reference to a variable that receives the value
//! \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed /// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
template <class T> template <class T>
AlgorithmParameters & operator()(const char *name, const T &value, bool throwIfNotUsed) AlgorithmParameters & operator()(const char *name, const T &value, bool throwIfNotUsed)
{ {
@ -480,10 +480,10 @@ public:
return *this; return *this;
} }
//! \brief Appends a NameValuePair to a collection of NameValuePairs /// \brief Appends a NameValuePair to a collection of NameValuePairs
//! \tparam T the class or type /// \tparam T the class or type
//! \param name the name of the object or value to retrieve /// \param name the name of the object or value to retrieve
//! \param value reference to a variable that receives the value /// \param value reference to a variable that receives the value
template <class T> template <class T>
AlgorithmParameters & operator()(const char *name, const T &value) AlgorithmParameters & operator()(const char *name, const T &value)
{ {
@ -497,18 +497,18 @@ protected:
bool m_defaultThrowIfNotUsed; bool m_defaultThrowIfNotUsed;
}; };
//! \brief Create an object that implements NameValuePairs /// \brief Create an object that implements NameValuePairs
//! \tparam T the class or type /// \tparam T the class or type
//! \param name the name of the object or value to retrieve /// \param name the name of the object or value to retrieve
//! \param value reference to a variable that receives the value /// \param value reference to a variable that receives the value
//! \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed /// \param throwIfNotUsed if true, the object will throw an exception if the value is not accessed
//! \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(), /// \note throwIfNotUsed is ignored if using a compiler that does not support std::uncaught_exception(),
//! such as MSVC 7.0 and earlier. /// such as MSVC 7.0 and earlier.
//! \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by /// \note A NameValuePairs object containing an arbitrary number of name value pairs may be constructed by
//! repeatedly using \p operator() on the object returned by \p MakeParameters, for example: /// repeatedly using \p operator() on the object returned by \p MakeParameters, for example:
//! <pre> /// <pre>
//! AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3); /// AlgorithmParameters parameters = MakeParameters(name1, value1)(name2, value2)(name3, value3);
//! </pre> /// </pre>
#ifdef __BORLANDC__ #ifdef __BORLANDC__
typedef AlgorithmParameters MakeParameters; typedef AlgorithmParameters MakeParameters;
#else #else

36
arc4.h
View File

@ -1,7 +1,7 @@
// arc4.h - originally written and placed in the public domain by Wei Dai // arc4.h - originally written and placed in the public domain by Wei Dai
//! \file arc4.h /// \file arc4.h
//! \brief Classes for ARC4 cipher /// \brief Classes for ARC4 cipher
#ifndef CRYPTOPP_ARC4_H #ifndef CRYPTOPP_ARC4_H
#define CRYPTOPP_ARC4_H #define CRYPTOPP_ARC4_H
@ -15,10 +15,10 @@ NAMESPACE_BEGIN(CryptoPP)
namespace Weak1 { namespace Weak1 {
//! \class ARC4_Base /// \class ARC4_Base
//! \brief ARC4 base class /// \brief ARC4 base class
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions /// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class CRYPTOPP_NO_VTABLE ARC4_Base : public VariableKeyLength<16, 1, 256>, public RandomNumberGenerator, public SymmetricCipher, public SymmetricCipherDocumentation class CRYPTOPP_NO_VTABLE ARC4_Base : public VariableKeyLength<16, 1, 256>, public RandomNumberGenerator, public SymmetricCipher, public SymmetricCipherDocumentation
{ {
public: public:
@ -46,16 +46,16 @@ protected:
byte m_x, m_y; byte m_x, m_y;
}; };
//! \class ARC4 /// \class ARC4
//! \brief Alleged RC4 /// \brief Alleged RC4
//! \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a> /// \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
DOCUMENTED_TYPEDEF(SymmetricCipherFinal<ARC4_Base>, ARC4) DOCUMENTED_TYPEDEF(SymmetricCipherFinal<ARC4_Base>, ARC4)
//! \class MARC4_Base /// \class MARC4_Base
//! \brief MARC4 base class /// \brief MARC4 base class
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions /// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
//! \details MARC4 discards the first 256 bytes of keystream, which may be weaker than the rest /// \details MARC4 discards the first 256 bytes of keystream, which may be weaker than the rest
class CRYPTOPP_NO_VTABLE MARC4_Base : public ARC4_Base class CRYPTOPP_NO_VTABLE MARC4_Base : public ARC4_Base
{ {
public: public:
@ -68,10 +68,10 @@ protected:
unsigned int GetDefaultDiscardBytes() const {return 256;} unsigned int GetDefaultDiscardBytes() const {return 256;}
}; };
//! \class MARC4 /// \class MARC4
//! \brief Modified Alleged RC4 /// \brief Modified Alleged RC4
//! \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a> /// \sa <a href="http://www.cryptopp.com/wiki/RC4">Alleged RC4</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
DOCUMENTED_TYPEDEF(SymmetricCipherFinal<MARC4_Base>, MARC4) DOCUMENTED_TYPEDEF(SymmetricCipherFinal<MARC4_Base>, MARC4)
} }

View File

@ -1,7 +1,7 @@
// argnames.h - originally written and placed in the public domain by Wei Dai // argnames.h - originally written and placed in the public domain by Wei Dai
//! \file argnames.h /// \file argnames.h
//! \brief Standard names for retrieving values by name when working with \p NameValuePairs /// \brief Standard names for retrieving values by name when working with \p NameValuePairs
#ifndef CRYPTOPP_ARGNAMES_H #ifndef CRYPTOPP_ARGNAMES_H
#define CRYPTOPP_ARGNAMES_H #define CRYPTOPP_ARGNAMES_H
@ -14,84 +14,84 @@ DOCUMENTED_NAMESPACE_BEGIN(Name)
#define CRYPTOPP_DEFINE_NAME_STRING(name) inline const char *name() {return #name;} #define CRYPTOPP_DEFINE_NAME_STRING(name) inline const char *name() {return #name;}
CRYPTOPP_DEFINE_NAME_STRING(ValueNames) //!< string, a list of value names with a semicolon (';') after each name CRYPTOPP_DEFINE_NAME_STRING(ValueNames) ///< string, a list of value names with a semicolon (';') after each name
CRYPTOPP_DEFINE_NAME_STRING(Version) //!< int CRYPTOPP_DEFINE_NAME_STRING(Version) ///< int
CRYPTOPP_DEFINE_NAME_STRING(Seed) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Seed) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Key) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Key) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(IV) //!< ConstByteArrayParameter, also accepts const byte * for backwards compatibility CRYPTOPP_DEFINE_NAME_STRING(IV) ///< ConstByteArrayParameter, also accepts const byte * for backwards compatibility
CRYPTOPP_DEFINE_NAME_STRING(StolenIV) //!< byte * CRYPTOPP_DEFINE_NAME_STRING(StolenIV) ///< byte *
CRYPTOPP_DEFINE_NAME_STRING(Nonce) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Nonce) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Rounds) //!< int CRYPTOPP_DEFINE_NAME_STRING(Rounds) ///< int
CRYPTOPP_DEFINE_NAME_STRING(FeedbackSize) //!< int CRYPTOPP_DEFINE_NAME_STRING(FeedbackSize) ///< int
CRYPTOPP_DEFINE_NAME_STRING(WordSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(WordSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(BlockSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(BlockSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(EffectiveKeyLength) //!< int, in bits CRYPTOPP_DEFINE_NAME_STRING(EffectiveKeyLength) ///< int, in bits
CRYPTOPP_DEFINE_NAME_STRING(KeySize) //!< int, in bits CRYPTOPP_DEFINE_NAME_STRING(KeySize) ///< int, in bits
CRYPTOPP_DEFINE_NAME_STRING(ModulusSize) //!< int, in bits CRYPTOPP_DEFINE_NAME_STRING(ModulusSize) ///< int, in bits
CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrderSize) //!< int, in bits CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrderSize) ///< int, in bits
CRYPTOPP_DEFINE_NAME_STRING(PrivateExponentSize)//!< int, in bits CRYPTOPP_DEFINE_NAME_STRING(PrivateExponentSize)///< int, in bits
CRYPTOPP_DEFINE_NAME_STRING(Modulus) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(Modulus) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(PublicExponent) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(PublicExponent) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(PrivateExponent) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(PrivateExponent) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(PublicElement) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(PublicElement) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrder) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(SubgroupOrder) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(Cofactor) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(Cofactor) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(SubgroupGenerator) //!< Integer, ECP::Point, or EC2N::Point CRYPTOPP_DEFINE_NAME_STRING(SubgroupGenerator) ///< Integer, ECP::Point, or EC2N::Point
CRYPTOPP_DEFINE_NAME_STRING(Curve) //!< ECP or EC2N CRYPTOPP_DEFINE_NAME_STRING(Curve) ///< ECP or EC2N
CRYPTOPP_DEFINE_NAME_STRING(GroupOID) //!< OID CRYPTOPP_DEFINE_NAME_STRING(GroupOID) ///< OID
CRYPTOPP_DEFINE_NAME_STRING(PointerToPrimeSelector) //!< const PrimeSelector * CRYPTOPP_DEFINE_NAME_STRING(PointerToPrimeSelector) ///< const PrimeSelector *
CRYPTOPP_DEFINE_NAME_STRING(Prime1) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(Prime1) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(Prime2) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(Prime2) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(ModPrime1PrivateExponent) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(ModPrime1PrivateExponent) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(ModPrime2PrivateExponent) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(ModPrime2PrivateExponent) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(MultiplicativeInverseOfPrime2ModPrime1) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(MultiplicativeInverseOfPrime2ModPrime1) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime1) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime1) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime2) //!< Integer CRYPTOPP_DEFINE_NAME_STRING(QuadraticResidueModPrime2) ///< Integer
CRYPTOPP_DEFINE_NAME_STRING(PutMessage) //!< bool CRYPTOPP_DEFINE_NAME_STRING(PutMessage) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(TruncatedDigestSize) //!< int CRYPTOPP_DEFINE_NAME_STRING(TruncatedDigestSize) ///< int
CRYPTOPP_DEFINE_NAME_STRING(BlockPaddingScheme) //!< StreamTransformationFilter::BlockPaddingScheme CRYPTOPP_DEFINE_NAME_STRING(BlockPaddingScheme) ///< StreamTransformationFilter::BlockPaddingScheme
CRYPTOPP_DEFINE_NAME_STRING(HashVerificationFilterFlags) //!< word32 CRYPTOPP_DEFINE_NAME_STRING(HashVerificationFilterFlags) ///< word32
CRYPTOPP_DEFINE_NAME_STRING(AuthenticatedDecryptionFilterFlags) //!< word32 CRYPTOPP_DEFINE_NAME_STRING(AuthenticatedDecryptionFilterFlags) ///< word32
CRYPTOPP_DEFINE_NAME_STRING(SignatureVerificationFilterFlags) //!< word32 CRYPTOPP_DEFINE_NAME_STRING(SignatureVerificationFilterFlags) ///< word32
CRYPTOPP_DEFINE_NAME_STRING(InputBuffer) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(InputBuffer) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(OutputBuffer) //!< ByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(OutputBuffer) ///< ByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(InputFileName) //!< const char * CRYPTOPP_DEFINE_NAME_STRING(InputFileName) ///< const char *
CRYPTOPP_DEFINE_NAME_STRING(InputFileNameWide) //!< const wchar_t * CRYPTOPP_DEFINE_NAME_STRING(InputFileNameWide) ///< const wchar_t *
CRYPTOPP_DEFINE_NAME_STRING(InputStreamPointer) //!< std::istream * CRYPTOPP_DEFINE_NAME_STRING(InputStreamPointer) ///< std::istream *
CRYPTOPP_DEFINE_NAME_STRING(InputBinaryMode) //!< bool CRYPTOPP_DEFINE_NAME_STRING(InputBinaryMode) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(OutputFileName) //!< const char * CRYPTOPP_DEFINE_NAME_STRING(OutputFileName) ///< const char *
CRYPTOPP_DEFINE_NAME_STRING(OutputFileNameWide) //!< const wchar_t * CRYPTOPP_DEFINE_NAME_STRING(OutputFileNameWide) ///< const wchar_t *
CRYPTOPP_DEFINE_NAME_STRING(OutputStreamPointer) //!< std::ostream * CRYPTOPP_DEFINE_NAME_STRING(OutputStreamPointer) ///< std::ostream *
CRYPTOPP_DEFINE_NAME_STRING(OutputBinaryMode) //!< bool CRYPTOPP_DEFINE_NAME_STRING(OutputBinaryMode) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(EncodingParameters) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(EncodingParameters) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(KeyDerivationParameters) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(KeyDerivationParameters) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Separator) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Separator) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Terminator) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Terminator) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Uppercase) //!< bool CRYPTOPP_DEFINE_NAME_STRING(Uppercase) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(GroupSize) //!< int CRYPTOPP_DEFINE_NAME_STRING(GroupSize) ///< int
CRYPTOPP_DEFINE_NAME_STRING(Pad) //!< bool CRYPTOPP_DEFINE_NAME_STRING(Pad) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(PaddingByte) //!< byte CRYPTOPP_DEFINE_NAME_STRING(PaddingByte) ///< byte
CRYPTOPP_DEFINE_NAME_STRING(Log2Base) //!< int CRYPTOPP_DEFINE_NAME_STRING(Log2Base) ///< int
CRYPTOPP_DEFINE_NAME_STRING(EncodingLookupArray) //!< const byte * CRYPTOPP_DEFINE_NAME_STRING(EncodingLookupArray) ///< const byte *
CRYPTOPP_DEFINE_NAME_STRING(DecodingLookupArray) //!< const byte * CRYPTOPP_DEFINE_NAME_STRING(DecodingLookupArray) ///< const byte *
CRYPTOPP_DEFINE_NAME_STRING(InsertLineBreaks) //!< bool CRYPTOPP_DEFINE_NAME_STRING(InsertLineBreaks) ///< bool
CRYPTOPP_DEFINE_NAME_STRING(MaxLineLength) //!< int CRYPTOPP_DEFINE_NAME_STRING(MaxLineLength) ///< int
CRYPTOPP_DEFINE_NAME_STRING(DigestSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(DigestSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(L1KeyLength) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(L1KeyLength) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(TableSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(TableSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(Blinding) //!< bool, timing attack mitigations, ON by default CRYPTOPP_DEFINE_NAME_STRING(Blinding) ///< bool, timing attack mitigations, ON by default
CRYPTOPP_DEFINE_NAME_STRING(DerivedKey) //!< ByteArrayParameter, key derivation, derived key CRYPTOPP_DEFINE_NAME_STRING(DerivedKey) ///< ByteArrayParameter, key derivation, derived key
CRYPTOPP_DEFINE_NAME_STRING(DerivedKeyLength) //!< int, key derivation, derived key length in bytes CRYPTOPP_DEFINE_NAME_STRING(DerivedKeyLength) ///< int, key derivation, derived key length in bytes
CRYPTOPP_DEFINE_NAME_STRING(Personalization) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Personalization) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(PersonalizationSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(PersonalizationSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(Salt) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Salt) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(Tweak) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Tweak) ///< ConstByteArrayParameter
CRYPTOPP_DEFINE_NAME_STRING(SaltSize) //!< int, in bytes CRYPTOPP_DEFINE_NAME_STRING(SaltSize) ///< int, in bytes
CRYPTOPP_DEFINE_NAME_STRING(TreeMode) //!< byte CRYPTOPP_DEFINE_NAME_STRING(TreeMode) ///< byte
CRYPTOPP_DEFINE_NAME_STRING(FileName) //!< const char * CRYPTOPP_DEFINE_NAME_STRING(FileName) ///< const char *
CRYPTOPP_DEFINE_NAME_STRING(FileTime) //!< int CRYPTOPP_DEFINE_NAME_STRING(FileTime) ///< int
CRYPTOPP_DEFINE_NAME_STRING(Comment) //!< const char * CRYPTOPP_DEFINE_NAME_STRING(Comment) ///< const char *
CRYPTOPP_DEFINE_NAME_STRING(Identity) //!< ConstByteArrayParameter CRYPTOPP_DEFINE_NAME_STRING(Identity) ///< ConstByteArrayParameter
DOCUMENTED_NAMESPACE_END DOCUMENTED_NAMESPACE_END
NAMESPACE_END NAMESPACE_END

46
aria.h
View File

@ -1,14 +1,14 @@
// aria.h - written and placed in the public domain by Jeffrey Walton // aria.h - written and placed in the public domain by Jeffrey Walton
//! \file aria.h /// \file aria.h
//! \brief Classes for the ARIA block cipher /// \brief Classes for the ARIA block cipher
//! \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun /// \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun
//! from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on /// from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on
//! the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea /// the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea
//! Internet & Security Agency website. /// Internet & Security Agency website.
//! \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>, /// \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>,
//! <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea /// <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea
//! Internet & Security Agency homepage</A> /// Internet & Security Agency homepage</A>
#ifndef CRYPTOPP_ARIA_H #ifndef CRYPTOPP_ARIA_H
#define CRYPTOPP_ARIA_H #define CRYPTOPP_ARIA_H
@ -19,25 +19,25 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ARIA_Info /// \class ARIA_Info
//! \brief ARIA block cipher information /// \brief ARIA block cipher information
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
struct ARIA_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8> struct ARIA_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ARIA";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ARIA";}
}; };
//! \class ARIA /// \class ARIA
//! \brief ARIA block cipher /// \brief ARIA block cipher
//! \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun /// \details The Crypto++ ARIA implementation is based on the 32-bit implementation by Aaram Yun
//! from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on /// from the National Security Research Institute, KOREA. Aaram Yun's implementation is based on
//! the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea /// the 8-bit implementation by Jin Hong. The source files are available in ARIA.zip from the Korea
//! Internet & Security Agency website. /// Internet & Security Agency website.
//! \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>, /// \sa <A HREF="http://tools.ietf.org/html/rfc5794">RFC 5794, A Description of the ARIA Encryption Algorithm</A>,
//! <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea /// <A HREF="http://seed.kisa.or.kr/iwt/ko/bbs/EgovReferenceList.do?bbsId=BBSMSTR_000000000002">Korea
//! Internet & Security Agency homepage</A> /// Internet & Security Agency homepage</A>
//! \sa <a href="http://www.cryptopp.com/wiki/ARIA">ARIA</a> /// \sa <a href="http://www.cryptopp.com/wiki/ARIA">ARIA</a>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class ARIA : public ARIA_Info, public BlockCipherDocumentation class ARIA : public ARIA_Info, public BlockCipherDocumentation
{ {
public: public:

330
asn.h
View File

@ -1,7 +1,7 @@
// asn.h - originally written and placed in the public domain by Wei Dai // asn.h - originally written and placed in the public domain by Wei Dai
//! \file asn.h /// \file asn.h
//! \brief Classes and functions for working with ANS.1 objects /// \brief Classes and functions for working with ANS.1 objects
#ifndef CRYPTOPP_ASN_H #ifndef CRYPTOPP_ASN_H
#define CRYPTOPP_ASN_H #define CRYPTOPP_ASN_H
@ -22,8 +22,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief ASN.1 types /// \brief ASN.1 types
//! \note These tags and flags are not complete /// \note These tags and flags are not complete
enum ASNTag enum ASNTag
{ {
BOOLEAN = 0x01, BOOLEAN = 0x01,
@ -51,8 +51,8 @@ enum ASNTag
GENERAL_STRING = 0x1b GENERAL_STRING = 0x1b
}; };
//! \brief ASN.1 flags /// \brief ASN.1 flags
//! \note These tags and flags are not complete /// \note These tags and flags are not complete
enum ASNIdFlag enum ASNIdFlag
{ {
UNIVERSAL = 0x00, UNIVERSAL = 0x00,
@ -65,140 +65,140 @@ enum ASNIdFlag
PRIVATE = 0xc0 PRIVATE = 0xc0
}; };
//! \brief Raises a BERDecodeErr /// \brief Raises a BERDecodeErr
inline void BERDecodeError() {throw BERDecodeErr();} inline void BERDecodeError() {throw BERDecodeErr();}
//! \brief Exception thrown when an unknown object identifier is encountered /// \brief Exception thrown when an unknown object identifier is encountered
class CRYPTOPP_DLL UnknownOID : public BERDecodeErr class CRYPTOPP_DLL UnknownOID : public BERDecodeErr
{ {
public: public:
//! \brief Construct an UnknownOID /// \brief Construct an UnknownOID
UnknownOID() : BERDecodeErr("BER decode error: unknown object identifier") {} UnknownOID() : BERDecodeErr("BER decode error: unknown object identifier") {}
//! \brief Construct an UnknownOID /// \brief Construct an UnknownOID
//! \param err error message to use for the execption /// \param err error message to use for the execption
UnknownOID(const char *err) : BERDecodeErr(err) {} UnknownOID(const char *err) : BERDecodeErr(err) {}
}; };
// unsigned int DERLengthEncode(unsigned int length, byte *output=0); // unsigned int DERLengthEncode(unsigned int length, byte *output=0);
//! \brief DER encode a length /// \brief DER encode a length
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
//! \param length the size to encode /// \param length the size to encode
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API DERLengthEncode(BufferedTransformation &bt, lword length); CRYPTOPP_DLL size_t CRYPTOPP_API DERLengthEncode(BufferedTransformation &bt, lword length);
//! \brief BER decode a length /// \brief BER decode a length
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param length the decoded size /// \param length the decoded size
//! \returns true if the value was decoded /// \returns true if the value was decoded
//! \throws BERDecodeError if the value fails to decode or is too large for size_t /// \throws BERDecodeError if the value fails to decode or is too large for size_t
//! \details BERLengthDecode() returns false if the encoding is indefinite length. /// \details BERLengthDecode() returns false if the encoding is indefinite length.
CRYPTOPP_DLL bool CRYPTOPP_API BERLengthDecode(BufferedTransformation &bt, size_t &length); CRYPTOPP_DLL bool CRYPTOPP_API BERLengthDecode(BufferedTransformation &bt, size_t &length);
//! \brief DER encode NULL /// \brief DER encode NULL
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
CRYPTOPP_DLL void CRYPTOPP_API DEREncodeNull(BufferedTransformation &bt); CRYPTOPP_DLL void CRYPTOPP_API DEREncodeNull(BufferedTransformation &bt);
//! \brief BER decode NULL /// \brief BER decode NULL
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
CRYPTOPP_DLL void CRYPTOPP_API BERDecodeNull(BufferedTransformation &bt); CRYPTOPP_DLL void CRYPTOPP_API BERDecodeNull(BufferedTransformation &bt);
//! \brief DER encode octet string /// \brief DER encode octet string
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
//! \param str the string to encode /// \param str the string to encode
//! \param strLen the length of the string /// \param strLen the length of the string
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const byte *str, size_t strLen); CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const byte *str, size_t strLen);
//! \brief DER encode octet string /// \brief DER encode octet string
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param str the string to encode /// \param str the string to encode
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const SecByteBlock &str); CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeOctetString(BufferedTransformation &bt, const SecByteBlock &str);
//! \brief BER decode octet string /// \brief BER decode octet string
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param str the decoded string /// \param str the decoded string
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, SecByteBlock &str); CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, SecByteBlock &str);
//! \brief BER decode octet string /// \brief BER decode octet string
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param str the decoded string /// \param str the decoded string
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, BufferedTransformation &str); CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeOctetString(BufferedTransformation &bt, BufferedTransformation &str);
//! \brief DER encode text string /// \brief DER encode text string
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
//! \param str the string to encode /// \param str the string to encode
//! \param asnTag the ASN.1 type /// \param asnTag the ASN.1 type
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
//! \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING /// \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeTextString(BufferedTransformation &bt, const std::string &str, byte asnTag); CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeTextString(BufferedTransformation &bt, const std::string &str, byte asnTag);
//! \brief BER decode text string /// \brief BER decode text string
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param str the string to encode /// \param str the string to encode
//! \param asnTag the ASN.1 type /// \param asnTag the ASN.1 type
//! \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING /// \details DEREncodeTextString() can be used for UTF8_STRING, PRINTABLE_STRING, and IA5_STRING
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeTextString(BufferedTransformation &bt, std::string &str, byte asnTag); CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeTextString(BufferedTransformation &bt, std::string &str, byte asnTag);
//! \brief DER encode bit string /// \brief DER encode bit string
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
//! \param str the string to encode /// \param str the string to encode
//! \param strLen the length of the string /// \param strLen the length of the string
//! \param unusedBits the number of unused bits /// \param unusedBits the number of unused bits
//! \returns the number of octets used for the encoding /// \returns the number of octets used for the encoding
CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeBitString(BufferedTransformation &bt, const byte *str, size_t strLen, unsigned int unusedBits=0); CRYPTOPP_DLL size_t CRYPTOPP_API DEREncodeBitString(BufferedTransformation &bt, const byte *str, size_t strLen, unsigned int unusedBits=0);
//! \brief DER decode bit string /// \brief DER decode bit string
//! \param bt BufferedTransformation object for reading /// \param bt BufferedTransformation object for reading
//! \param str the decoded string /// \param str the decoded string
//! \param unusedBits the number of unused bits /// \param unusedBits the number of unused bits
CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeBitString(BufferedTransformation &bt, SecByteBlock &str, unsigned int &unusedBits); CRYPTOPP_DLL size_t CRYPTOPP_API BERDecodeBitString(BufferedTransformation &bt, SecByteBlock &str, unsigned int &unusedBits);
//! \brief BER decode and DER re-encode /// \brief BER decode and DER re-encode
//! \param bt BufferedTransformation object for writing /// \param bt BufferedTransformation object for writing
//! \param dest BufferedTransformation object /// \param dest BufferedTransformation object
CRYPTOPP_DLL void CRYPTOPP_API DERReencode(BufferedTransformation &bt, BufferedTransformation &dest); CRYPTOPP_DLL void CRYPTOPP_API DERReencode(BufferedTransformation &bt, BufferedTransformation &dest);
//! \brief Object Identifier /// \brief Object Identifier
class CRYPTOPP_DLL OID class CRYPTOPP_DLL OID
{ {
public: public:
virtual ~OID() {} virtual ~OID() {}
//! \brief Construct an OID /// \brief Construct an OID
OID() {} OID() {}
//! \brief Construct an OID /// \brief Construct an OID
//! \param v value to initialize the OID /// \param v value to initialize the OID
OID(word32 v) : m_values(1, v) {} OID(word32 v) : m_values(1, v) {}
//! \brief Construct an OID /// \brief Construct an OID
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
OID(BufferedTransformation &bt) {BERDecode(bt);} OID(BufferedTransformation &bt) {BERDecode(bt);}
//! \brief Append a value to an OID /// \brief Append a value to an OID
//! \param rhs the value to append /// \param rhs the value to append
inline OID & operator+=(word32 rhs) {m_values.push_back(rhs); return *this;} inline OID & operator+=(word32 rhs) {m_values.push_back(rhs); return *this;}
//! \brief DER encode this OID /// \brief DER encode this OID
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
//! \brief BER decode an OID /// \brief BER decode an OID
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
void BERDecode(BufferedTransformation &bt); void BERDecode(BufferedTransformation &bt);
//! \brief BER decode an OID /// \brief BER decode an OID
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
//! \throws BERDecodeErr() if decoded value doesn't match an expected OID /// \throws BERDecodeErr() if decoded value doesn't match an expected OID
//! \details BERDecodeAndCheck() can be used to parse an OID and verify it matches an expected. /// \details BERDecodeAndCheck() can be used to parse an OID and verify it matches an expected.
//! <pre> /// <pre>
//! BERSequenceDecoder key(bt); /// BERSequenceDecoder key(bt);
//! ... /// ...
//! BERSequenceDecoder algorithm(key); /// BERSequenceDecoder algorithm(key);
//! GetAlgorithmID().BERDecodeAndCheck(algorithm); /// GetAlgorithmID().BERDecodeAndCheck(algorithm);
//! </pre> /// </pre>
void BERDecodeAndCheck(BufferedTransformation &bt) const; void BERDecodeAndCheck(BufferedTransformation &bt) const;
std::vector<word32> m_values; std::vector<word32> m_values;
@ -208,7 +208,7 @@ private:
static size_t DecodeValue(BufferedTransformation &bt, word32 &v); static size_t DecodeValue(BufferedTransformation &bt, word32 &v);
}; };
//! \brief ASN.1 encoded object filter /// \brief ASN.1 encoded object filter
class EncodedObjectFilter : public Filter class EncodedObjectFilter : public Filter
{ {
public: public:
@ -216,15 +216,15 @@ public:
virtual ~EncodedObjectFilter() {} virtual ~EncodedObjectFilter() {}
//! \brief Construct an EncodedObjectFilter /// \brief Construct an EncodedObjectFilter
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param nObjects the number of objects /// \param nObjects the number of objects
//! \param flags bitwise OR of EncodedObjectFilter::Flag /// \param flags bitwise OR of EncodedObjectFilter::Flag
EncodedObjectFilter(BufferedTransformation *attachment = NULLPTR, unsigned int nObjects = 1, word32 flags = 0); EncodedObjectFilter(BufferedTransformation *attachment = NULLPTR, unsigned int nObjects = 1, word32 flags = 0);
//! \brief Input a byte buffer for processing /// \brief Input a byte buffer for processing
//! \param inString the byte buffer to process /// \param inString the byte buffer to process
//! \param length the size of the string, in bytes /// \param length the size of the string, in bytes
void Put(const byte *inString, size_t length); void Put(const byte *inString, size_t length);
unsigned int GetNumberOfCompletedObjects() const {return m_nCurrentObject;} unsigned int GetNumberOfCompletedObjects() const {return m_nCurrentObject;}
@ -242,7 +242,7 @@ private:
lword m_lengthRemaining; lword m_lengthRemaining;
}; };
//! \brief BER General Decoder /// \brief BER General Decoder
class CRYPTOPP_DLL BERGeneralDecoder : public Store class CRYPTOPP_DLL BERGeneralDecoder : public Store
{ {
public: public:
@ -280,7 +280,7 @@ private:
// proper direction. We did not break the library or versioning based on the output of // proper direction. We did not break the library or versioning based on the output of
// `nm --demangle libcryptopp.a | grep DERGeneralEncoder::DERGeneralEncoder | grep -v " U "`. // `nm --demangle libcryptopp.a | grep DERGeneralEncoder::DERGeneralEncoder | grep -v " U "`.
//! \brief DER General Encoder /// \brief DER General Encoder
class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue class CRYPTOPP_DLL DERGeneralEncoder : public ByteQueue
{ {
public: public:
@ -299,7 +299,7 @@ private:
byte m_asnTag; byte m_asnTag;
}; };
//! \brief BER Sequence Decoder /// \brief BER Sequence Decoder
class CRYPTOPP_DLL BERSequenceDecoder : public BERGeneralDecoder class CRYPTOPP_DLL BERSequenceDecoder : public BERGeneralDecoder
{ {
public: public:
@ -309,7 +309,7 @@ public:
: BERGeneralDecoder(inQueue, asnTag) {} : BERGeneralDecoder(inQueue, asnTag) {}
}; };
//! \brief DER Sequence Encoder /// \brief DER Sequence Encoder
class CRYPTOPP_DLL DERSequenceEncoder : public DERGeneralEncoder class CRYPTOPP_DLL DERSequenceEncoder : public DERGeneralEncoder
{ {
public: public:
@ -319,7 +319,7 @@ public:
: DERGeneralEncoder(outQueue, asnTag) {} : DERGeneralEncoder(outQueue, asnTag) {}
}; };
//! \brief BER Set Decoder /// \brief BER Set Decoder
class CRYPTOPP_DLL BERSetDecoder : public BERGeneralDecoder class CRYPTOPP_DLL BERSetDecoder : public BERGeneralDecoder
{ {
public: public:
@ -329,7 +329,7 @@ public:
: BERGeneralDecoder(inQueue, asnTag) {} : BERGeneralDecoder(inQueue, asnTag) {}
}; };
//! \brief DER Set Encoder /// \brief DER Set Encoder
class CRYPTOPP_DLL DERSetEncoder : public DERGeneralEncoder class CRYPTOPP_DLL DERSetEncoder : public DERGeneralEncoder
{ {
public: public:
@ -339,17 +339,17 @@ public:
: DERGeneralEncoder(outQueue, asnTag) {} : DERGeneralEncoder(outQueue, asnTag) {}
}; };
//! \brief Optional data encoder and decoder /// \brief Optional data encoder and decoder
//! \tparam T class or type /// \tparam T class or type
template <class T> template <class T>
class ASNOptional : public member_ptr<T> class ASNOptional : public member_ptr<T>
{ {
public: public:
//! \brief BER decode optional data /// \brief BER decode optional data
//! \param seqDecoder sequence with the optional ASN.1 data /// \param seqDecoder sequence with the optional ASN.1 data
//! \param tag ASN.1 tag to match as optional data /// \param tag ASN.1 tag to match as optional data
//! \param mask the mask to apply when matching the tag /// \param mask the mask to apply when matching the tag
//! \sa ASNTag and ASNIdFlag /// \sa ASNTag and ASNIdFlag
void BERDecode(BERSequenceDecoder &seqDecoder, byte tag, byte mask = ~CONSTRUCTED) void BERDecode(BERSequenceDecoder &seqDecoder, byte tag, byte mask = ~CONSTRUCTED)
{ {
byte b; byte b;
@ -357,8 +357,8 @@ public:
reset(new T(seqDecoder)); reset(new T(seqDecoder));
} }
//! \brief DER encode optional data /// \brief DER encode optional data
//! \param out BufferedTransformation object /// \param out BufferedTransformation object
void DEREncode(BufferedTransformation &out) void DEREncode(BufferedTransformation &out)
{ {
if (this->get() != NULLPTR) if (this->get() != NULLPTR)
@ -366,29 +366,29 @@ public:
} }
}; };
//! \brief Encode and decode ASN.1 objects with additional information /// \brief Encode and decode ASN.1 objects with additional information
//! \tparam BASE base class or type /// \tparam BASE base class or type
//! \details Encodes and decodes public keys, private keys and group /// \details Encodes and decodes public keys, private keys and group
//! parameters with OID identifying the algorithm or scheme. /// parameters with OID identifying the algorithm or scheme.
template <class BASE> template <class BASE>
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1CryptoMaterial : public ASN1Object, public BASE class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1CryptoMaterial : public ASN1Object, public BASE
{ {
public: public:
//! \brief DER encode ASN.1 object /// \brief DER encode ASN.1 object
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
//! \details Save() will write the OID associated with algorithm or scheme. /// \details Save() will write the OID associated with algorithm or scheme.
//! In the case of public and private keys, this function writes the /// In the case of public and private keys, this function writes the
//! subjectPubicKeyInfo and privateKeyInfo parts. /// subjectPubicKeyInfo and privateKeyInfo parts.
void Save(BufferedTransformation &bt) const void Save(BufferedTransformation &bt) const
{BEREncode(bt);} {BEREncode(bt);}
//! \brief BER decode ASN.1 object /// \brief BER decode ASN.1 object
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
void Load(BufferedTransformation &bt) void Load(BufferedTransformation &bt)
{BERDecode(bt);} {BERDecode(bt);}
}; };
//! \brief Encodes and decodes subjectPublicKeyInfo /// \brief Encodes and decodes subjectPublicKeyInfo
class CRYPTOPP_DLL X509PublicKey : public ASN1CryptoMaterial<PublicKey> class CRYPTOPP_DLL X509PublicKey : public ASN1CryptoMaterial<PublicKey>
{ {
public: public:
@ -397,21 +397,21 @@ public:
void BERDecode(BufferedTransformation &bt); void BERDecode(BufferedTransformation &bt);
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
//! \brief Retrieves the OID of the algorithm /// \brief Retrieves the OID of the algorithm
//! \returns OID of the algorithm /// \returns OID of the algorithm
virtual OID GetAlgorithmID() const =0; virtual OID GetAlgorithmID() const =0;
virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt) virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt)
{BERDecodeNull(bt); return false;} {BERDecodeNull(bt); return false;}
virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const
{DEREncodeNull(bt); return false;} // see RFC 2459, section 7.3.1 {DEREncodeNull(bt); return false;} // see RFC 2459, section 7.3.1
//! decode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header /// decode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header
virtual void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0; virtual void BERDecodePublicKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0;
//! encode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header /// encode subjectPublicKey part of subjectPublicKeyInfo, without the BIT STRING header
virtual void DEREncodePublicKey(BufferedTransformation &bt) const =0; virtual void DEREncodePublicKey(BufferedTransformation &bt) const =0;
}; };
//! \brief Encodes and decodesprivateKeyInfo /// \brief Encodes and decodesprivateKeyInfo
class CRYPTOPP_DLL PKCS8PrivateKey : public ASN1CryptoMaterial<PrivateKey> class CRYPTOPP_DLL PKCS8PrivateKey : public ASN1CryptoMaterial<PrivateKey>
{ {
public: public:
@ -420,23 +420,23 @@ public:
void BERDecode(BufferedTransformation &bt); void BERDecode(BufferedTransformation &bt);
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
//! \brief Retrieves the OID of the algorithm /// \brief Retrieves the OID of the algorithm
//! \returns OID of the algorithm /// \returns OID of the algorithm
virtual OID GetAlgorithmID() const =0; virtual OID GetAlgorithmID() const =0;
virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt) virtual bool BERDecodeAlgorithmParameters(BufferedTransformation &bt)
{BERDecodeNull(bt); return false;} {BERDecodeNull(bt); return false;}
virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const virtual bool DEREncodeAlgorithmParameters(BufferedTransformation &bt) const
{DEREncodeNull(bt); return false;} // see RFC 2459, section 7.3.1 {DEREncodeNull(bt); return false;} // see RFC 2459, section 7.3.1
//! decode privateKey part of privateKeyInfo, without the OCTET STRING header /// decode privateKey part of privateKeyInfo, without the OCTET STRING header
virtual void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0; virtual void BERDecodePrivateKey(BufferedTransformation &bt, bool parametersPresent, size_t size) =0;
//! encode privateKey part of privateKeyInfo, without the OCTET STRING header /// encode privateKey part of privateKeyInfo, without the OCTET STRING header
virtual void DEREncodePrivateKey(BufferedTransformation &bt) const =0; virtual void DEREncodePrivateKey(BufferedTransformation &bt) const =0;
//! decode optional attributes including context-specific tag /// decode optional attributes including context-specific tag
/*! /note default implementation stores attributes to be output in DEREncodeOptionalAttributes */ /*! /note default implementation stores attributes to be output in DEREncodeOptionalAttributes */
virtual void BERDecodeOptionalAttributes(BufferedTransformation &bt); virtual void BERDecodeOptionalAttributes(BufferedTransformation &bt);
//! encode optional attributes including context-specific tag /// encode optional attributes including context-specific tag
virtual void DEREncodeOptionalAttributes(BufferedTransformation &bt) const; virtual void DEREncodeOptionalAttributes(BufferedTransformation &bt) const;
protected: protected:
@ -445,12 +445,12 @@ protected:
// ******************************************************** // ********************************************************
//! \brief DER Encode unsigned value /// \brief DER Encode unsigned value
//! \tparam T class or type /// \tparam T class or type
//! \param out BufferedTransformation object /// \param out BufferedTransformation object
//! \param w unsigned value to encode /// \param w unsigned value to encode
//! \param asnTag the ASN.1 type /// \param asnTag the ASN.1 type
//! \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM /// \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM
template <class T> template <class T>
size_t DEREncodeUnsigned(BufferedTransformation &out, T w, byte asnTag = INTEGER) size_t DEREncodeUnsigned(BufferedTransformation &out, T w, byte asnTag = INTEGER)
{ {
@ -478,15 +478,15 @@ size_t DEREncodeUnsigned(BufferedTransformation &out, T w, byte asnTag = INTEGER
return 1+lengthBytes+bc; return 1+lengthBytes+bc;
} }
//! \brief BER Decode unsigned value /// \brief BER Decode unsigned value
//! \tparam T fundamental C++ type /// \tparam T fundamental C++ type
//! \param in BufferedTransformation object /// \param in BufferedTransformation object
//! \param w the decoded value /// \param w the decoded value
//! \param asnTag the ASN.1 type /// \param asnTag the ASN.1 type
//! \param minValue the minimum expected value /// \param minValue the minimum expected value
//! \param maxValue the maximum expected value /// \param maxValue the maximum expected value
//! \throws BERDecodeErr() if the value cannot be parsed or the decoded value is not within range. /// \throws BERDecodeErr() if the value cannot be parsed or the decoded value is not within range.
//! \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM /// \details DEREncodeUnsigned() can be used with INTEGER, BOOLEAN, and ENUM
template <class T> template <class T>
void BERDecodeUnsigned(BufferedTransformation &in, T &w, byte asnTag = INTEGER, void BERDecodeUnsigned(BufferedTransformation &in, T &w, byte asnTag = INTEGER,
T minValue = 0, T maxValue = T(0xffffffff)) T minValue = 0, T maxValue = T(0xffffffff))
@ -534,25 +534,25 @@ void BERDecodeUnsigned(BufferedTransformation &in, T &w, byte asnTag = INTEGER,
} }
#ifdef CRYPTOPP_DOXYGEN_PROCESSING #ifdef CRYPTOPP_DOXYGEN_PROCESSING
//! \brief Compare two OIDs for equality /// \brief Compare two OIDs for equality
//! \param lhs the first OID /// \param lhs the first OID
//! \param rhs the second OID /// \param rhs the second OID
//! \returns true if the OIDs are equal, false otherwise /// \returns true if the OIDs are equal, false otherwise
inline bool operator==(const OID &lhs, const OID &rhs); inline bool operator==(const OID &lhs, const OID &rhs);
//! \brief Compare two OIDs for inequality /// \brief Compare two OIDs for inequality
//! \param lhs the first OID /// \param lhs the first OID
//! \param rhs the second OID /// \param rhs the second OID
//! \returns true if the OIDs are not equal, false otherwise /// \returns true if the OIDs are not equal, false otherwise
inline bool operator!=(const OID &lhs, const OID &rhs); inline bool operator!=(const OID &lhs, const OID &rhs);
//! \brief Compare two OIDs for ordering /// \brief Compare two OIDs for ordering
//! \param lhs the first OID /// \param lhs the first OID
//! \param rhs the second OID /// \param rhs the second OID
//! \returns true if the first OID is less than the second OID, false otherwise /// \returns true if the first OID is less than the second OID, false otherwise
//! \details operator<() calls std::lexicographical_compare() on each element in the array of values. /// \details operator<() calls std::lexicographical_compare() on each element in the array of values.
inline bool operator<(const OID &lhs, const OID &rhs); inline bool operator<(const OID &lhs, const OID &rhs);
//! \brief Append a value to an OID /// \brief Append a value to an OID
//! \param lhs the OID /// \param lhs the OID
//! \param rhs the value to append /// \param rhs the value to append
inline OID operator+(const OID &lhs, unsigned long rhs); inline OID operator+(const OID &lhs, unsigned long rhs);
#else #else
inline bool operator==(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs) inline bool operator==(const ::CryptoPP::OID &lhs, const ::CryptoPP::OID &rhs)

View File

@ -1,21 +1,21 @@
// authenc.h - originally written and placed in the public domain by Wei Dai // authenc.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \brief Classes for authenticated encryption modes of operation /// \brief Classes for authenticated encryption modes of operation
//! \details Authenticated encryption (AE) schemes combine confidentiality and authenticity /// \details Authenticated encryption (AE) schemes combine confidentiality and authenticity
//! into a single mode of operation They gained traction in the early 2000's because manually /// into a single mode of operation They gained traction in the early 2000's because manually
//! combining them was error prone for the typical developer. Around that time, the desire to /// combining them was error prone for the typical developer. Around that time, the desire to
//! authenticate but not ecrypt additional data (AAD) was also identified. When both features /// authenticate but not ecrypt additional data (AAD) was also identified. When both features
//! are available from a scheme, the system is referred to as an AEAD scheme. /// are available from a scheme, the system is referred to as an AEAD scheme.
//! \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
//! and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the /// and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the
//! motivation for the API, like calling AAD a &quot;header&quot;, can be found in Bellare, /// motivation for the API, like calling AAD a &quot;header&quot;, can be found in Bellare,
//! Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX /// Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX
//! Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD /// Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD
//! schemes in software and promote adoption of the modes. /// schemes in software and promote adoption of the modes.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
//! Encryption</A> on the Crypto++ wiki. /// Encryption</A> on the Crypto++ wiki.
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
#ifndef CRYPTOPP_AUTHENC_H #ifndef CRYPTOPP_AUTHENC_H
#define CRYPTOPP_AUTHENC_H #define CRYPTOPP_AUTHENC_H
@ -25,19 +25,19 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class AuthenticatedSymmetricCipherBase /// \class AuthenticatedSymmetricCipherBase
//! \brief Base class for authenticated encryption modes of operation /// \brief Base class for authenticated encryption modes of operation
//! \details AuthenticatedSymmetricCipherBase() serves as a base implementation for one direction /// \details AuthenticatedSymmetricCipherBase() serves as a base implementation for one direction
//! (encryption or decryption) of a stream cipher or block cipher mode with authentication. /// (encryption or decryption) of a stream cipher or block cipher mode with authentication.
//! \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
//! and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the /// and OCB mode. All modes derive from AuthenticatedSymmetricCipherBase() and the
//! motivation for the API, like calling AAD a &quot;header&quot;, can be found in Bellare, /// motivation for the API, like calling AAD a &quot;header&quot;, can be found in Bellare,
//! Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX /// Rogaway and Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX
//! Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD /// Mode of Operation</A>. The EAX paper suggested a basic API to help standardize AEAD
//! schemes in software and promote adoption of the modes. /// schemes in software and promote adoption of the modes.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
//! Encryption</A> on the Crypto++ wiki. /// Encryption</A> on the Crypto++ wiki.
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipherBase : public AuthenticatedSymmetricCipher class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipherBase : public AuthenticatedSymmetricCipher
{ {
public: public:

198
base32.h
View File

@ -1,8 +1,8 @@
// base32.h - written and placed in the public domain by Frank Palazzolo, based on hex.cpp by Wei Dai // base32.h - written and placed in the public domain by Frank Palazzolo, based on hex.cpp by Wei Dai
// extended hex alphabet added by JW in November, 2017. // extended hex alphabet added by JW in November, 2017.
//! \file base32.h /// \file base32.h
//! \brief Classes for Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \brief Classes for Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
#ifndef CRYPTOPP_BASE32_H #ifndef CRYPTOPP_BASE32_H
#define CRYPTOPP_BASE32_H #define CRYPTOPP_BASE32_H
@ -12,148 +12,148 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Base32Encoder /// \class Base32Encoder
//! \brief Base32 encodes data using DUDE encoding /// \brief Base32 encodes data using DUDE encoding
//! \details Converts data to base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>. /// \details Converts data to base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
class Base32Encoder : public SimpleProxyFilter class Base32Encoder : public SimpleProxyFilter
{ {
public: public:
//! \brief Construct a Base32Encoder /// \brief Construct a Base32Encoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param uppercase a flag indicating uppercase output /// \param uppercase a flag indicating uppercase output
//! \param groupSize the size of the grouping /// \param groupSize the size of the grouping
//! \param separator the separator to use between groups /// \param separator the separator to use between groups
//! \param terminator the terminator appeand after processing /// \param terminator the terminator appeand after processing
//! \details Base32Encoder() constructs a default encoder. The constructor lacks fields for padding and /// \details Base32Encoder() constructs a default encoder. The constructor lacks fields for padding and
//! line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it. /// line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
Base32Encoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "") Base32Encoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment) : SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{ {
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator))); IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
} }
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details The following code modifies the padding and line break parameters for an encoder: /// \details The following code modifies the padding and line break parameters for an encoder:
//! <pre> /// <pre>
//! Base32Encoder encoder; /// Base32Encoder encoder;
//! AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false); /// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
//! \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base /// \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base
//! 32 Encoding with Extended Hex Alphabet</A> by performing the following: /// 32 Encoding with Extended Hex Alphabet</A> by performing the following:
//! <pre> /// <pre>
//! Base32Encoder encoder; /// Base32Encoder encoder;
//! const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; /// const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
//! AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET); /// AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
//! \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and /// \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and
//! the decoder's lookup table. /// the decoder's lookup table.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
}; };
//! \class Base32Decoder /// \class Base32Decoder
//! \brief Base32 decodes data using DUDE encoding /// \brief Base32 decodes data using DUDE encoding
//! \details Converts data from base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>. /// \details Converts data from base32 using DUDE encoding. The default code is based on <A HREF="http://www.ietf.org/proceedings/51/I-D/draft-ietf-idn-dude-02.txt">Differential Unicode Domain Encoding (DUDE) (draft-ietf-idn-dude-02.txt)</A>.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
class Base32Decoder : public BaseN_Decoder class Base32Decoder : public BaseN_Decoder
{ {
public: public:
//! \brief Construct a Base32Decoder /// \brief Construct a Base32Decoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \sa IsolatedInitialize() for an example of modifying a Base32Decoder after construction. /// \sa IsolatedInitialize() for an example of modifying a Base32Decoder after construction.
Base32Decoder(BufferedTransformation *attachment = NULLPTR) Base32Decoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {} : BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {}
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base /// \details You can change the encoding to <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base
//! 32 Encoding with Extended Hex Alphabet</A> by performing the following: /// 32 Encoding with Extended Hex Alphabet</A> by performing the following:
//! <pre> /// <pre>
//! int lookup[256]; /// int lookup[256];
//! const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV"; /// const byte ALPHABET[] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
//! Base32Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 32, true /*insensitive*/); /// Base32Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 32, true /*insensitive*/);
//! ///
//! Base32Decoder decoder; /// Base32Decoder decoder;
//! AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup); /// AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup);
//! decoder.IsolatedInitialize(params);</pre> /// decoder.IsolatedInitialize(params);</pre>
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
private: private:
//! \brief Provides the default decoding lookup table /// \brief Provides the default decoding lookup table
//! \return default decoding lookup table /// \return default decoding lookup table
static const int * CRYPTOPP_API GetDefaultDecodingLookupArray(); static const int * CRYPTOPP_API GetDefaultDecodingLookupArray();
}; };
//! \class Base32HexEncoder /// \class Base32HexEncoder
//! \brief Base32 encodes data using extended hex /// \brief Base32 encodes data using extended hex
//! \details Converts data to base32 using extended hex alphabet. The alphabet is different than Base32Encoder. /// \details Converts data to base32 using extended hex alphabet. The alphabet is different than Base32Encoder.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>. /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class Base32HexEncoder : public SimpleProxyFilter class Base32HexEncoder : public SimpleProxyFilter
{ {
public: public:
//! \brief Construct a Base32HexEncoder /// \brief Construct a Base32HexEncoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param uppercase a flag indicating uppercase output /// \param uppercase a flag indicating uppercase output
//! \param groupSize the size of the grouping /// \param groupSize the size of the grouping
//! \param separator the separator to use between groups /// \param separator the separator to use between groups
//! \param terminator the terminator appeand after processing /// \param terminator the terminator appeand after processing
//! \details Base32HexEncoder() constructs a default encoder. The constructor lacks fields for padding and /// \details Base32HexEncoder() constructs a default encoder. The constructor lacks fields for padding and
//! line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it. /// line breaks. You must use IsolatedInitialize() to change the default padding character or suppress it.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
Base32HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "") Base32HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment) : SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{ {
IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator))); IsolatedInitialize(MakeParameters(Name::Uppercase(), uppercase)(Name::GroupSize(), groupSize)(Name::Separator(), ConstByteArrayParameter(separator))(Name::Terminator(), ConstByteArrayParameter(terminator)));
} }
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details The following code modifies the padding and line break parameters for an encoder: /// \details The following code modifies the padding and line break parameters for an encoder:
//! <pre> /// <pre>
//! Base32HexEncoder encoder; /// Base32HexEncoder encoder;
//! AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false); /// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
}; };
//! \class Base32HexDecoder /// \class Base32HexDecoder
//! \brief Base32 decodes data using extended hex /// \brief Base32 decodes data using extended hex
//! \details Converts data from base32 using extended hex alphabet. The alphabet is different than Base32Decoder. /// \details Converts data from base32 using extended hex alphabet. The alphabet is different than Base32Decoder.
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>. /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder, <A HREF="http://tools.ietf.org/html/rfc4648#page-10">RFC 4648, Base 32 Encoding with Extended Hex Alphabet</A>.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class Base32HexDecoder : public BaseN_Decoder class Base32HexDecoder : public BaseN_Decoder
{ {
public: public:
//! \brief Construct a Base32HexDecoder /// \brief Construct a Base32HexDecoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder /// \sa Base32Encoder, Base32Decoder, Base32HexEncoder and Base32HexDecoder
Base32HexDecoder(BufferedTransformation *attachment = NULLPTR) Base32HexDecoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {} : BaseN_Decoder(GetDefaultDecodingLookupArray(), 5, attachment) {}
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
private: private:
//! \brief Provides the default decoding lookup table /// \brief Provides the default decoding lookup table
//! \return default decoding lookup table /// \return default decoding lookup table
static const int * CRYPTOPP_API GetDefaultDecodingLookupArray(); static const int * CRYPTOPP_API GetDefaultDecodingLookupArray();
}; };

198
base64.h
View File

@ -1,7 +1,7 @@
// base64.h - originally written and placed in the public domain by Wei Dai // base64.h - originally written and placed in the public domain by Wei Dai
//! \file base64.h /// \file base64.h
//! \brief Classes for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder /// \brief Classes for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder
#ifndef CRYPTOPP_BASE64_H #ifndef CRYPTOPP_BASE64_H
#define CRYPTOPP_BASE64_H #define CRYPTOPP_BASE64_H
@ -11,104 +11,104 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Base64Encoder /// \class Base64Encoder
//! \brief Base64 encodes data /// \brief Base64 encodes data
//! \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>. /// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>.
class Base64Encoder : public SimpleProxyFilter class Base64Encoder : public SimpleProxyFilter
{ {
public: public:
//! \brief Construct a Base64Encoder /// \brief Construct a Base64Encoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param insertLineBreaks a BufferedTrasformation to attach to this object /// \param insertLineBreaks a BufferedTrasformation to attach to this object
//! \param maxLineLength the length of a line if line breaks are used /// \param maxLineLength the length of a line if line breaks are used
//! \details Base64Encoder constructs a default encoder. The constructor lacks a parameter for padding, and you must /// \details Base64Encoder constructs a default encoder. The constructor lacks a parameter for padding, and you must
//! use IsolatedInitialize() to modify the Base64Encoder after construction. /// use IsolatedInitialize() to modify the Base64Encoder after construction.
//! \sa IsolatedInitialize() for an example of modifying an encoder after construction. /// \sa IsolatedInitialize() for an example of modifying an encoder after construction.
Base64Encoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = true, int maxLineLength = 72) Base64Encoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = true, int maxLineLength = 72)
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment) : SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{ {
IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), insertLineBreaks)(Name::MaxLineLength(), maxLineLength)); IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), insertLineBreaks)(Name::MaxLineLength(), maxLineLength));
} }
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details The following code modifies the padding and line break parameters for an encoder: /// \details The following code modifies the padding and line break parameters for an encoder:
//! <pre> /// <pre>
//! Base64Encoder encoder; /// Base64Encoder encoder;
//! AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false); /// AlgorithmParameters params = MakeParameters(Pad(), false)(InsertLineBreaks(), false);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
//! \details You can change the encoding to RFC 4648 web safe alphabet by performing the following: /// \details You can change the encoding to RFC 4648 web safe alphabet by performing the following:
//! <pre> /// <pre>
//! Base64Encoder encoder; /// Base64Encoder encoder;
//! const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; /// const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
//! AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET); /// AlgorithmParameters params = MakeParameters(Name::EncodingLookupArray(),(const byte *)ALPHABET);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
//! \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and /// \details If you change the encoding alphabet, then you will need to change the decoding alphabet \a and
//! the decoder's lookup table. /// the decoder's lookup table.
//! \sa Base64URLEncoder for an encoder that provides the web safe alphabet, and Base64Decoder::IsolatedInitialize() /// \sa Base64URLEncoder for an encoder that provides the web safe alphabet, and Base64Decoder::IsolatedInitialize()
//! for an example of modifying a decoder's lookup table after construction. /// for an example of modifying a decoder's lookup table after construction.
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
}; };
//! \class Base64Decoder /// \class Base64Decoder
//! \brief Base64 decodes data /// \brief Base64 decodes data
//! \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>. /// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648, Base 64 Encoding</A>.
class Base64Decoder : public BaseN_Decoder class Base64Decoder : public BaseN_Decoder
{ {
public: public:
//! \brief Construct a Base64Decoder /// \brief Construct a Base64Decoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \sa IsolatedInitialize() for an example of modifying an encoder after construction. /// \sa IsolatedInitialize() for an example of modifying an encoder after construction.
Base64Decoder(BufferedTransformation *attachment = NULLPTR) Base64Decoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {} : BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details The default decoding alpahbet is RFC 4868. You can change the to RFC 4868 web safe alphabet /// \details The default decoding alpahbet is RFC 4868. You can change the to RFC 4868 web safe alphabet
//! by performing the following: /// by performing the following:
//! <pre> /// <pre>
//! int lookup[256]; /// int lookup[256];
//! const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; /// const byte ALPHABET[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
//! Base64Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 64, false); /// Base64Decoder::InitializeDecodingLookupArray(lookup, ALPHABET, 64, false);
//! ///
//! Base64Decoder decoder; /// Base64Decoder decoder;
//! AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup); /// AlgorithmParameters params = MakeParameters(Name::DecodingLookupArray(),(const int *)lookup);
//! decoder.IsolatedInitialize(params);</pre> /// decoder.IsolatedInitialize(params);</pre>
//! \sa Base64URLDecoder for a decoder that provides the web safe alphabet, and Base64Encoder::IsolatedInitialize() /// \sa Base64URLDecoder for a decoder that provides the web safe alphabet, and Base64Encoder::IsolatedInitialize()
//! for an example of modifying an encoder's alphabet after construction. /// for an example of modifying an encoder's alphabet after construction.
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
private: private:
//! \brief Provides the default decoding lookup table /// \brief Provides the default decoding lookup table
//! \return default decoding lookup table /// \return default decoding lookup table
static const int * CRYPTOPP_API GetDecodingLookupArray(); static const int * CRYPTOPP_API GetDecodingLookupArray();
}; };
//! \class Base64URLEncoder /// \class Base64URLEncoder
//! \brief Base64 encodes data using a web safe alphabet /// \brief Base64 encodes data using a web safe alphabet
//! \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding /// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding
//! with URL and Filename Safe Alphabet</A>. /// with URL and Filename Safe Alphabet</A>.
class Base64URLEncoder : public SimpleProxyFilter class Base64URLEncoder : public SimpleProxyFilter
{ {
public: public:
//! \brief Construct a Base64URLEncoder /// \brief Construct a Base64URLEncoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param insertLineBreaks a BufferedTrasformation to attach to this object /// \param insertLineBreaks a BufferedTrasformation to attach to this object
//! \param maxLineLength the length of a line if line breaks are used /// \param maxLineLength the length of a line if line breaks are used
//! \details Base64URLEncoder() constructs a default encoder using a web safe alphabet. The constructor ignores /// \details Base64URLEncoder() constructs a default encoder using a web safe alphabet. The constructor ignores
//! insertLineBreaks and maxLineLength because the web and URL safe specifications don't use them. They are /// insertLineBreaks and maxLineLength because the web and URL safe specifications don't use them. They are
//! present in the constructor for API compatibility with Base64Encoder so it is a drop-in replacement. The /// present in the constructor for API compatibility with Base64Encoder so it is a drop-in replacement. The
//! constructor also disables padding on the encoder for the same reason. /// constructor also disables padding on the encoder for the same reason.
//! \details If you need line breaks or padding, then you must use IsolatedInitialize() to set them /// \details If you need line breaks or padding, then you must use IsolatedInitialize() to set them
//! after constructing a Base64URLEncoder. /// after constructing a Base64URLEncoder.
//! \sa Base64Encoder for an encoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize /// \sa Base64Encoder for an encoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize
//! for an example of modifying an encoder after construction. /// for an example of modifying an encoder after construction.
Base64URLEncoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = false, int maxLineLength = -1) Base64URLEncoder(BufferedTransformation *attachment = NULLPTR, bool insertLineBreaks = false, int maxLineLength = -1)
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment) : SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{ {
@ -116,44 +116,44 @@ public:
IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), false)(Name::MaxLineLength(), -1)(Name::Pad(),false)); IsolatedInitialize(MakeParameters(Name::InsertLineBreaks(), false)(Name::MaxLineLength(), -1)(Name::Pad(),false));
} }
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on attached
//! transformations. If initialization should be propagated, then use the Initialize() function. /// transformations. If initialization should be propagated, then use the Initialize() function.
//! \details The following code modifies the padding and line break parameters for an encoder: /// \details The following code modifies the padding and line break parameters for an encoder:
//! <pre> /// <pre>
//! Base64URLEncoder encoder; /// Base64URLEncoder encoder;
//! AlgorithmParameters params = MakeParameters(Name::Pad(), true)(Name::InsertLineBreaks(), true); /// AlgorithmParameters params = MakeParameters(Name::Pad(), true)(Name::InsertLineBreaks(), true);
//! encoder.IsolatedInitialize(params);</pre> /// encoder.IsolatedInitialize(params);</pre>
//! \sa Base64Encoder for an encoder that provides a classic alphabet. /// \sa Base64Encoder for an encoder that provides a classic alphabet.
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
}; };
//! \class Base64URLDecoder /// \class Base64URLDecoder
//! \brief Base64 decodes data using a web safe alphabet /// \brief Base64 decodes data using a web safe alphabet
//! \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding /// \details Base64 encodes data per <A HREF="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648, Base 64 Encoding
//! with URL and Filename Safe Alphabet</A>. /// with URL and Filename Safe Alphabet</A>.
class Base64URLDecoder : public BaseN_Decoder class Base64URLDecoder : public BaseN_Decoder
{ {
public: public:
//! \brief Construct a Base64URLDecoder /// \brief Construct a Base64URLDecoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \details Base64URLDecoder() constructs a default decoder using a web safe alphabet. /// \details Base64URLDecoder() constructs a default decoder using a web safe alphabet.
//! \sa Base64Decoder for a decoder that provides a classic alphabet. /// \sa Base64Decoder for a decoder that provides a classic alphabet.
Base64URLDecoder(BufferedTransformation *attachment = NULLPTR) Base64URLDecoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {} : BaseN_Decoder(GetDecodingLookupArray(), 6, attachment) {}
//! \brief Initialize or reinitialize this object, without signal propagation /// \brief Initialize or reinitialize this object, without signal propagation
//! \param parameters a set of NameValuePairs used to initialize this object /// \param parameters a set of NameValuePairs used to initialize this object
//! \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
//! number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on /// number of arbitrarily typed arguments. IsolatedInitialize() does not call Initialize() on
//! attached transformations. If initialization should be propagated, then use the Initialize() function. /// attached transformations. If initialization should be propagated, then use the Initialize() function.
//! \sa Base64Decoder for a decoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize /// \sa Base64Decoder for a decoder that provides a classic alphabet, and Base64URLEncoder::IsolatedInitialize
//! for an example of modifying an encoder after construction. /// for an example of modifying an encoder after construction.
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
private: private:
//! \brief Provides the default decoding lookup table /// \brief Provides the default decoding lookup table
//! \return default decoding lookup table /// \return default decoding lookup table
static const int * CRYPTOPP_API GetDecodingLookupArray(); static const int * CRYPTOPP_API GetDecodingLookupArray();
}; };

View File

@ -1,7 +1,7 @@
// basecode.h - originally written and placed in the public domain by Wei Dai // basecode.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \brief Base classes for working with encoders and decoders. /// \brief Base classes for working with encoders and decoders.
#ifndef CRYPTOPP_BASECODE_H #ifndef CRYPTOPP_BASECODE_H
#define CRYPTOPP_BASECODE_H #define CRYPTOPP_BASECODE_H
@ -13,25 +13,25 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class BaseN_Encoder /// \class BaseN_Encoder
//! \brief Encoder for bases that are a power of 2 /// \brief Encoder for bases that are a power of 2
class CRYPTOPP_DLL BaseN_Encoder : public Unflushable<Filter> class CRYPTOPP_DLL BaseN_Encoder : public Unflushable<Filter>
{ {
public: public:
//! \brief Construct a BaseN_Encoder /// \brief Construct a BaseN_Encoder
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
BaseN_Encoder(BufferedTransformation *attachment=NULLPTR) BaseN_Encoder(BufferedTransformation *attachment=NULLPTR)
: m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0) : m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0)
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0) , m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
{Detach(attachment);} {Detach(attachment);}
//! \brief Construct a BaseN_Encoder /// \brief Construct a BaseN_Encoder
//! \param alphabet table of ASCII characters to use as the alphabet /// \param alphabet table of ASCII characters to use as the alphabet
//! \param log2base the log<sub>2</sub>base /// \param log2base the log<sub>2</sub>base
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \param padding the character to use as padding /// \param padding the character to use as padding
//! \pre log2base must be between 1 and 7 inclusive /// \pre log2base must be between 1 and 7 inclusive
//! \throws InvalidArgument if log2base is not between 1 and 7 /// \throws InvalidArgument if log2base is not between 1 and 7
BaseN_Encoder(const byte *alphabet, int log2base, BufferedTransformation *attachment=NULLPTR, int padding=-1) BaseN_Encoder(const byte *alphabet, int log2base, BufferedTransformation *attachment=NULLPTR, int padding=-1)
: m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0) : m_alphabet(NULLPTR), m_padding(0), m_bitsPerChar(0)
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0) , m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
@ -53,28 +53,28 @@ private:
SecByteBlock m_outBuf; SecByteBlock m_outBuf;
}; };
//! \class BaseN_Decoder /// \class BaseN_Decoder
//! \brief Decoder for bases that are a power of 2 /// \brief Decoder for bases that are a power of 2
class CRYPTOPP_DLL BaseN_Decoder : public Unflushable<Filter> class CRYPTOPP_DLL BaseN_Decoder : public Unflushable<Filter>
{ {
public: public:
//! \brief Construct a BaseN_Decoder /// \brief Construct a BaseN_Decoder
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \details padding is set to -1, which means use default padding. If not /// \details padding is set to -1, which means use default padding. If not
//! required, then the value must be set via IsolatedInitialize(). /// required, then the value must be set via IsolatedInitialize().
BaseN_Decoder(BufferedTransformation *attachment=NULLPTR) BaseN_Decoder(BufferedTransformation *attachment=NULLPTR)
: m_lookup(NULLPTR), m_padding(0), m_bitsPerChar(0) : m_lookup(NULLPTR), m_padding(0), m_bitsPerChar(0)
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0) , m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
{Detach(attachment);} {Detach(attachment);}
//! \brief Construct a BaseN_Decoder /// \brief Construct a BaseN_Decoder
//! \param lookup table of values /// \param lookup table of values
//! \param log2base the log<sub>2</sub>base /// \param log2base the log<sub>2</sub>base
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \details log2base is the exponent (like 5 in 2<sup>5</sup>), and not /// \details log2base is the exponent (like 5 in 2<sup>5</sup>), and not
//! the number of elements (like 32). /// the number of elements (like 32).
//! \details padding is set to -1, which means use default padding. If not /// \details padding is set to -1, which means use default padding. If not
//! required, then the value must be set via IsolatedInitialize(). /// required, then the value must be set via IsolatedInitialize().
BaseN_Decoder(const int *lookup, int log2base, BufferedTransformation *attachment=NULLPTR) BaseN_Decoder(const int *lookup, int log2base, BufferedTransformation *attachment=NULLPTR)
: m_lookup(NULLPTR), m_padding(0), m_bitsPerChar(0) : m_lookup(NULLPTR), m_padding(0), m_bitsPerChar(0)
, m_outputBlockSize(0), m_bytePos(0), m_bitPos(0) , m_outputBlockSize(0), m_bytePos(0), m_bitPos(0)
@ -86,16 +86,16 @@ public:
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking); size_t Put2(const byte *begin, size_t length, int messageEnd, bool blocking);
//! \brief Initializes BaseN lookup array /// \brief Initializes BaseN lookup array
//! \param lookup table of values /// \param lookup table of values
//! \param alphabet table of ASCII characters /// \param alphabet table of ASCII characters
//! \param base the base for the encoder /// \param base the base for the encoder
//! \param caseInsensitive flag indicating whether the alphabet is case sensitivie /// \param caseInsensitive flag indicating whether the alphabet is case sensitivie
//! \pre COUNTOF(lookup) == 256 /// \pre COUNTOF(lookup) == 256
//! \pre COUNTOF(alphabet) == base /// \pre COUNTOF(alphabet) == base
//! \details Internally, the function sets the first 256 elements in the lookup table to /// \details Internally, the function sets the first 256 elements in the lookup table to
//! their value from the alphabet array or -1. base is the number of element (like 32), /// their value from the alphabet array or -1. base is the number of element (like 32),
//! and not an exponent (like 5 in 2<sup>5</sup>) /// and not an exponent (like 5 in 2<sup>5</sup>)
static void CRYPTOPP_API InitializeDecodingLookupArray(int *lookup, const byte *alphabet, unsigned int base, bool caseInsensitive); static void CRYPTOPP_API InitializeDecodingLookupArray(int *lookup, const byte *alphabet, unsigned int base, bool caseInsensitive);
private: private:
@ -105,21 +105,21 @@ private:
SecByteBlock m_outBuf; SecByteBlock m_outBuf;
}; };
//! \class Grouper /// \class Grouper
//! \brief Filter that breaks input stream into groups of fixed size /// \brief Filter that breaks input stream into groups of fixed size
class CRYPTOPP_DLL Grouper : public Bufferless<Filter> class CRYPTOPP_DLL Grouper : public Bufferless<Filter>
{ {
public: public:
//! \brief Construct a Grouper /// \brief Construct a Grouper
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
Grouper(BufferedTransformation *attachment=NULLPTR) Grouper(BufferedTransformation *attachment=NULLPTR)
: m_groupSize(0), m_counter(0) {Detach(attachment);} : m_groupSize(0), m_counter(0) {Detach(attachment);}
//! \brief Construct a Grouper /// \brief Construct a Grouper
//! \param groupSize the size of the grouping /// \param groupSize the size of the grouping
//! \param separator the separator to use between groups /// \param separator the separator to use between groups
//! \param terminator the terminator appeand after processing /// \param terminator the terminator appeand after processing
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
Grouper(int groupSize, const std::string &separator, const std::string &terminator, BufferedTransformation *attachment=NULLPTR) Grouper(int groupSize, const std::string &separator, const std::string &terminator, BufferedTransformation *attachment=NULLPTR)
: m_groupSize(0), m_counter(0) : m_groupSize(0), m_counter(0)
{ {

198
blake2.h
View File

@ -2,17 +2,17 @@
// Wilcox-O'Hearn. Based on Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's // Wilcox-O'Hearn. Based on Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
// reference BLAKE2 implementation at http://github.com/BLAKE2/BLAKE2. // reference BLAKE2 implementation at http://github.com/BLAKE2/BLAKE2.
//! \file blake2.h /// \file blake2.h
//! \brief Classes for BLAKE2b and BLAKE2s message digests and keyed message digests /// \brief Classes for BLAKE2b and BLAKE2s message digests and keyed message digests
//! \details This implementation follows Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's /// \details This implementation follows Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
//! <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29). /// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
//! Static algorithm name return either "BLAKE2b" or "BLAKE2s". An object algorithm name follows /// Static algorithm name return either "BLAKE2b" or "BLAKE2s". An object algorithm name follows
//! the naming described in <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The /// the naming described in <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The
//! BLAKE2 Cryptographic Hash and Message Authentication Code (MAC)</A>. /// BLAKE2 Cryptographic Hash and Message Authentication Code (MAC)</A>.
//! \details The library provides specialized SSE2, SSE4 and NEON version of the BLAKE2 compression /// \details The library provides specialized SSE2, SSE4 and NEON version of the BLAKE2 compression
//! function. For best results under ARM NEON, specify both an architecture and cpu. For example: /// function. For best results under ARM NEON, specify both an architecture and cpu. For example:
//! <pre>CXXFLAGS="-DNDEBUG -march=armv8-a+crc -mcpu=cortex-a53 ..."</pre> /// <pre>CXXFLAGS="-DNDEBUG -march=armv8-a+crc -mcpu=cortex-a53 ..."</pre>
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
#ifndef CRYPTOPP_BLAKE2_H #ifndef CRYPTOPP_BLAKE2_H
#define CRYPTOPP_BLAKE2_H #define CRYPTOPP_BLAKE2_H
@ -23,10 +23,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class BLAKE2_Info /// \class BLAKE2_Info
//! \brief BLAKE2 hash information /// \brief BLAKE2 hash information
//! \tparam T_64bit flag indicating 64-bit /// \tparam T_64bit flag indicating 64-bit
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <bool T_64bit> template <bool T_64bit>
struct BLAKE2_Info : public VariableKeyLength<(T_64bit ? 64 : 32),0,(T_64bit ? 64 : 32),1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE> struct BLAKE2_Info : public VariableKeyLength<(T_64bit ? 64 : 32),0,(T_64bit ? 64 : 32),1,SimpleKeyingInterface::NOT_RESYNCHRONIZABLE>
{ {
@ -43,18 +43,18 @@ struct BLAKE2_Info : public VariableKeyLength<(T_64bit ? 64 : 32),0,(T_64bit ? 6
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return (T_64bit ? "BLAKE2b" : "BLAKE2s");} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return (T_64bit ? "BLAKE2b" : "BLAKE2s");}
}; };
//! \class BLAKE2_ParameterBlock /// \class BLAKE2_ParameterBlock
//! \brief BLAKE2 parameter block /// \brief BLAKE2 parameter block
//! \tparam T_64bit flag indicating 64-bit /// \tparam T_64bit flag indicating 64-bit
//! \details BLAKE2b uses BLAKE2_ParameterBlock<true>, while BLAKE2s /// \details BLAKE2b uses BLAKE2_ParameterBlock<true>, while BLAKE2s
//! uses BLAKE2_ParameterBlock<false>. /// uses BLAKE2_ParameterBlock<false>.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <bool T_64bit> template <bool T_64bit>
struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock
{ {
}; };
//! \brief BLAKE2b parameter block specialization /// \brief BLAKE2b parameter block specialization
template<> template<>
struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<true> struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<true>
{ {
@ -89,7 +89,7 @@ struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<true>
byte personalization[PERSONALIZATIONSIZE]; byte personalization[PERSONALIZATIONSIZE];
}; };
//! \brief BLAKE2s parameter block specialization /// \brief BLAKE2s parameter block specialization
template<> template<>
struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<false> struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<false>
{ {
@ -124,13 +124,13 @@ struct CRYPTOPP_NO_VTABLE BLAKE2_ParameterBlock<false>
byte personalization[PERSONALIZATIONSIZE]; byte personalization[PERSONALIZATIONSIZE];
}; };
//! \class BLAKE2_State /// \class BLAKE2_State
//! \brief BLAKE2 state information /// \brief BLAKE2 state information
//! \tparam W word type /// \tparam W word type
//! \tparam T_64bit flag indicating 64-bit /// \tparam T_64bit flag indicating 64-bit
//! \details BLAKE2b uses BLAKE2_State<word64, true>, while BLAKE2s /// \details BLAKE2b uses BLAKE2_State<word64, true>, while BLAKE2s
//! uses BLAKE2_State<word32, false>. /// uses BLAKE2_State<word32, false>.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <class W, bool T_64bit> template <class W, bool T_64bit>
struct CRYPTOPP_NO_VTABLE BLAKE2_State struct CRYPTOPP_NO_VTABLE BLAKE2_State
{ {
@ -150,13 +150,13 @@ struct CRYPTOPP_NO_VTABLE BLAKE2_State
size_t length; size_t length;
}; };
//! \class BLAKE2_Base /// \class BLAKE2_Base
//! \brief BLAKE2 hash implementation /// \brief BLAKE2 hash implementation
//! \tparam W word type /// \tparam W word type
//! \tparam T_64bit flag indicating 64-bit /// \tparam T_64bit flag indicating 64-bit
//! \details BLAKE2b uses BLAKE2_Base<word64, true>, while BLAKE2s /// \details BLAKE2b uses BLAKE2_Base<word64, true>, while BLAKE2s
//! uses BLAKE2_Base<word32, false>. /// uses BLAKE2_Base<word32, false>.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <class W, bool T_64bit> template <class W, bool T_64bit>
class BLAKE2_Base : public SimpleKeyingInterfaceImpl<MessageAuthenticationCode, BLAKE2_Info<T_64bit> > class BLAKE2_Base : public SimpleKeyingInterfaceImpl<MessageAuthenticationCode, BLAKE2_Info<T_64bit> >
{ {
@ -177,15 +177,15 @@ public:
virtual ~BLAKE2_Base() {} virtual ~BLAKE2_Base() {}
//! \brief Retrieve the static algorithm name /// \brief Retrieve the static algorithm name
//! \returns the algorithm name (BLAKE2s or BLAKE2b) /// \returns the algorithm name (BLAKE2s or BLAKE2b)
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return BLAKE2_Info<T_64bit>::StaticAlgorithmName();} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return BLAKE2_Info<T_64bit>::StaticAlgorithmName();}
//! \brief Retrieve the object's name /// \brief Retrieve the object's name
//! \returns the object's algorithm name following RFC 7693 /// \returns the object's algorithm name following RFC 7693
//! \details Object algorithm name follows the naming described in /// \details Object algorithm name follows the naming described in
//! <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The BLAKE2 Cryptographic Hash and /// <A HREF="http://tools.ietf.org/html/rfc7693#section-4">RFC 7693, The BLAKE2 Cryptographic Hash and
//! Message Authentication Code (MAC)</A>. For example, "BLAKE2b-512" and "BLAKE2s-256". /// Message Authentication Code (MAC)</A>. For example, "BLAKE2b-512" and "BLAKE2s-256".
std::string AlgorithmName() const {return std::string(StaticAlgorithmName()) + "-" + IntToString(this->DigestSize()*8);} std::string AlgorithmName() const {return std::string(StaticAlgorithmName()) + "-" + IntToString(this->DigestSize()*8);}
unsigned int DigestSize() const {return m_digestSize;} unsigned int DigestSize() const {return m_digestSize;}
@ -194,23 +194,23 @@ public:
void Update(const byte *input, size_t length); void Update(const byte *input, size_t length);
void Restart(); void Restart();
//! \brief Restart a hash with parameter block and counter /// \brief Restart a hash with parameter block and counter
//! \param block parameter block /// \param block parameter block
//! \param counter counter array /// \param counter counter array
//! \details Parameter block is persisted across calls to Restart(). /// \details Parameter block is persisted across calls to Restart().
void Restart(const BLAKE2_ParameterBlock<T_64bit>& block, const W counter[2]); void Restart(const BLAKE2_ParameterBlock<T_64bit>& block, const W counter[2]);
//! \brief Set tree mode /// \brief Set tree mode
//! \param mode the new tree mode /// \param mode the new tree mode
//! \details BLAKE2 has two finalization flags, called State::f[0] and State::f[1]. /// \details BLAKE2 has two finalization flags, called State::f[0] and State::f[1].
//! If <tt>treeMode=false</tt> (default), then State::f[1] is never set. If /// If <tt>treeMode=false</tt> (default), then State::f[1] is never set. If
//! <tt>treeMode=true</tt>, then State::f[1] is set when State::f[0] is set. /// <tt>treeMode=true</tt>, then State::f[1] is set when State::f[0] is set.
//! Tree mode is persisted across calls to Restart(). /// Tree mode is persisted across calls to Restart().
void SetTreeMode(bool mode) {m_treeMode=mode;} void SetTreeMode(bool mode) {m_treeMode=mode;}
//! \brief Get tree mode /// \brief Get tree mode
//! \returns the current tree mode /// \returns the current tree mode
//! \details Tree mode is persisted across calls to Restart(). /// \details Tree mode is persisted across calls to Restart().
bool GetTreeMode() const {return m_treeMode;} bool GetTreeMode() const {return m_treeMode;}
void TruncatedFinal(byte *hash, size_t size); void TruncatedFinal(byte *hash, size_t size);
@ -236,15 +236,15 @@ private:
bool m_treeMode; bool m_treeMode;
}; };
//! \brief The BLAKE2b cryptographic hash function /// \brief The BLAKE2b cryptographic hash function
//! \details BLAKE2b can function as both a hash and keyed hash. If you want only the hash, /// \details BLAKE2b can function as both a hash and keyed hash. If you want only the hash,
//! then use the BLAKE2b constructor that accepts no parameters or digest size. If you /// then use the BLAKE2b constructor that accepts no parameters or digest size. If you
//! want a keyed hash, then use the constructor that accpts the key as a parameter. /// want a keyed hash, then use the constructor that accpts the key as a parameter.
//! Once a key and digest size are selected, its effectively immutable. The Restart() /// Once a key and digest size are selected, its effectively immutable. The Restart()
//! method that accepts a ParameterBlock does not allow you to change it. /// method that accepts a ParameterBlock does not allow you to change it.
//! \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's /// \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
//! <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29). /// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
class BLAKE2b : public BLAKE2_Base<word64, true> class BLAKE2b : public BLAKE2_Base<word64, true>
{ {
public: public:
@ -252,35 +252,35 @@ public:
typedef BLAKE2_ParameterBlock<true> ParameterBlock; typedef BLAKE2_ParameterBlock<true> ParameterBlock;
CRYPTOPP_COMPILE_ASSERT(sizeof(ParameterBlock) == 64); CRYPTOPP_COMPILE_ASSERT(sizeof(ParameterBlock) == 64);
//! \brief Construct a BLAKE2b hash /// \brief Construct a BLAKE2b hash
//! \param digestSize the digest size, in bytes /// \param digestSize the digest size, in bytes
//! \param treeMode flag indicating tree mode /// \param treeMode flag indicating tree mode
BLAKE2b(bool treeMode=false, unsigned int digestSize = DIGESTSIZE) : ThisBase(treeMode, digestSize) {} BLAKE2b(bool treeMode=false, unsigned int digestSize = DIGESTSIZE) : ThisBase(treeMode, digestSize) {}
//! \brief Construct a BLAKE2b hash /// \brief Construct a BLAKE2b hash
//! \param key a byte array used to key the cipher /// \param key a byte array used to key the cipher
//! \param keyLength the size of the byte array /// \param keyLength the size of the byte array
//! \param salt a byte array used as salt /// \param salt a byte array used as salt
//! \param saltLength the size of the byte array /// \param saltLength the size of the byte array
//! \param personalization a byte array used as prsonalization string /// \param personalization a byte array used as prsonalization string
//! \param personalizationLength the size of the byte array /// \param personalizationLength the size of the byte array
//! \param treeMode flag indicating tree mode /// \param treeMode flag indicating tree mode
//! \param digestSize the digest size, in bytes /// \param digestSize the digest size, in bytes
BLAKE2b(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0, BLAKE2b(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0,
const byte* personalization = NULLPTR, size_t personalizationLength = 0, const byte* personalization = NULLPTR, size_t personalizationLength = 0,
bool treeMode=false, unsigned int digestSize = DIGESTSIZE) bool treeMode=false, unsigned int digestSize = DIGESTSIZE)
: ThisBase(key, keyLength, salt, saltLength, personalization, personalizationLength, treeMode, digestSize) {} : ThisBase(key, keyLength, salt, saltLength, personalization, personalizationLength, treeMode, digestSize) {}
}; };
//! \brief The BLAKE2s cryptographic hash function /// \brief The BLAKE2s cryptographic hash function
//! \details BLAKE2s can function as both a hash and keyed hash. If you want only the hash, /// \details BLAKE2s can function as both a hash and keyed hash. If you want only the hash,
//! then use the BLAKE2s constructor that accepts no parameters or digest size. If you /// then use the BLAKE2s constructor that accepts no parameters or digest size. If you
//! want a keyed hash, then use the constructor that accpts the key as a parameter. /// want a keyed hash, then use the constructor that accpts the key as a parameter.
//! Once a key and digest size are selected, its effectively immutable. The Restart() /// Once a key and digest size are selected, its effectively immutable. The Restart()
//! method that accepts a ParameterBlock does not allow you to change it. /// method that accepts a ParameterBlock does not allow you to change it.
//! \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's /// \sa Aumasson, Neves, Wilcox-O'Hearn and Winnerlein's
//! <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29). /// <A HREF="http://blake2.net/blake2.pdf">BLAKE2: simpler, smaller, fast as MD5</A> (2013.01.29).
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
class BLAKE2s : public BLAKE2_Base<word32, false> class BLAKE2s : public BLAKE2_Base<word32, false>
{ {
public: public:
@ -288,20 +288,20 @@ public:
typedef BLAKE2_ParameterBlock<false> ParameterBlock; typedef BLAKE2_ParameterBlock<false> ParameterBlock;
CRYPTOPP_COMPILE_ASSERT(sizeof(ParameterBlock) == 32); CRYPTOPP_COMPILE_ASSERT(sizeof(ParameterBlock) == 32);
//! \brief Construct a BLAKE2s hash /// \brief Construct a BLAKE2s hash
//! \param digestSize the digest size, in bytes /// \param digestSize the digest size, in bytes
//! \param treeMode flag indicating tree mode /// \param treeMode flag indicating tree mode
BLAKE2s(bool treeMode=false, unsigned int digestSize = DIGESTSIZE) : ThisBase(treeMode, digestSize) {} BLAKE2s(bool treeMode=false, unsigned int digestSize = DIGESTSIZE) : ThisBase(treeMode, digestSize) {}
//! \brief Construct a BLAKE2s hash /// \brief Construct a BLAKE2s hash
//! \param key a byte array used to key the cipher /// \param key a byte array used to key the cipher
//! \param keyLength the size of the byte array /// \param keyLength the size of the byte array
//! \param salt a byte array used as salt /// \param salt a byte array used as salt
//! \param saltLength the size of the byte array /// \param saltLength the size of the byte array
//! \param personalization a byte array used as prsonalization string /// \param personalization a byte array used as prsonalization string
//! \param personalizationLength the size of the byte array /// \param personalizationLength the size of the byte array
//! \param treeMode flag indicating tree mode /// \param treeMode flag indicating tree mode
//! \param digestSize the digest size, in bytes /// \param digestSize the digest size, in bytes
BLAKE2s(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0, BLAKE2s(const byte *key, size_t keyLength, const byte* salt = NULLPTR, size_t saltLength = 0,
const byte* personalization = NULLPTR, size_t personalizationLength = 0, const byte* personalization = NULLPTR, size_t personalizationLength = 0,
bool treeMode=false, unsigned int digestSize = DIGESTSIZE) bool treeMode=false, unsigned int digestSize = DIGESTSIZE)

View File

@ -1,7 +1,7 @@
// blowfish.h - originally written and placed in the public domain by Wei Dai // blowfish.h - originally written and placed in the public domain by Wei Dai
//! \file blowfish.h /// \file blowfish.h
//! \brief Classes for the Blowfish block cipher /// \brief Classes for the Blowfish block cipher
#ifndef CRYPTOPP_BLOWFISH_H #ifndef CRYPTOPP_BLOWFISH_H
#define CRYPTOPP_BLOWFISH_H #define CRYPTOPP_BLOWFISH_H
@ -11,8 +11,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Blowfish_Info /// \class Blowfish_Info
//! \brief Blowfish block cipher information /// \brief Blowfish block cipher information
struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 4, 56>, public FixedRounds<16> struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 4, 56>, public FixedRounds<16>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Blowfish";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Blowfish";}
@ -20,14 +20,14 @@ struct Blowfish_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 4,
// <a href="http://www.cryptopp.com/wiki/Blowfish">Blowfish</a> // <a href="http://www.cryptopp.com/wiki/Blowfish">Blowfish</a>
//! \class Blowfish /// \class Blowfish
//! \brief Blowfish block cipher /// \brief Blowfish block cipher
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class Blowfish : public Blowfish_Info, public BlockCipherDocumentation class Blowfish : public Blowfish_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief Class specific implementation and overrides used to operate the cipher. /// \brief Class specific implementation and overrides used to operate the cipher.
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions /// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Blowfish_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Blowfish_Info>
{ {
public: public:

View File

@ -1,8 +1,8 @@
// blumshub.h - originally written and placed in the public domain by Wei Dai // blumshub.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile blumshub.h /// \headerfile blumshub.h
//! \brief Classes for Blum Blum Shub generator /// \brief Classes for Blum Blum Shub generator
#ifndef CRYPTOPP_BLUMSHUB_H #ifndef CRYPTOPP_BLUMSHUB_H
#define CRYPTOPP_BLUMSHUB_H #define CRYPTOPP_BLUMSHUB_H
@ -13,7 +13,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! BlumBlumShub without factorization of the modulus /// BlumBlumShub without factorization of the modulus
class PublicBlumBlumShub : public RandomNumberGenerator, class PublicBlumBlumShub : public RandomNumberGenerator,
public StreamTransformation public StreamTransformation
{ {
@ -36,7 +36,7 @@ protected:
word maxBits, bitsLeft; word maxBits, bitsLeft;
}; };
//! BlumBlumShub with factorization of the modulus /// BlumBlumShub with factorization of the modulus
class BlumBlumShub : public PublicBlumBlumShub class BlumBlumShub : public PublicBlumBlumShub
{ {
public: public:

View File

@ -1,7 +1,7 @@
// camellia.h - originally written and placed in the public domain by Wei Dai // camellia.h - originally written and placed in the public domain by Wei Dai
//! \file camellia.h /// \file camellia.h
//! \brief Classes for the Camellia block cipher /// \brief Classes for the Camellia block cipher
#ifndef CRYPTOPP_CAMELLIA_H #ifndef CRYPTOPP_CAMELLIA_H
#define CRYPTOPP_CAMELLIA_H #define CRYPTOPP_CAMELLIA_H
@ -12,16 +12,16 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Camellia_Info /// \class Camellia_Info
//! \brief Camellia block cipher information /// \brief Camellia block cipher information
struct Camellia_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8> struct Camellia_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 8>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Camellia";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Camellia";}
}; };
//! \class Camellia /// \class Camellia
//! \brief Camellia block cipher /// \brief Camellia block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/Camellia">Camellia</a> /// \sa <a href="http://www.cryptopp.com/wiki/Camellia">Camellia</a>
class Camellia : public Camellia_Info, public BlockCipherDocumentation class Camellia : public Camellia_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Camellia_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<Camellia_Info>

44
cast.h
View File

@ -1,7 +1,7 @@
// cast.h - originally written and placed in the public domain by Wei Dai // cast.h - originally written and placed in the public domain by Wei Dai
//! \file cast.h /// \file cast.h
//! \brief Classes for the CAST-128 and CAST-256 block ciphers /// \brief Classes for the CAST-128 and CAST-256 block ciphers
#ifndef CRYPTOPP_CAST_H #ifndef CRYPTOPP_CAST_H
#define CRYPTOPP_CAST_H #define CRYPTOPP_CAST_H
@ -11,28 +11,28 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class CAST /// \class CAST
//! \brief CAST block cipher base /// \brief CAST block cipher base
class CAST class CAST
{ {
protected: protected:
static const word32 S[8][256]; static const word32 S[8][256];
}; };
//! \class CAST128_Info /// \class CAST128_Info
//! \brief CAST128 block cipher information /// \brief CAST128 block cipher information
struct CAST128_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 5, 16> struct CAST128_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 5, 16>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-128";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-128";}
}; };
//! \class CAST128 /// \class CAST128
//! \brief CAST128 block cipher /// \brief CAST128 block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/CAST-128">CAST-128</a> /// \sa <a href="http://www.cryptopp.com/wiki/CAST-128">CAST-128</a>
class CAST128 : public CAST128_Info, public BlockCipherDocumentation class CAST128 : public CAST128_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief CAST128 block cipher default operation /// \brief CAST128 block cipher default operation
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST128_Info> class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST128_Info>
{ {
public: public:
@ -43,16 +43,16 @@ class CAST128 : public CAST128_Info, public BlockCipherDocumentation
FixedSizeSecBlock<word32, 32> K; FixedSizeSecBlock<word32, 32> K;
}; };
//! \class Enc /// \class Enc
//! \brief CAST128 block cipher encryption operation /// \brief CAST128 block cipher encryption operation
class CRYPTOPP_NO_VTABLE Enc : public Base class CRYPTOPP_NO_VTABLE Enc : public Base
{ {
public: public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
}; };
//! \class Dec /// \class Dec
//! \brief CAST128 block cipher decryption operation /// \brief CAST128 block cipher decryption operation
class CRYPTOPP_NO_VTABLE Dec : public Base class CRYPTOPP_NO_VTABLE Dec : public Base
{ {
public: public:
@ -64,20 +64,20 @@ public:
typedef BlockCipherFinal<DECRYPTION, Dec> Decryption; typedef BlockCipherFinal<DECRYPTION, Dec> Decryption;
}; };
//! \class CAST256_Info /// \class CAST256_Info
//! \brief CAST256 block cipher information /// \brief CAST256 block cipher information
struct CAST256_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 4> struct CAST256_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 32, 4>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-256";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "CAST-256";}
}; };
//! \class CAST256 /// \class CAST256
//! \brief CAST256 block cipher /// \brief CAST256 block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/CAST-256">CAST-256</a> /// \sa <a href="http://www.cryptopp.com/wiki/CAST-256">CAST-256</a>
class CAST256 : public CAST256_Info, public BlockCipherDocumentation class CAST256 : public CAST256_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief CAST256 block cipher default operation /// \brief CAST256 block cipher default operation
class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST256_Info> class CRYPTOPP_NO_VTABLE Base : public CAST, public BlockCipherImpl<CAST256_Info>
{ {
public: public:

View File

@ -1,8 +1,8 @@
// cbcmac.h - originally written and placed in the public domain by Wei Dai // cbcmac.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile cbcmac.h /// \headerfile cbcmac.h
//! \brief Classes for CBC MAC /// \brief Classes for CBC MAC
#ifndef CRYPTOPP_CBCMAC_H #ifndef CRYPTOPP_CBCMAC_H
#define CRYPTOPP_CBCMAC_H #define CRYPTOPP_CBCMAC_H
@ -12,7 +12,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! _ /// _
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_MAC_Base : public MessageAuthenticationCode class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_MAC_Base : public MessageAuthenticationCode
{ {
public: public:
@ -32,7 +32,7 @@ private:
unsigned int m_counter; unsigned int m_counter;
}; };
//! <a href="http://www.weidai.com/scan-mirror/mac.html#CBC-MAC">CBC-MAC</a> /// <a href="http://www.weidai.com/scan-mirror/mac.html#CBC-MAC">CBC-MAC</a>
/*! Compatible with FIPS 113. T should be a class derived from BlockCipherDocumentation. /*! Compatible with FIPS 113. T should be a class derived from BlockCipherDocumentation.
Secure only for fixed length messages. For variable length messages use CMAC or DMAC. Secure only for fixed length messages. For variable length messages use CMAC or DMAC.
*/ */

46
ccm.h
View File

@ -1,8 +1,8 @@
// ccm.h - originally written and placed in the public domain by Wei Dai // ccm.h - originally written and placed in the public domain by Wei Dai
//! \file ccm.h /// \file ccm.h
//! \brief CCM block cipher mode of operation /// \brief CCM block cipher mode of operation
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
#ifndef CRYPTOPP_CCM_H #ifndef CRYPTOPP_CCM_H
#define CRYPTOPP_CCM_H #define CRYPTOPP_CCM_H
@ -12,10 +12,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class CCM_Base /// \class CCM_Base
//! \brief CCM block cipher base implementation /// \brief CCM block cipher base implementation
//! \details Base implementation of the AuthenticatedSymmetricCipher interface /// \details Base implementation of the AuthenticatedSymmetricCipher interface
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CCM_Base : public AuthenticatedSymmetricCipherBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CCM_Base : public AuthenticatedSymmetricCipherBase
{ {
public: public:
@ -81,12 +81,12 @@ protected:
CTR_Mode_ExternalCipher::Encryption m_ctr; CTR_Mode_ExternalCipher::Encryption m_ctr;
}; };
//! \class CCM_Final /// \class CCM_Final
//! \brief CCM block cipher final implementation /// \brief CCM block cipher final implementation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \tparam T_DefaultDigestSize default digest size, in bytes /// \tparam T_DefaultDigestSize default digest size, in bytes
//! \tparam T_IsEncryption direction in which to operate the cipher /// \tparam T_IsEncryption direction in which to operate the cipher
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher, int T_DefaultDigestSize, bool T_IsEncryption> template <class T_BlockCipher, int T_DefaultDigestSize, bool T_IsEncryption>
class CCM_Final : public CCM_Base class CCM_Final : public CCM_Base
{ {
@ -102,16 +102,16 @@ private:
typename T_BlockCipher::Encryption m_cipher; typename T_BlockCipher::Encryption m_cipher;
}; };
//! \class CCM /// \class CCM
//! \brief CCM block cipher mode of operation /// \brief CCM block cipher mode of operation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \tparam T_DefaultDigestSize default digest size, in bytes /// \tparam T_DefaultDigestSize default digest size, in bytes
//! \details \p CCM provides the \p Encryption and \p Decryption typedef. See GCM_Base /// \details \p CCM provides the \p Encryption and \p Decryption typedef. See GCM_Base
//! and GCM_Final for the AuthenticatedSymmetricCipher implementation. /// and GCM_Final for the AuthenticatedSymmetricCipher implementation.
//! \sa <a href="http://www.cryptopp.com/wiki/CCM_Mode">CCM Mode</a> and /// \sa <a href="http://www.cryptopp.com/wiki/CCM_Mode">CCM Mode</a> and
//! <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher, int T_DefaultDigestSize = 16> template <class T_BlockCipher, int T_DefaultDigestSize = 16>
struct CCM : public AuthenticatedSymmetricCipherDocumentation struct CCM : public AuthenticatedSymmetricCipherDocumentation
{ {

View File

@ -2,13 +2,13 @@
// Based on Wei Dai's Salsa20 and Bernstein's reference ChaCha // Based on Wei Dai's Salsa20 and Bernstein's reference ChaCha
// family implementation at http://cr.yp.to/chacha.html. // family implementation at http://cr.yp.to/chacha.html.
//! \file chacha.h /// \file chacha.h
//! \brief Classes for ChaCha8, ChaCha12 and ChaCha20 stream ciphers /// \brief Classes for ChaCha8, ChaCha12 and ChaCha20 stream ciphers
//! \details Crypto++ provides Bernstein and ECRYPT's ChaCha from <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, /// \details Crypto++ provides Bernstein and ECRYPT's ChaCha from <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha,
//! a variant of Salsa20</a> (2008.01.28). Bernstein's implementation is _slightly_ different from the TLS working group's /// a variant of Salsa20</a> (2008.01.28). Bernstein's implementation is _slightly_ different from the TLS working group's
//! implementation for cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>, /// implementation for cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
//! <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>. /// <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
#ifndef CRYPTOPP_CHACHA_H #ifndef CRYPTOPP_CHACHA_H
#define CRYPTOPP_CHACHA_H #define CRYPTOPP_CHACHA_H
@ -18,9 +18,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ChaCha_Info /// \class ChaCha_Info
//! \brief ChaCha stream cipher information /// \brief ChaCha stream cipher information
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <unsigned int R> template <unsigned int R>
struct ChaCha_Info : public VariableKeyLength<32, 16, 32, 16, SimpleKeyingInterface::UNIQUE_IV, 8>, public FixedRounds<R> struct ChaCha_Info : public VariableKeyLength<32, 16, 32, 16, SimpleKeyingInterface::UNIQUE_IV, 8>, public FixedRounds<R>
{ {
@ -29,9 +29,9 @@ struct ChaCha_Info : public VariableKeyLength<32, 16, 32, 16, SimpleKeyingInterf
} }
}; };
//! \class ChaCha_Policy /// \class ChaCha_Policy
//! \brief ChaCha stream cipher implementation /// \brief ChaCha stream cipher implementation
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <unsigned int R> template <unsigned int R>
class CRYPTOPP_NO_VTABLE ChaCha_Policy : public AdditiveCipherConcretePolicy<word32, 16> class CRYPTOPP_NO_VTABLE ChaCha_Policy : public AdditiveCipherConcretePolicy<word32, 16>
{ {
@ -49,36 +49,36 @@ protected:
FixedSizeAlignedSecBlock<word32, 16> m_state; FixedSizeAlignedSecBlock<word32, 16> m_state;
}; };
//! \class ChaCha8 /// \class ChaCha8
//! \brief ChaCha8 stream cipher /// \brief ChaCha8 stream cipher
//! \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28). /// \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28).
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
struct ChaCha8 : public ChaCha_Info<8>, public SymmetricCipherDocumentation struct ChaCha8 : public ChaCha_Info<8>, public SymmetricCipherDocumentation
{ {
typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<8>, AdditiveCipherTemplate<> >, ChaCha_Info<8> > Encryption; typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<8>, AdditiveCipherTemplate<> >, ChaCha_Info<8> > Encryption;
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class ChaCha12 /// \class ChaCha12
//! \brief ChaCha12 stream cipher /// \brief ChaCha12 stream cipher
//! \details Bernstein and ECRYPT's ChaCha is _slightly_ different from the TLS working group's implementation for /// \details Bernstein and ECRYPT's ChaCha is _slightly_ different from the TLS working group's implementation for
//! cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>, /// cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
//! <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>. /// <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>.
//! \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28). /// \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28).
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
struct ChaCha12 : public ChaCha_Info<12>, public SymmetricCipherDocumentation struct ChaCha12 : public ChaCha_Info<12>, public SymmetricCipherDocumentation
{ {
typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<12>, AdditiveCipherTemplate<> >, ChaCha_Info<12> > Encryption; typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<12>, AdditiveCipherTemplate<> >, ChaCha_Info<12> > Encryption;
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class ChaCha20 /// \class ChaCha20
//! \brief ChaCha20 stream cipher /// \brief ChaCha20 stream cipher
//! \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28). /// \sa <a href="http://cr.yp.to/chacha/chacha-20080128.pdf">ChaCha, a variant of Salsa20</a> (2008.01.28).
//! \details Bernstein and ECRYPT's ChaCha is _slightly_ different from the TLS working group's implementation for /// \details Bernstein and ECRYPT's ChaCha is _slightly_ different from the TLS working group's implementation for
//! cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>, /// cipher suites <tt>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>,
//! <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>. /// <tt>TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256</tt>, and <tt>TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256</tt>.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
struct ChaCha20 : public ChaCha_Info<20>, public SymmetricCipherDocumentation struct ChaCha20 : public ChaCha_Info<20>, public SymmetricCipherDocumentation
{ {
typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<20>, AdditiveCipherTemplate<> >, ChaCha_Info<20> > Encryption; typedef SymmetricCipherFinal<ConcretePolicyHolder<ChaCha_Policy<20>, AdditiveCipherTemplate<> >, ChaCha_Info<20> > Encryption;

View File

@ -1,8 +1,8 @@
// channels.h - originally written and placed in the public domain by Wei Dai // channels.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile channels.h /// \headerfile channels.h
//! \brief Classes for multiple named channels /// \brief Classes for multiple named channels
#ifndef CRYPTOPP_CHANNELS_H #ifndef CRYPTOPP_CHANNELS_H
#define CRYPTOPP_CHANNELS_H #define CRYPTOPP_CHANNELS_H
@ -20,7 +20,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
#if 0 #if 0
//! Route input on default channel to different and/or multiple channels based on message sequence number /// Route input on default channel to different and/or multiple channels based on message sequence number
class MessageSwitch : public Sink class MessageSwitch : public Sink
{ {
public: public:
@ -93,7 +93,7 @@ protected:
ChannelRouteIterator(); ChannelRouteIterator();
}; };
//! Route input to different and/or multiple channels based on channel ID /// Route input to different and/or multiple channels based on channel ID
class CRYPTOPP_DLL ChannelSwitch : public Multichannel<Sink>, public ChannelSwitchTypedefs class CRYPTOPP_DLL ChannelSwitch : public Multichannel<Sink>, public ChannelSwitchTypedefs
{ {
public: public:

30
cmac.h
View File

@ -1,8 +1,8 @@
// cmac.h - originally written and placed in the public domain by Wei Dai // cmac.h - originally written and placed in the public domain by Wei Dai
//! \file cmac.h /// \file cmac.h
//! \brief Classes for CMAC message authentication code /// \brief Classes for CMAC message authentication code
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
#ifndef CRYPTOPP_CMAC_H #ifndef CRYPTOPP_CMAC_H
#define CRYPTOPP_CMAC_H #define CRYPTOPP_CMAC_H
@ -12,9 +12,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class CMAC_Base /// \class CMAC_Base
//! \brief CMAC base implementation /// \brief CMAC base implementation
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CMAC_Base : public MessageAuthenticationCode class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CMAC_Base : public MessageAuthenticationCode
{ {
public: public:
@ -38,20 +38,20 @@ protected:
unsigned int m_counter; unsigned int m_counter;
}; };
//! \brief CMAC message authentication code /// \brief CMAC message authentication code
//! \tparam T block cipher /// \tparam T block cipher
//! \details Template parameter T should be a class derived from BlockCipherDocumentation, for example AES, with a block size of 8, 16, or 32. /// \details Template parameter T should be a class derived from BlockCipherDocumentation, for example AES, with a block size of 8, 16, or 32.
//! \sa <a href="http://www.cryptolounge.org/wiki/CMAC">CMAC</a> /// \sa <a href="http://www.cryptolounge.org/wiki/CMAC">CMAC</a>
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T> template <class T>
class CMAC : public MessageAuthenticationCodeImpl<CMAC_Base, CMAC<T> >, public SameKeyLengthAs<T> class CMAC : public MessageAuthenticationCodeImpl<CMAC_Base, CMAC<T> >, public SameKeyLengthAs<T>
{ {
public: public:
//! \brief Construct a CMAC /// \brief Construct a CMAC
CMAC() {} CMAC() {}
//! \brief Construct a CMAC /// \brief Construct a CMAC
//! \param key the MAC key /// \param key the MAC key
//! \param length the key size, in bytes /// \param length the key size, in bytes
CMAC(const byte *key, size_t length=SameKeyLengthAs<T>::DEFAULT_KEYLENGTH) CMAC(const byte *key, size_t length=SameKeyLengthAs<T>::DEFAULT_KEYLENGTH)
{this->SetKey(key, length);} {this->SetKey(key, length);}

View File

@ -1,7 +1,7 @@
// config.h - originally written and placed in the public domain by Wei Dai // config.h - originally written and placed in the public domain by Wei Dai
//! \file config.h /// \file config.h
//! \brief Library configuration file /// \brief Library configuration file
#ifndef CRYPTOPP_CONFIG_H #ifndef CRYPTOPP_CONFIG_H
#define CRYPTOPP_CONFIG_H #define CRYPTOPP_CONFIG_H
@ -163,15 +163,15 @@
#ifdef CRYPTOPP_DOXYGEN_PROCESSING #ifdef CRYPTOPP_DOXYGEN_PROCESSING
// Document the namespce exists. Put it here before CryptoPP is undefined below. // Document the namespce exists. Put it here before CryptoPP is undefined below.
//! \namespace CryptoPP /// \namespace CryptoPP
//! \brief Crypto++ library namespace /// \brief Crypto++ library namespace
//! \details Nearly all classes are located in the CryptoPP namespace. Within /// \details Nearly all classes are located in the CryptoPP namespace. Within
//! the namespace, there are two additional namespaces. /// the namespace, there are two additional namespaces.
//! <ul> /// <ul>
//! <li>Name - namespace for names used with \p NameValuePairs and documented in argnames.h /// <li>Name - namespace for names used with \p NameValuePairs and documented in argnames.h
//! <li>Test - namespace for testing and benchmarks classes /// <li>Test - namespace for testing and benchmarks classes
//! <li>Weak - namespace for weak and wounded algorithms, like ARC4, MD5 and Pananma /// <li>Weak - namespace for weak and wounded algorithms, like ARC4, MD5 and Pananma
//! </ul> /// </ul>
namespace CryptoPP { } namespace CryptoPP { }
// Bring in the symbols fund in the weak namespace; and fold Weak1 into Weak // Bring in the symbols fund in the weak namespace; and fold Weak1 into Weak
# define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 # define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1

426
cpu.h
View File

@ -2,30 +2,30 @@
// updated for ARM and PowerPC by Jeffrey Walton. // updated for ARM and PowerPC by Jeffrey Walton.
// updated to split CPU_Query() and CPU_Probe() by Jeffrey Walton. // updated to split CPU_Query() and CPU_Probe() by Jeffrey Walton.
//! \file cpu.h /// \file cpu.h
//! \brief Functions for CPU features and intrinsics /// \brief Functions for CPU features and intrinsics
//! \details The CPU functions are used in IA-32, ARM and PowerPC code paths. The /// \details The CPU functions are used in IA-32, ARM and PowerPC code paths. The
//! functions provide cpu specific feature testing on IA-32, ARM and PowerPC machines. /// functions provide cpu specific feature testing on IA-32, ARM and PowerPC machines.
//! \details Feature detection uses CPUID on IA-32, like Intel and AMD. On other platforms /// \details Feature detection uses CPUID on IA-32, like Intel and AMD. On other platforms
//! a two-part strategy is used. First, the library attempts to *Query* the OS for a feature, /// a two-part strategy is used. First, the library attempts to *Query* the OS for a feature,
//! like using Linux getauxval() or android_getCpuFeatures(). If that fails, then *Probe* /// like using Linux getauxval() or android_getCpuFeatures(). If that fails, then *Probe*
//! the cpu executing an instruction and an observe a SIGILL if unsupported. The general /// the cpu executing an instruction and an observe a SIGILL if unsupported. The general
//! pattern used by the library is: /// pattern used by the library is:
//! <pre> /// <pre>
//! g_hasCRC32 = CPU_QueryCRC32() || CPU_ProbeCRC32(); /// g_hasCRC32 = CPU_QueryCRC32() || CPU_ProbeCRC32();
//! g_hasPMULL = CPU_QueryPMULL() || CPU_ProbePMULL(); /// g_hasPMULL = CPU_QueryPMULL() || CPU_ProbePMULL();
//! g_hasAES = CPU_QueryAES() || CPU_ProbeAES(); /// g_hasAES = CPU_QueryAES() || CPU_ProbeAES();
//! </pre> /// </pre>
//! \details Generally speaking, CPU_Query() is in the source file <tt>cpu.cpp</tt> because it /// \details Generally speaking, CPU_Query() is in the source file <tt>cpu.cpp</tt> because it
//! does not require special architectural flags. CPU_Probe() is in a source file that recieves /// does not require special architectural flags. CPU_Probe() is in a source file that recieves
//! architectural flags, like <tt>sse-simd.cpp</tt>, <tt>neon-simd.cpp</tt> and /// architectural flags, like <tt>sse-simd.cpp</tt>, <tt>neon-simd.cpp</tt> and
//! <tt>ppc-simd.cpp</tt>. For example, compiling <tt>neon-simd.cpp</tt> on an ARM64 machine will /// <tt>ppc-simd.cpp</tt>. For example, compiling <tt>neon-simd.cpp</tt> on an ARM64 machine will
//! have <tt>-march=armv8-a</tt> applied during a compile to make the instruction set architecture /// have <tt>-march=armv8-a</tt> applied during a compile to make the instruction set architecture
//! (ISA) available. /// (ISA) available.
//! \details The cpu probes are expensive when compared to a standard OS feature query. The library /// \details The cpu probes are expensive when compared to a standard OS feature query. The library
//! also avoids probes on Apple platforms because Apple's signal handling for SIGILLs appears to /// also avoids probes on Apple platforms because Apple's signal handling for SIGILLs appears to
//! corrupt memory. CPU_Probe() will unconditionally return false for Apple platforms. OpenSSL /// corrupt memory. CPU_Probe() will unconditionally return false for Apple platforms. OpenSSL
//! experienced the same problem and moved away from SIGILL probes on Apple. /// experienced the same problem and moved away from SIGILL probes on Apple.
#ifndef CRYPTOPP_CPU_H #ifndef CRYPTOPP_CPU_H
#define CRYPTOPP_CPU_H #define CRYPTOPP_CPU_H
@ -103,14 +103,14 @@ CRYPTOPP_DLL void CRYPTOPP_API DetectX86Features();
CRYPTOPP_DLL bool CRYPTOPP_API CpuId(word32 func, word32 subfunc, word32 output[4]); CRYPTOPP_DLL bool CRYPTOPP_API CpuId(word32 func, word32 subfunc, word32 output[4]);
#endif // CRYPTOPP_DOXYGEN_PROCESSING #endif // CRYPTOPP_DOXYGEN_PROCESSING
//! \name IA-32 CPU FEATURES /// \name IA-32 CPU FEATURES
//@{ //@{
//! \brief Determines SSE2 availability /// \brief Determines SSE2 availability
//! \returns true if SSE2 is determined to be available, false otherwise /// \returns true if SSE2 is determined to be available, false otherwise
//! \details MMX, SSE and SSE2 are core processor features for x86_64, and /// \details MMX, SSE and SSE2 are core processor features for x86_64, and
//! the function always returns true for the platform. /// the function always returns true for the platform.
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasSSE2() inline bool HasSSE2()
{ {
#if CRYPTOPP_BOOL_X64 #if CRYPTOPP_BOOL_X64
@ -122,10 +122,10 @@ inline bool HasSSE2()
#endif #endif
} }
//! \brief Determines SSSE3 availability /// \brief Determines SSSE3 availability
//! \returns true if SSSE3 is determined to be available, false otherwise /// \returns true if SSSE3 is determined to be available, false otherwise
//! \details HasSSSE3() is a runtime check performed using CPUID /// \details HasSSSE3() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasSSSE3() inline bool HasSSSE3()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -133,10 +133,10 @@ inline bool HasSSSE3()
return g_hasSSSE3; return g_hasSSSE3;
} }
//! \brief Determines SSE4.1 availability /// \brief Determines SSE4.1 availability
//! \returns true if SSE4.1 is determined to be available, false otherwise /// \returns true if SSE4.1 is determined to be available, false otherwise
//! \details HasSSE41() is a runtime check performed using CPUID /// \details HasSSE41() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasSSE41() inline bool HasSSE41()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -144,10 +144,10 @@ inline bool HasSSE41()
return g_hasSSE41; return g_hasSSE41;
} }
//! \brief Determines SSE4.2 availability /// \brief Determines SSE4.2 availability
//! \returns true if SSE4.2 is determined to be available, false otherwise /// \returns true if SSE4.2 is determined to be available, false otherwise
//! \details HasSSE42() is a runtime check performed using CPUID /// \details HasSSE42() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasSSE42() inline bool HasSSE42()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -155,10 +155,10 @@ inline bool HasSSE42()
return g_hasSSE42; return g_hasSSE42;
} }
//! \brief Determines AES-NI availability /// \brief Determines AES-NI availability
//! \returns true if AES-NI is determined to be available, false otherwise /// \returns true if AES-NI is determined to be available, false otherwise
//! \details HasAESNI() is a runtime check performed using CPUID /// \details HasAESNI() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasAESNI() inline bool HasAESNI()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -166,10 +166,10 @@ inline bool HasAESNI()
return g_hasAESNI; return g_hasAESNI;
} }
//! \brief Determines Carryless Multiply availability /// \brief Determines Carryless Multiply availability
//! \returns true if pclmulqdq is determined to be available, false otherwise /// \returns true if pclmulqdq is determined to be available, false otherwise
//! \details HasCLMUL() is a runtime check performed using CPUID /// \details HasCLMUL() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasCLMUL() inline bool HasCLMUL()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -177,10 +177,10 @@ inline bool HasCLMUL()
return g_hasCLMUL; return g_hasCLMUL;
} }
//! \brief Determines SHA availability /// \brief Determines SHA availability
//! \returns true if SHA is determined to be available, false otherwise /// \returns true if SHA is determined to be available, false otherwise
//! \details HasSHA() is a runtime check performed using CPUID /// \details HasSHA() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasSHA() inline bool HasSHA()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -188,10 +188,10 @@ inline bool HasSHA()
return g_hasSHA; return g_hasSHA;
} }
//! \brief Determines ADX availability /// \brief Determines ADX availability
//! \returns true if ADX is determined to be available, false otherwise /// \returns true if ADX is determined to be available, false otherwise
//! \details HasADX() is a runtime check performed using CPUID /// \details HasADX() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasADX() inline bool HasADX()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -199,10 +199,10 @@ inline bool HasADX()
return g_hasADX; return g_hasADX;
} }
//! \brief Determines if the CPU is an Intel P4 /// \brief Determines if the CPU is an Intel P4
//! \returns true if the CPU is a P4, false otherwise /// \returns true if the CPU is a P4, false otherwise
//! \details IsP4() is a runtime check performed using CPUID /// \details IsP4() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool IsP4() inline bool IsP4()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -210,10 +210,10 @@ inline bool IsP4()
return g_isP4; return g_isP4;
} }
//! \brief Determines RDRAND availability /// \brief Determines RDRAND availability
//! \returns true if RDRAND is determined to be available, false otherwise /// \returns true if RDRAND is determined to be available, false otherwise
//! \details HasRDRAND() is a runtime check performed using CPUID /// \details HasRDRAND() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasRDRAND() inline bool HasRDRAND()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -221,10 +221,10 @@ inline bool HasRDRAND()
return g_hasRDRAND; return g_hasRDRAND;
} }
//! \brief Determines RDSEED availability /// \brief Determines RDSEED availability
//! \returns true if RDSEED is determined to be available, false otherwise /// \returns true if RDSEED is determined to be available, false otherwise
//! \details HasRDSEED() is a runtime check performed using CPUID /// \details HasRDSEED() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasRDSEED() inline bool HasRDSEED()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -232,10 +232,10 @@ inline bool HasRDSEED()
return g_hasRDSEED; return g_hasRDSEED;
} }
//! \brief Determines Padlock RNG availability /// \brief Determines Padlock RNG availability
//! \returns true if VIA Padlock RNG is determined to be available, false otherwise /// \returns true if VIA Padlock RNG is determined to be available, false otherwise
//! \details HasPadlockRNG() is a runtime check performed using CPUID /// \details HasPadlockRNG() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasPadlockRNG() inline bool HasPadlockRNG()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -243,10 +243,10 @@ inline bool HasPadlockRNG()
return g_hasPadlockRNG; return g_hasPadlockRNG;
} }
//! \brief Determines Padlock ACE availability /// \brief Determines Padlock ACE availability
//! \returns true if VIA Padlock ACE is determined to be available, false otherwise /// \returns true if VIA Padlock ACE is determined to be available, false otherwise
//! \details HasPadlockACE() is a runtime check performed using CPUID /// \details HasPadlockACE() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasPadlockACE() inline bool HasPadlockACE()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -254,10 +254,10 @@ inline bool HasPadlockACE()
return g_hasPadlockACE; return g_hasPadlockACE;
} }
//! \brief Determines Padlock ACE2 availability /// \brief Determines Padlock ACE2 availability
//! \returns true if VIA Padlock ACE2 is determined to be available, false otherwise /// \returns true if VIA Padlock ACE2 is determined to be available, false otherwise
//! \details HasPadlockACE2() is a runtime check performed using CPUID /// \details HasPadlockACE2() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasPadlockACE2() inline bool HasPadlockACE2()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -265,10 +265,10 @@ inline bool HasPadlockACE2()
return g_hasPadlockACE2; return g_hasPadlockACE2;
} }
//! \brief Determines Padlock PHE availability /// \brief Determines Padlock PHE availability
//! \returns true if VIA Padlock PHE is determined to be available, false otherwise /// \returns true if VIA Padlock PHE is determined to be available, false otherwise
//! \details HasPadlockPHE() is a runtime check performed using CPUID /// \details HasPadlockPHE() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasPadlockPHE() inline bool HasPadlockPHE()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -276,10 +276,10 @@ inline bool HasPadlockPHE()
return g_hasPadlockPHE; return g_hasPadlockPHE;
} }
//! \brief Determines Padlock PMM availability /// \brief Determines Padlock PMM availability
//! \returns true if VIA Padlock PMM is determined to be available, false otherwise /// \returns true if VIA Padlock PMM is determined to be available, false otherwise
//! \details HasPadlockPMM() is a runtime check performed using CPUID /// \details HasPadlockPMM() is a runtime check performed using CPUID
//! \note This function is only available on Intel IA-32 platforms /// \note This function is only available on Intel IA-32 platforms
inline bool HasPadlockPMM() inline bool HasPadlockPMM()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -287,14 +287,14 @@ inline bool HasPadlockPMM()
return g_hasPadlockPMM; return g_hasPadlockPMM;
} }
//! \brief Provides the cache line size /// \brief Provides the cache line size
//! \returns lower bound on the size of a cache line in bytes, if available /// \returns lower bound on the size of a cache line in bytes, if available
//! \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it /// \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it
//! is available. If the value is not available at runtime, then 32 is returned for a 32-bit /// is available. If the value is not available at runtime, then 32 is returned for a 32-bit
//! processor and 64 is returned for a 64-bit processor. /// processor and 64 is returned for a 64-bit processor.
//! \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC /// \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC
//! and AIX also makes the value available to user space and it is also usually accurate. The /// and AIX also makes the value available to user space and it is also usually accurate. The
//! ARM processor equivalent is a privileged instruction, so a compile time value is returned. /// ARM processor equivalent is a privileged instruction, so a compile time value is returned.
inline int GetCacheLineSize() inline int GetCacheLineSize()
{ {
if (!g_x86DetectionDone) if (!g_x86DetectionDone)
@ -316,16 +316,16 @@ extern bool g_hasNEON, g_hasPMULL, g_hasCRC32, g_hasAES, g_hasSHA1, g_hasSHA2;
void CRYPTOPP_API DetectArmFeatures(); void CRYPTOPP_API DetectArmFeatures();
#endif // CRYPTOPP_DOXYGEN_PROCESSING #endif // CRYPTOPP_DOXYGEN_PROCESSING
//! \name ARM A-32, Aarch32 and AArch64 CPU FEATURES /// \name ARM A-32, Aarch32 and AArch64 CPU FEATURES
//@{ //@{
//! \brief Determine if an ARM processor has Advanced SIMD available /// \brief Determine if an ARM processor has Advanced SIMD available
//! \returns true if the hardware is capable of Advanced SIMD at runtime, false otherwise. /// \returns true if the hardware is capable of Advanced SIMD at runtime, false otherwise.
//! \details Advanced SIMD instructions are available under most ARMv7, Aarch32 and Aarch64. /// \details Advanced SIMD instructions are available under most ARMv7, Aarch32 and Aarch64.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mfpu=neon</tt> (32-bit) or <tt>-march=armv8-a</tt> /// need to compile with <tt>-mfpu=neon</tt> (32-bit) or <tt>-march=armv8-a</tt>
//! (64-bit). Also see ARM's <tt>__ARM_NEON</tt> preprocessor macro. /// (64-bit). Also see ARM's <tt>__ARM_NEON</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasNEON() inline bool HasNEON()
{ {
// ASIMD is a core feature on Aarch32 and Aarch64 like SSE2 is a core feature on x86_64 // ASIMD is a core feature on Aarch32 and Aarch64 like SSE2 is a core feature on x86_64
@ -338,13 +338,13 @@ inline bool HasNEON()
#endif #endif
} }
//! \brief Determine if an ARM processor provides Polynomial Multiplication /// \brief Determine if an ARM processor provides Polynomial Multiplication
//! \returns true if the hardware is capable of polynomial multiplications at runtime, false otherwise. /// \returns true if the hardware is capable of polynomial multiplications at runtime, false otherwise.
//! \details The multiplication instructions are available under Aarch32 and Aarch64. /// \details The multiplication instructions are available under Aarch32 and Aarch64.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires /// need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires
//! <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro. /// <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasPMULL() inline bool HasPMULL()
{ {
#if defined(__aarch32__) || defined(__aarch64__) #if defined(__aarch32__) || defined(__aarch64__)
@ -356,14 +356,14 @@ inline bool HasPMULL()
#endif #endif
} }
//! \brief Determine if an ARM processor has CRC32 available /// \brief Determine if an ARM processor has CRC32 available
//! \returns true if the hardware is capable of CRC32 at runtime, false otherwise. /// \returns true if the hardware is capable of CRC32 at runtime, false otherwise.
//! \details CRC32 instructions provide access to the processor's CRC-32 and CRC-32C instructions. /// \details CRC32 instructions provide access to the processor's CRC-32 and CRC-32C instructions.
//! They are provided by ARM C Language Extensions 2.0 (ACLE 2.0) and available under Aarch32 and Aarch64. /// They are provided by ARM C Language Extensions 2.0 (ACLE 2.0) and available under Aarch32 and Aarch64.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-march=armv8-a+crc</tt>; while Apple requires /// need to compile with <tt>-march=armv8-a+crc</tt>; while Apple requires
//! <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRC32</tt> preprocessor macro. /// <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRC32</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasCRC32() inline bool HasCRC32()
{ {
#if defined(__aarch32__) || defined(__aarch64__) #if defined(__aarch32__) || defined(__aarch64__)
@ -375,14 +375,14 @@ inline bool HasCRC32()
#endif #endif
} }
//! \brief Determine if an ARM processor has AES available /// \brief Determine if an ARM processor has AES available
//! \returns true if the hardware is capable of AES at runtime, false otherwise. /// \returns true if the hardware is capable of AES at runtime, false otherwise.
//! \details AES is part of the optional Crypto extensions on Aarch32 and Aarch64. They are /// \details AES is part of the optional Crypto extensions on Aarch32 and Aarch64. They are
//! accessed using ARM C Language Extensions 2.0 (ACLE 2.0). /// accessed using ARM C Language Extensions 2.0 (ACLE 2.0).
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires /// need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires
//! <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro. /// <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasAES() inline bool HasAES()
{ {
#if defined(__aarch32__) || defined(__aarch64__) #if defined(__aarch32__) || defined(__aarch64__)
@ -394,14 +394,14 @@ inline bool HasAES()
#endif #endif
} }
//! \brief Determine if an ARM processor has SHA1 available /// \brief Determine if an ARM processor has SHA1 available
//! \returns true if the hardware is capable of SHA1 at runtime, false otherwise. /// \returns true if the hardware is capable of SHA1 at runtime, false otherwise.
//! \details SHA1 is part of the optional Crypto extensions on Aarch32 and Aarch64. They are /// \details SHA1 is part of the optional Crypto extensions on Aarch32 and Aarch64. They are
//! accessed using ARM C Language Extensions 2.0 (ACLE 2.0). /// accessed using ARM C Language Extensions 2.0 (ACLE 2.0).
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires /// need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires
//! <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro. /// <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasSHA1() inline bool HasSHA1()
{ {
#if defined(__aarch32__) || defined(__aarch64__) #if defined(__aarch32__) || defined(__aarch64__)
@ -413,14 +413,14 @@ inline bool HasSHA1()
#endif #endif
} }
//! \brief Determine if an ARM processor has SHA2 available /// \brief Determine if an ARM processor has SHA2 available
//! \returns true if the hardware is capable of SHA2 at runtime, false otherwise. /// \returns true if the hardware is capable of SHA2 at runtime, false otherwise.
//! \details SHA2 is part of the optional Crypto extensions on Aarch32 and Aarch64. They are /// \details SHA2 is part of the optional Crypto extensions on Aarch32 and Aarch64. They are
//! accessed using ARM C Language Extensions 2.0 (ACLE 2.0). /// accessed using ARM C Language Extensions 2.0 (ACLE 2.0).
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires /// need to compile with <tt>-march=armv8-a+crypto</tt>; while Apple requires
//! <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro. /// <tt>-arch arm64</tt>. Also see ARM's <tt>__ARM_FEATURE_CRYPTO</tt> preprocessor macro.
//! \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms /// \note This function is only available on ARM-32, Aarch32 and Aarch64 platforms
inline bool HasSHA2() inline bool HasSHA2()
{ {
#if defined(__aarch32__) || defined(__aarch64__) #if defined(__aarch32__) || defined(__aarch64__)
@ -448,19 +448,19 @@ extern word32 g_cacheLineSize;
void CRYPTOPP_API DetectPowerpcFeatures(); void CRYPTOPP_API DetectPowerpcFeatures();
#endif // CRYPTOPP_DOXYGEN_PROCESSING #endif // CRYPTOPP_DOXYGEN_PROCESSING
//! \name POWERPC CPU FEATURES /// \name POWERPC CPU FEATURES
//@{ //@{
//! \brief Determine if a PowerPC processor has Altivec available /// \brief Determine if a PowerPC processor has Altivec available
//! \returns true if the hardware is capable of Altivec at runtime, false otherwise. /// \returns true if the hardware is capable of Altivec at runtime, false otherwise.
//! \details Altivec instructions are available under most modern PowerPCs. /// \details Altivec instructions are available under most modern PowerPCs.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power7</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power7</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr7 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro. /// <tt>-qarch=pwr7 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro.
//! \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned /// \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned
//! loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the /// loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the
//! GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>. /// GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasAltivec() inline bool HasAltivec()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -468,16 +468,16 @@ inline bool HasAltivec()
return g_hasAltivec; return g_hasAltivec;
} }
//! \brief Determine if a PowerPC processor has Power8 available /// \brief Determine if a PowerPC processor has Power8 available
//! \returns true if the hardware is capable of Power8 at runtime, false otherwise. /// \returns true if the hardware is capable of Power8 at runtime, false otherwise.
//! \details Altivec instructions are available under most modern PowerPCs. /// \details Altivec instructions are available under most modern PowerPCs.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro. /// <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro.
//! \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned /// \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned
//! loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the /// loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the
//! GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>. /// GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasPower7() inline bool HasPower7()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -485,16 +485,16 @@ inline bool HasPower7()
return g_hasPower7; return g_hasPower7;
} }
//! \brief Determine if a PowerPC processor has Power8 available /// \brief Determine if a PowerPC processor has Power8 available
//! \returns true if the hardware is capable of Power8 at runtime, false otherwise. /// \returns true if the hardware is capable of Power8 at runtime, false otherwise.
//! \details Altivec instructions are available under most modern PowerPCs. /// \details Altivec instructions are available under most modern PowerPCs.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro. /// <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>_ALTIVEC_</tt> preprocessor macro.
//! \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned /// \details Atilvec was first available on Power4 platforms. However Crypto++ releies on unaligned
//! loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the /// loads and stores which is a Power7 feature. If the platform lacks Power7 extensions, then the
//! GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>. /// GNUmakefile sets <tt>-DCRYPTOPP_DISABLE_ALTIVEC</tt>.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasPower8() inline bool HasPower8()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -502,13 +502,13 @@ inline bool HasPower8()
return g_hasPower8; return g_hasPower8;
} }
//! \brief Determine if a PowerPC processor has AES available /// \brief Determine if a PowerPC processor has AES available
//! \returns true if the hardware is capable of AES at runtime, false otherwise. /// \returns true if the hardware is capable of AES at runtime, false otherwise.
//! \details AES is part of the in-crypto extensions on Power8 and Power9. /// \details AES is part of the in-crypto extensions on Power8 and Power9.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro. /// <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasAES() inline bool HasAES()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -516,13 +516,13 @@ inline bool HasAES()
return g_hasAES; return g_hasAES;
} }
//! \brief Determine if a PowerPC processor has SHA256 available /// \brief Determine if a PowerPC processor has SHA256 available
//! \returns true if the hardware is capable of SHA256 at runtime, false otherwise. /// \returns true if the hardware is capable of SHA256 at runtime, false otherwise.
//! \details SHA is part of the in-crypto extensions on Power8 and Power9. /// \details SHA is part of the in-crypto extensions on Power8 and Power9.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro. /// <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasSHA256() inline bool HasSHA256()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -530,13 +530,13 @@ inline bool HasSHA256()
return g_hasSHA256; return g_hasSHA256;
} }
//! \brief Determine if a PowerPC processor has SHA512 available /// \brief Determine if a PowerPC processor has SHA512 available
//! \returns true if the hardware is capable of SHA512 at runtime, false otherwise. /// \returns true if the hardware is capable of SHA512 at runtime, false otherwise.
//! \details SHA is part of the in-crypto extensions on Power8 and Power9. /// \details SHA is part of the in-crypto extensions on Power8 and Power9.
//! \details Runtime support requires compile time support. When compiling with GCC, you may /// \details Runtime support requires compile time support. When compiling with GCC, you may
//! need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require /// need to compile with <tt>-mcpu=power8</tt>; while IBM XL C/C++ compilers require
//! <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro. /// <tt>-qarch=pwr8 -qaltivec</tt>. Also see PowerPC's <tt>__CRYPTO</tt> preprocessor macro.
//! \note This function is only available on PowerPC and PowerPC-64 platforms /// \note This function is only available on PowerPC and PowerPC-64 platforms
inline bool HasSHA512() inline bool HasSHA512()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -544,14 +544,14 @@ inline bool HasSHA512()
return g_hasSHA512; return g_hasSHA512;
} }
//! \brief Provides the cache line size /// \brief Provides the cache line size
//! \returns lower bound on the size of a cache line in bytes, if available /// \returns lower bound on the size of a cache line in bytes, if available
//! \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it /// \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it
//! is available. If the value is not available at runtime, then 32 is returned for a 32-bit /// is available. If the value is not available at runtime, then 32 is returned for a 32-bit
//! processor and 64 is returned for a 64-bit processor. /// processor and 64 is returned for a 64-bit processor.
//! \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC /// \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC
//! and AIX also makes the value available to user space and it is also usually accurate. The /// and AIX also makes the value available to user space and it is also usually accurate. The
//! ARM processor equivalent is a privileged instruction, so a compile time value is returned. /// ARM processor equivalent is a privileged instruction, so a compile time value is returned.
inline int GetCacheLineSize() inline int GetCacheLineSize()
{ {
if (!g_PowerpcDetectionDone) if (!g_PowerpcDetectionDone)
@ -567,14 +567,14 @@ inline int GetCacheLineSize()
// Non-Intel systems // Non-Intel systems
#if !(CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64) #if !(CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_PPC32 || CRYPTOPP_BOOL_PPC64)
//! \brief Provides the cache line size /// \brief Provides the cache line size
//! \returns lower bound on the size of a cache line in bytes, if available /// \returns lower bound on the size of a cache line in bytes, if available
//! \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it /// \details GetCacheLineSize() returns the lower bound on the size of a cache line, if it
//! is available. If the value is not available at runtime, then 32 is returned for a 32-bit /// is available. If the value is not available at runtime, then 32 is returned for a 32-bit
//! processor and 64 is returned for a 64-bit processor. /// processor and 64 is returned for a 64-bit processor.
//! \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC /// \details x86/x32/x64 uses CPUID to determine the value and it is usually accurate. PowerPC
//! and AIX also makes the value available to user space and it is also usually accurate. The /// and AIX also makes the value available to user space and it is also usually accurate. The
//! ARM processor equivalent is a privileged instruction, so a compile time value is returned. /// ARM processor equivalent is a privileged instruction, so a compile time value is returned.
inline int GetCacheLineSize() inline int GetCacheLineSize()
{ {
return CRYPTOPP_L1_CACHE_LINE_SIZE; return CRYPTOPP_L1_CACHE_LINE_SIZE;

16
crc.h
View File

@ -1,8 +1,8 @@
// crc.h - originally written and placed in the public domain by Wei Dai // crc.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile crc.h /// \headerfile crc.h
//! \brief Classes for CRC-32 and CRC-32C checksum algorithm /// \brief Classes for CRC-32 and CRC-32C checksum algorithm
#ifndef CRYPTOPP_CRC32_H #ifndef CRYPTOPP_CRC32_H
#define CRYPTOPP_CRC32_H #define CRYPTOPP_CRC32_H
@ -21,8 +21,8 @@ const word32 CRC32_NEGL = 0xffffffffL;
#define CRC32_SHIFTED(c) (c << 8) #define CRC32_SHIFTED(c) (c << 8)
#endif #endif
//! \brief CRC-32 Checksum Calculation /// \brief CRC-32 Checksum Calculation
//! \details Uses CRC polynomial 0xEDB88320 /// \details Uses CRC polynomial 0xEDB88320
class CRC32 : public HashTransformation class CRC32 : public HashTransformation
{ {
public: public:
@ -45,9 +45,9 @@ private:
word32 m_crc; word32 m_crc;
}; };
//! \brief CRC-32C Checksum Calculation /// \brief CRC-32C Checksum Calculation
//! \details Uses CRC polynomial 0x82F63B78 /// \details Uses CRC polynomial 0x82F63B78
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
class CRC32C : public HashTransformation class CRC32C : public HashTransformation
{ {
public: public:

View File

@ -330,28 +330,28 @@ void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransform
} }
} }
//! \class ClassNullRNG /// \class ClassNullRNG
//! \brief Random Number Generator that does not produce random numbers /// \brief Random Number Generator that does not produce random numbers
//! \details ClassNullRNG can be used for functions that require a RandomNumberGenerator /// \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
//! but don't actually use it. The class throws NotImplemented when a generation function is called. /// but don't actually use it. The class throws NotImplemented when a generation function is called.
//! \sa NullRNG() /// \sa NullRNG()
class ClassNullRNG : public RandomNumberGenerator class ClassNullRNG : public RandomNumberGenerator
{ {
public: public:
//! \brief The name of the generator /// \brief The name of the generator
//! \returns the string \a NullRNGs /// \returns the string \a NullRNGs
std::string AlgorithmName() const {return "NullRNG";} std::string AlgorithmName() const {return "NullRNG";}
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
byte GenerateByte () {} byte GenerateByte () {}
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
unsigned int GenerateBit () {} unsigned int GenerateBit () {}
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
word32 GenerateWord32 (word32 min, word32 max) {} word32 GenerateWord32 (word32 min, word32 max) {}
#endif #endif
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
void GenerateBlock(byte *output, size_t size) void GenerateBlock(byte *output, size_t size)
{ {
CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size); CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
@ -359,15 +359,15 @@ public:
} }
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {} void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
//! \brief An implementation that throws NotImplemented /// \brief An implementation that throws NotImplemented
void IncorporateEntropy (const byte *input, size_t length) {} void IncorporateEntropy (const byte *input, size_t length) {}
//! \brief An implementation that returns \p false /// \brief An implementation that returns \p false
bool CanIncorporateEntropy () const {} bool CanIncorporateEntropy () const {}
//! \brief An implementation that does nothing /// \brief An implementation that does nothing
void DiscardBytes (size_t n) {} void DiscardBytes (size_t n) {}
//! \brief An implementation that does nothing /// \brief An implementation that does nothing
void Shuffle (IT begin, IT end) {} void Shuffle (IT begin, IT end) {}
private: private:

3562
cryptlib.h

File diff suppressed because it is too large Load Diff

276
default.h
View File

@ -1,7 +1,7 @@
// default.h - originally written and placed in the public domain by Wei Dai // default.h - originally written and placed in the public domain by Wei Dai
//! \file default.h /// \file default.h
//! \brief Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC /// \brief Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
#ifndef CRYPTOPP_DEFAULT_H #ifndef CRYPTOPP_DEFAULT_H
#define CRYPTOPP_DEFAULT_H #define CRYPTOPP_DEFAULT_H
@ -16,22 +16,22 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Legacy block cipher for LegacyEncryptor, LegacyDecryptor, LegacyEncryptorWithMAC and LegacyDecryptorWithMAC /// \brief Legacy block cipher for LegacyEncryptor, LegacyDecryptor, LegacyEncryptorWithMAC and LegacyDecryptorWithMAC
typedef DES_EDE2 LegacyBlockCipher; typedef DES_EDE2 LegacyBlockCipher;
//! \brief Legacy hash for use with LegacyEncryptorWithMAC and LegacyDecryptorWithMAC /// \brief Legacy hash for use with LegacyEncryptorWithMAC and LegacyDecryptorWithMAC
typedef SHA1 LegacyHashModule; typedef SHA1 LegacyHashModule;
//! \brief Legacy HMAC for use withLegacyEncryptorWithMAC and LegacyDecryptorWithMAC /// \brief Legacy HMAC for use withLegacyEncryptorWithMAC and LegacyDecryptorWithMAC
typedef HMAC<LegacyHashModule> LegacyMAC; typedef HMAC<LegacyHashModule> LegacyMAC;
//! \brief Default block cipher for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC /// \brief Default block cipher for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
typedef AES DefaultBlockCipher; typedef AES DefaultBlockCipher;
//! \brief Default hash for use with DefaultEncryptorWithMAC and DefaultDecryptorWithMAC /// \brief Default hash for use with DefaultEncryptorWithMAC and DefaultDecryptorWithMAC
typedef SHA256 DefaultHashModule; typedef SHA256 DefaultHashModule;
//! \brief Default HMAC for use withDefaultEncryptorWithMAC and DefaultDecryptorWithMAC /// \brief Default HMAC for use withDefaultEncryptorWithMAC and DefaultDecryptorWithMAC
typedef HMAC<DefaultHashModule> DefaultMAC; typedef HMAC<DefaultHashModule> DefaultMAC;
//! \class DataDecryptorErr /// \class DataDecryptorErr
//! \brief Exception thrown when LegacyDecryptorWithMAC or DefaultDecryptorWithMAC decryption error is encountered /// \brief Exception thrown when LegacyDecryptorWithMAC or DefaultDecryptorWithMAC decryption error is encountered
class DataDecryptorErr : public Exception class DataDecryptorErr : public Exception
{ {
public: public:
@ -39,24 +39,24 @@ public:
: Exception(DATA_INTEGRITY_CHECK_FAILED, s) {} : Exception(DATA_INTEGRITY_CHECK_FAILED, s) {}
}; };
//! \class KeyBadErr /// \class KeyBadErr
//! \brief Exception thrown when a bad key is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC /// \brief Exception thrown when a bad key is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC
class KeyBadErr : public DataDecryptorErr class KeyBadErr : public DataDecryptorErr
{ {
public: KeyBadErr() public: KeyBadErr()
: DataDecryptorErr("DataDecryptor: cannot decrypt message with this passphrase") {} : DataDecryptorErr("DataDecryptor: cannot decrypt message with this passphrase") {}
}; };
//! \class MACBadErr /// \class MACBadErr
//! \brief Exception thrown when an incorrect MAC is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC /// \brief Exception thrown when an incorrect MAC is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC
class MACBadErr : public DataDecryptorErr class MACBadErr : public DataDecryptorErr
{ {
public: MACBadErr() public: MACBadErr()
: DataDecryptorErr("DataDecryptorWithMAC: MAC check failed") {} : DataDecryptorErr("DataDecryptorWithMAC: MAC check failed") {}
}; };
//! \class DataParametersInfo /// \class DataParametersInfo
//! \brief Algorithm information for password-based encryptors and decryptors /// \brief Algorithm information for password-based encryptors and decryptors
template <unsigned int BlockSize, unsigned int KeyLength, unsigned int DigestSize, unsigned int SaltSize, unsigned int Iterations> template <unsigned int BlockSize, unsigned int KeyLength, unsigned int DigestSize, unsigned int SaltSize, unsigned int Iterations>
struct DataParametersInfo struct DataParametersInfo
{ {
@ -70,15 +70,15 @@ struct DataParametersInfo
typedef DataParametersInfo<LegacyBlockCipher::BLOCKSIZE, LegacyBlockCipher::DEFAULT_KEYLENGTH, LegacyHashModule::DIGESTSIZE, 8, 200> LegacyParametersInfo; typedef DataParametersInfo<LegacyBlockCipher::BLOCKSIZE, LegacyBlockCipher::DEFAULT_KEYLENGTH, LegacyHashModule::DIGESTSIZE, 8, 200> LegacyParametersInfo;
typedef DataParametersInfo<DefaultBlockCipher::BLOCKSIZE, DefaultBlockCipher::DEFAULT_KEYLENGTH, DefaultHashModule::DIGESTSIZE, 8, 2500> DefaultParametersInfo; typedef DataParametersInfo<DefaultBlockCipher::BLOCKSIZE, DefaultBlockCipher::DEFAULT_KEYLENGTH, DefaultHashModule::DIGESTSIZE, 8, 2500> DefaultParametersInfo;
//! \class DataEncryptor /// \class DataEncryptor
//! \brief Password-based Encryptor /// \brief Password-based Encryptor
//! \tparam BC BlockCipher based class used for encryption /// \tparam BC BlockCipher based class used for encryption
//! \tparam H HashTransformation based class used for mashing /// \tparam H HashTransformation based class used for mashing
//! \tparam Info Constants used by the algorithms /// \tparam Info Constants used by the algorithms
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. /// Crypto++ 5.7 switched to AES and SHA256.
//! \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor /// \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
template <class BC, class H, class Info> template <class BC, class H, class Info>
class DataEncryptor : public ProxyFilter, public Info class DataEncryptor : public ProxyFilter, public Info
{ {
@ -89,15 +89,15 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE) CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE)
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS) CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS)
//! \brief Construct a DataEncryptor /// \brief Construct a DataEncryptor
//! \param passphrase a C-String password /// \param passphrase a C-String password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
DataEncryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR); DataEncryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR);
//! \brief Construct a DataEncryptor /// \brief Construct a DataEncryptor
//! \param passphrase a byte string password /// \param passphrase a byte string password
//! \param passphraseLength the length of the byte string password /// \param passphraseLength the length of the byte string password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
DataEncryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR); DataEncryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR);
protected: protected:
@ -109,15 +109,15 @@ private:
typename CBC_Mode<BC>::Encryption m_cipher; typename CBC_Mode<BC>::Encryption m_cipher;
}; };
//! \class DataDecryptor /// \class DataDecryptor
//! \brief Password-based Decryptor /// \brief Password-based Decryptor
//! \tparam BC BlockCipher based class used for encryption /// \tparam BC BlockCipher based class used for encryption
//! \tparam H HashTransformation based class used for mashing /// \tparam H HashTransformation based class used for mashing
//! \tparam Info Constants used by the algorithms /// \tparam Info Constants used by the algorithms
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. /// Crypto++ 5.7 switched to AES and SHA256.
//! \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor /// \sa DefaultEncryptor, DefaultDecryptor, LegacyEncryptor, LegacyDecryptor
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
template <class BC, class H, class Info> template <class BC, class H, class Info>
class DataDecryptor : public ProxyFilter, public Info class DataDecryptor : public ProxyFilter, public Info
{ {
@ -128,17 +128,17 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE) CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE)
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS) CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS)
//! \brief Constructs a DataDecryptor /// \brief Constructs a DataDecryptor
//! \param passphrase a C-String password /// \param passphrase a C-String password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \param throwException a flag specifiying whether an Exception should be thrown on error /// \param throwException a flag specifiying whether an Exception should be thrown on error
DataDecryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true); DataDecryptor(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
//! \brief Constructs a DataDecryptor /// \brief Constructs a DataDecryptor
//! \param passphrase a byte string password /// \param passphrase a byte string password
//! \param passphraseLength the length of the byte string password /// \param passphraseLength the length of the byte string password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \param throwException a flag specifiying whether an Exception should be thrown on error /// \param throwException a flag specifiying whether an Exception should be thrown on error
DataDecryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true); DataDecryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
enum State {WAITING_FOR_KEYCHECK, KEY_GOOD, KEY_BAD}; enum State {WAITING_FOR_KEYCHECK, KEY_GOOD, KEY_BAD};
@ -160,22 +160,22 @@ private:
}; };
//! \class DataEncryptorWithMAC /// \class DataEncryptorWithMAC
//! \brief Password-based encryptor with MAC /// \brief Password-based encryptor with MAC
//! \tparam BC BlockCipher based class used for encryption /// \tparam BC BlockCipher based class used for encryption
//! \tparam H HashTransformation based class used for mashing /// \tparam H HashTransformation based class used for mashing
//! \tparam MAC HashTransformation based class used for authentication /// \tparam MAC HashTransformation based class used for authentication
//! \tparam Info Constants used by the algorithms /// \tparam Info Constants used by the algorithms
//! \details DataEncryptorWithMAC uses a non-standard mashup function called Mash() to derive key /// \details DataEncryptorWithMAC uses a non-standard mashup function called Mash() to derive key
//! bits from the password. /// bits from the password.
//! \details The purpose of the function Mash() is to take an arbitrary length input string and /// \details The purpose of the function Mash() is to take an arbitrary length input string and
//! *deterministically* produce an arbitrary length output string such that (1) it looks random, /// *deterministically* produce an arbitrary length output string such that (1) it looks random,
//! (2) no information about the input is deducible from it, and (3) it contains as much entropy /// (2) no information about the input is deducible from it, and (3) it contains as much entropy
//! as it can hold, or the amount of entropy in the input string, whichever is smaller. /// as it can hold, or the amount of entropy in the input string, whichever is smaller.
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. /// Crypto++ 5.7 switched to AES and SHA256.
//! \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC /// \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
template <class BC, class H, class MAC, class Info> template <class BC, class H, class MAC, class Info>
class DataEncryptorWithMAC : public ProxyFilter class DataEncryptorWithMAC : public ProxyFilter
{ {
@ -186,15 +186,15 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE) CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE)
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS) CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS)
//! \brief Constructs a DataEncryptorWithMAC /// \brief Constructs a DataEncryptorWithMAC
//! \param passphrase a C-String password /// \param passphrase a C-String password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
DataEncryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR); DataEncryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR);
//! \brief Constructs a DataEncryptorWithMAC /// \brief Constructs a DataEncryptorWithMAC
//! \param passphrase a byte string password /// \param passphrase a byte string password
//! \param passphraseLength the length of the byte string password /// \param passphraseLength the length of the byte string password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
DataEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR); DataEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR);
protected: protected:
@ -206,22 +206,22 @@ private:
}; };
//! \class DataDecryptorWithMAC /// \class DataDecryptorWithMAC
//! \brief Password-based decryptor with MAC /// \brief Password-based decryptor with MAC
//! \tparam BC BlockCipher based class used for encryption /// \tparam BC BlockCipher based class used for encryption
//! \tparam H HashTransformation based class used for mashing /// \tparam H HashTransformation based class used for mashing
//! \tparam MAC HashTransformation based class used for authentication /// \tparam MAC HashTransformation based class used for authentication
//! \tparam Info Constants used by the algorithms /// \tparam Info Constants used by the algorithms
//! \details DataDecryptorWithMAC uses a non-standard mashup function called Mash() to derive key /// \details DataDecryptorWithMAC uses a non-standard mashup function called Mash() to derive key
//! bits from the password. /// bits from the password.
//! \details The purpose of the function Mash() is to take an arbitrary length input string and /// \details The purpose of the function Mash() is to take an arbitrary length input string and
//! *deterministically* produce an arbitrary length output string such that (1) it looks random, /// *deterministically* produce an arbitrary length output string such that (1) it looks random,
//! (2) no information about the input is deducible from it, and (3) it contains as much entropy /// (2) no information about the input is deducible from it, and (3) it contains as much entropy
//! as it can hold, or the amount of entropy in the input string, whichever is smaller. /// as it can hold, or the amount of entropy in the input string, whichever is smaller.
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. /// Crypto++ 5.7 switched to AES and SHA256.
//! \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC /// \sa DefaultEncryptorWithMAC, DefaultDecryptorWithMAC, LegacyDecryptorWithMAC, LegacyEncryptorWithMAC
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
template <class BC, class H, class MAC, class Info> template <class BC, class H, class MAC, class Info>
class DataDecryptorWithMAC : public ProxyFilter class DataDecryptorWithMAC : public ProxyFilter
{ {
@ -232,17 +232,17 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE) CRYPTOPP_CONSTANT(DIGESTSIZE = Info::DIGESTSIZE)
CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS) CRYPTOPP_CONSTANT(ITERATIONS = Info::ITERATIONS)
//! \brief Constructs a DataDecryptor /// \brief Constructs a DataDecryptor
//! \param passphrase a C-String password /// \param passphrase a C-String password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \param throwException a flag specifiying whether an Exception should be thrown on error /// \param throwException a flag specifiying whether an Exception should be thrown on error
DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true); DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
//! \brief Constructs a DataDecryptor /// \brief Constructs a DataDecryptor
//! \param passphrase a byte string password /// \param passphrase a byte string password
//! \param passphraseLength the length of the byte string password /// \param passphraseLength the length of the byte string password
//! \param attachment a BufferedTransformation to attach to this object /// \param attachment a BufferedTransformation to attach to this object
//! \param throwException a flag specifiying whether an Exception should be thrown on error /// \param throwException a flag specifiying whether an Exception should be thrown on error
DataDecryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true); DataDecryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment = NULLPTR, bool throwException=true);
typename DataDecryptor<BC,H,Info>::State CurrentState() const; typename DataDecryptor<BC,H,Info>::State CurrentState() const;
@ -259,53 +259,53 @@ private:
}; };
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \class LegacyEncryptor /// \class LegacyEncryptor
//! \brief Password-based encryptor (deprecated) /// \brief Password-based encryptor (deprecated)
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct LegacyEncryptor : public DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {}; struct LegacyEncryptor : public DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {};
//! \class LegacyDecryptor /// \class LegacyDecryptor
//! \brief Password-based decryptor (deprecated) /// \brief Password-based decryptor (deprecated)
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct LegacyDecryptor : public DataDecryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {}; struct LegacyDecryptor : public DataDecryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> {};
//! \class DefaultEncryptor /// \class DefaultEncryptor
//! \brief Password-based encryptor /// \brief Password-based encryptor
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct DefaultEncryptor : public DataEncryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {}; struct DefaultEncryptor : public DataEncryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {};
//! \class DefaultDecryptor /// \class DefaultDecryptor
//! \brief Password-based decryptor /// \brief Password-based decryptor
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct DefaultDecryptor : public DataDecryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {}; struct DefaultDecryptor : public DataDecryptor<DefaultBlockCipher,DefaultHashModule,DefaultParametersInfo> {};
//! \class LegacyEncryptorWithMAC /// \class LegacyEncryptorWithMAC
//! \brief Password-based encryptor with MAC (deprecated) /// \brief Password-based encryptor with MAC (deprecated)
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct LegacyEncryptorWithMAC : public DataEncryptorWithMAC<LegacyBlockCipher,LegacyHashModule,DefaultMAC,LegacyParametersInfo> {}; struct LegacyEncryptorWithMAC : public DataEncryptorWithMAC<LegacyBlockCipher,LegacyHashModule,DefaultMAC,LegacyParametersInfo> {};
//! \class LegacyDecryptorWithMAC /// \class LegacyDecryptorWithMAC
//! \brief Password-based decryptor with MAC (deprecated) /// \brief Password-based decryptor with MAC (deprecated)
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct LegacyDecryptorWithMAC : public DataDecryptorWithMAC<LegacyBlockCipher,LegacyHashModule,DefaultMAC,LegacyParametersInfo> {}; struct LegacyDecryptorWithMAC : public DataDecryptorWithMAC<LegacyBlockCipher,LegacyHashModule,DefaultMAC,LegacyParametersInfo> {};
//! \class DefaultEncryptorWithMAC /// \class DefaultEncryptorWithMAC
//! \brief Password-based encryptor with MAC /// \brief Password-based encryptor with MAC
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct DefaultEncryptorWithMAC : public DataEncryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {}; struct DefaultEncryptorWithMAC : public DataEncryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {};
//! \class DefaultDecryptorWithMAC /// \class DefaultDecryptorWithMAC
//! \brief Password-based decryptor with MAC /// \brief Password-based decryptor with MAC
//! \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1. /// \details Crypto++ 5.6.5 and earlier used the legacy algorithms, including DES_EDE2 and SHA1.
//! Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the /// Crypto++ 5.7 switched to AES and SHA256. The updated algorithms are available with the
//! <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes. /// <tt>Default*</tt> classes, and the old algorithms are available with the <tt>Legacy*</tt> classes.
struct DefaultDecryptorWithMAC : public DataDecryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {}; struct DefaultDecryptorWithMAC : public DataDecryptorWithMAC<DefaultBlockCipher,DefaultHashModule,DefaultMAC,DefaultParametersInfo> {};
#else #else
typedef DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> LegacyEncryptor; typedef DataEncryptor<LegacyBlockCipher,LegacyHashModule,LegacyParametersInfo> LegacyEncryptor;

82
des.h
View File

@ -1,7 +1,7 @@
// des.h - originally written and placed in the public domain by Wei Dai // des.h - originally written and placed in the public domain by Wei Dai
//! \file des.h /// \file des.h
//! \brief Classes for DES, 2-key Triple-DES, 3-key Triple-DES and DESX /// \brief Classes for DES, 2-key Triple-DES, 3-key Triple-DES and DESX
#ifndef CRYPTOPP_DES_H #ifndef CRYPTOPP_DES_H
#define CRYPTOPP_DES_H #define CRYPTOPP_DES_H
@ -11,8 +11,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class RawDES /// \class RawDES
//! \brief DES block cipher base class /// \brief DES block cipher base class
class CRYPTOPP_DLL RawDES class CRYPTOPP_DLL RawDES
{ {
public: public:
@ -25,25 +25,25 @@ protected:
FixedSizeSecBlock<word32, 32> k; FixedSizeSecBlock<word32, 32> k;
}; };
//! \class DES_Info /// \class DES_Info
//! \brief DES block cipher information /// \brief DES block cipher information
struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8> struct DES_Info : public FixedBlockSize<8>, public FixedKeyLength<8>
{ {
// disable DES in DLL version by not exporting this function // disable DES in DLL version by not exporting this function
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES";}
}; };
//! \class DES /// \class DES
//! \brief DES block cipher /// \brief DES block cipher
//! \details The DES implementation in Crypto++ ignores the parity bits /// \details The DES implementation in Crypto++ ignores the parity bits
//! (the least significant bits of each byte) in the key. However you can use CheckKeyParityBits() /// (the least significant bits of each byte) in the key. However you can use CheckKeyParityBits()
//! and CorrectKeyParityBits() to check or correct the parity bits if you wish. /// and CorrectKeyParityBits() to check or correct the parity bits if you wish.
//! \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES</a> /// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class DES : public DES_Info, public BlockCipherDocumentation class DES : public DES_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief DES block cipher default operation /// \brief DES block cipher default operation
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_Info>, public RawDES class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_Info>, public RawDES
{ {
public: public:
@ -52,30 +52,30 @@ class DES : public DES_Info, public BlockCipherDocumentation
}; };
public: public:
//! check DES key parity bits /// check DES key parity bits
static bool CheckKeyParityBits(const byte *key); static bool CheckKeyParityBits(const byte *key);
//! correct DES key parity bits /// correct DES key parity bits
static void CorrectKeyParityBits(byte *key); static void CorrectKeyParityBits(byte *key);
typedef BlockCipherFinal<ENCRYPTION, Base> Encryption; typedef BlockCipherFinal<ENCRYPTION, Base> Encryption;
typedef BlockCipherFinal<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
//! \class DES_EDE2_Info /// \class DES_EDE2_Info
//! \brief 2-key TripleDES block cipher information /// \brief 2-key TripleDES block cipher information
struct DES_EDE2_Info : public FixedBlockSize<8>, public FixedKeyLength<16> struct DES_EDE2_Info : public FixedBlockSize<8>, public FixedKeyLength<16>
{ {
CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE2";} CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE2";}
}; };
//! \class DES_EDE2 /// \class DES_EDE2
//! \brief 2-key TripleDES block cipher /// \brief 2-key TripleDES block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE2</a> /// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE2</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation class DES_EDE2 : public DES_EDE2_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief DES_EDE2 block cipher default operation /// \brief DES_EDE2 block cipher default operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE2_Info> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE2_Info>
{ {
public: public:
@ -91,21 +91,21 @@ public:
typedef BlockCipherFinal<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
//! \class DES_EDE3_Info /// \class DES_EDE3_Info
//! \brief 3-key TripleDES block cipher information /// \brief 3-key TripleDES block cipher information
struct DES_EDE3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> struct DES_EDE3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
{ {
CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE3";} CRYPTOPP_DLL static const char * CRYPTOPP_API StaticAlgorithmName() {return "DES-EDE3";}
}; };
//! \class DES_EDE3 /// \class DES_EDE3
//! \brief 3-key TripleDES block cipher /// \brief 3-key TripleDES block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE3</a> /// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-EDE3</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation class DES_EDE3 : public DES_EDE3_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief DES_EDE3 block cipher default operation /// \brief DES_EDE3 block cipher default operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE3_Info> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_EDE3_Info>
{ {
public: public:
@ -121,21 +121,21 @@ public:
typedef BlockCipherFinal<DECRYPTION, Base> Decryption; typedef BlockCipherFinal<DECRYPTION, Base> Decryption;
}; };
//! \class DES_XEX3_Info /// \class DES_XEX3_Info
//! \brief DESX block cipher information /// \brief DESX block cipher information
struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24> struct DES_XEX3_Info : public FixedBlockSize<8>, public FixedKeyLength<24>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES-XEX3";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "DES-XEX3";}
}; };
//! \class DES_XEX3 /// \class DES_XEX3
//! \brief DESX block cipher /// \brief DESX block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-XEX3</a>, AKA DESX /// \sa <a href="http://www.cryptopp.com/wiki/TripleDES">DES-XEX3</a>, AKA DESX
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation class DES_XEX3 : public DES_XEX3_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief DES_XEX3 block cipher default operation /// \brief DES_XEX3 block cipher default operation
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_XEX3_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<DES_XEX3_Info>
{ {
public: public:

286
dh.h
View File

@ -1,7 +1,7 @@
// dh.h - originally written and placed in the public domain by Wei Dai // dh.h - originally written and placed in the public domain by Wei Dai
//! \file dh.h /// \file dh.h
//! \brief Classes for Diffie-Hellman key exchange /// \brief Classes for Diffie-Hellman key exchange
#ifndef CRYPTOPP_DH_H #ifndef CRYPTOPP_DH_H
#define CRYPTOPP_DH_H #define CRYPTOPP_DH_H
@ -12,16 +12,16 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class DH_Domain /// \class DH_Domain
//! \brief Diffie-Hellman domain /// \brief Diffie-Hellman domain
//! \tparam GROUP_PARAMETERS group parameters /// \tparam GROUP_PARAMETERS group parameters
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \details A Diffie-Hellman domain is a set of parameters that must be shared /// \details A Diffie-Hellman domain is a set of parameters that must be shared
//! by two parties in a key agreement protocol, along with the algorithms /// by two parties in a key agreement protocol, along with the algorithms
//! for generating key pairs and deriving agreed values. /// for generating key pairs and deriving agreed values.
//! \details For COFACTOR_OPTION, see CofactorMultiplicationOption. /// \details For COFACTOR_OPTION, see CofactorMultiplicationOption.
//! \sa DL_SimpleKeyAgreementDomainBase /// \sa DL_SimpleKeyAgreementDomainBase
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption> template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption>
class DH_Domain : public DL_SimpleKeyAgreementDomainBase<typename GROUP_PARAMETERS::Element> class DH_Domain : public DL_SimpleKeyAgreementDomainBase<typename GROUP_PARAMETERS::Element>
{ {
@ -35,104 +35,104 @@ public:
virtual ~DH_Domain() {} virtual ~DH_Domain() {}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
DH_Domain() {} DH_Domain() {}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
//! \param params group parameters and options /// \param params group parameters and options
DH_Domain(const GroupParameters &params) DH_Domain(const GroupParameters &params)
: m_groupParameters(params) {} : m_groupParameters(params) {}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
//! \param bt BufferedTransformation with group parameters and options /// \param bt BufferedTransformation with group parameters and options
DH_Domain(BufferedTransformation &bt) DH_Domain(BufferedTransformation &bt)
{m_groupParameters.BERDecode(bt);} {m_groupParameters.BERDecode(bt);}
//! \brief Create a Diffie-Hellman domain /// \brief Create a Diffie-Hellman domain
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \param v1 RandomNumberGenerator derived class /// \param v1 RandomNumberGenerator derived class
//! \param v2 second parameter /// \param v2 second parameter
//! \details v1 and v2 are passed directly to the GROUP_PARAMETERS object. /// \details v1 and v2 are passed directly to the GROUP_PARAMETERS object.
template <class T2> template <class T2>
DH_Domain(RandomNumberGenerator &v1, const T2 &v2) DH_Domain(RandomNumberGenerator &v1, const T2 &v2)
{m_groupParameters.Initialize(v1, v2);} {m_groupParameters.Initialize(v1, v2);}
//! \brief Create a Diffie-Hellman domain /// \brief Create a Diffie-Hellman domain
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \param v1 RandomNumberGenerator derived class /// \param v1 RandomNumberGenerator derived class
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object.
template <class T2, class T3> template <class T2, class T3>
DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3) DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3)
{m_groupParameters.Initialize(v1, v2, v3);} {m_groupParameters.Initialize(v1, v2, v3);}
//! \brief Create a Diffie-Hellman domain /// \brief Create a Diffie-Hellman domain
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \tparam T4 template parameter used as a constructor parameter /// \tparam T4 template parameter used as a constructor parameter
//! \param v1 RandomNumberGenerator derived class /// \param v1 RandomNumberGenerator derived class
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \param v4 fourth parameter /// \param v4 fourth parameter
//! \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object.
template <class T2, class T3, class T4> template <class T2, class T3, class T4>
DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3, const T4 &v4) DH_Domain(RandomNumberGenerator &v1, const T2 &v2, const T3 &v3, const T4 &v4)
{m_groupParameters.Initialize(v1, v2, v3, v4);} {m_groupParameters.Initialize(v1, v2, v3, v4);}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \details v1 and v2 are passed directly to the GROUP_PARAMETERS object. /// \details v1 and v2 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2> template <class T1, class T2>
DH_Domain(const T1 &v1, const T2 &v2) DH_Domain(const T1 &v1, const T2 &v2)
{m_groupParameters.Initialize(v1, v2);} {m_groupParameters.Initialize(v1, v2);}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2, class T3> template <class T1, class T2, class T3>
DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3) DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3)
{m_groupParameters.Initialize(v1, v2, v3);} {m_groupParameters.Initialize(v1, v2, v3);}
//! \brief Construct a Diffie-Hellman domain /// \brief Construct a Diffie-Hellman domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \tparam T4 template parameter used as a constructor parameter /// \tparam T4 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \param v4 fourth parameter /// \param v4 fourth parameter
//! \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2, class T3, class T4> template <class T1, class T2, class T3, class T4>
DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4) DH_Domain(const T1 &v1, const T2 &v2, const T3 &v3, const T4 &v4)
{m_groupParameters.Initialize(v1, v2, v3, v4);} {m_groupParameters.Initialize(v1, v2, v3, v4);}
//! \brief Retrieves the group parameters for this domain /// \brief Retrieves the group parameters for this domain
//! \return the group parameters for this domain as a const reference /// \return the group parameters for this domain as a const reference
const GroupParameters & GetGroupParameters() const {return m_groupParameters;} const GroupParameters & GetGroupParameters() const {return m_groupParameters;}
//! \brief Retrieves the group parameters for this domain /// \brief Retrieves the group parameters for this domain
//! \return the group parameters for this domain as a non-const reference /// \return the group parameters for this domain as a non-const reference
GroupParameters & AccessGroupParameters() {return m_groupParameters;} GroupParameters & AccessGroupParameters() {return m_groupParameters;}
//! \brief Generate a public key from a private key in this domain /// \brief Generate a public key from a private key in this domain
//! \param rng RandomNumberGenerator derived class /// \param rng RandomNumberGenerator derived class
//! \param privateKey byte buffer with the previously generated private key /// \param privateKey byte buffer with the previously generated private key
//! \param publicKey byte buffer for the generated public key in this domain /// \param publicKey byte buffer for the generated public key in this domain
//! \details If using a FIPS 140-2 validated library on Windows, then this class will perform /// \details If using a FIPS 140-2 validated library on Windows, then this class will perform
//! a self test to ensure the key pair is pairwise consistent. Non-FIPS and non-Windows /// a self test to ensure the key pair is pairwise consistent. Non-FIPS and non-Windows
//! builds of the library do not provide FIPS validated cryptography, so the code should be /// builds of the library do not provide FIPS validated cryptography, so the code should be
//! removed by the optimizer. /// removed by the optimizer.
//! \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt> /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
Base::GeneratePublicKey(rng, privateKey, publicKey); Base::GeneratePublicKey(rng, privateKey, publicKey);
@ -169,45 +169,45 @@ private:
CRYPTOPP_DLL_TEMPLATE_CLASS DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>; CRYPTOPP_DLL_TEMPLATE_CLASS DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>;
//! \brief Diffie-Hellman in GF(p) /// \brief Diffie-Hellman in GF(p)
//! \details DH() class is a typedef of DH_Domain(). The documentation that follows /// \details DH() class is a typedef of DH_Domain(). The documentation that follows
//! does not exist. Rather the documentation was created in response to <a href="https://github.com/weidai11/cryptopp/issues/328">Issue /// does not exist. Rather the documentation was created in response to <a href="https://github.com/weidai11/cryptopp/issues/328">Issue
//! 328, Diffie-Hellman example code not compiling</a>. /// 328, Diffie-Hellman example code not compiling</a>.
//! \details Generally speaking, a DH() object is ephemeral and is intended to execute one instance of the Diffie-Hellman protocol. The /// \details Generally speaking, a DH() object is ephemeral and is intended to execute one instance of the Diffie-Hellman protocol. The
//! private and public key parts are not intended to be set or persisted. Rather, a new set of domain parameters are generated each /// private and public key parts are not intended to be set or persisted. Rather, a new set of domain parameters are generated each
//! time an object is created. /// time an object is created.
//! \details Once a DH() object is created, once can retrieve the ephemeral public key for the other party with code similar to the /// \details Once a DH() object is created, once can retrieve the ephemeral public key for the other party with code similar to the
//! following. /// following.
//! <pre> AutoSeededRandomPool prng; /// <pre> AutoSeededRandomPool prng;
//! Integer p, q, g; /// Integer p, q, g;
//! PrimeAndGenerator pg; /// PrimeAndGenerator pg;
//! ///
//! pg.Generate(1, prng, 512, 511); /// pg.Generate(1, prng, 512, 511);
//! p = pg.Prime(); /// p = pg.Prime();
//! q = pg.SubPrime(); /// q = pg.SubPrime();
//! g = pg.Generator(); /// g = pg.Generator();
//! ///
//! DH dh(p, q, g); /// DH dh(p, q, g);
//! SecByteBlock t1(dh.PrivateKeyLength()), t2(dh.PublicKeyLength()); /// SecByteBlock t1(dh.PrivateKeyLength()), t2(dh.PublicKeyLength());
//! dh.GenerateKeyPair(prng, t1, t2); /// dh.GenerateKeyPair(prng, t1, t2);
//! Integer k1(t1, t1.size()), k2(t2, t2.size()); /// Integer k1(t1, t1.size()), k2(t2, t2.size());
//! ///
//! cout << "Private key:\n"; /// cout << "Private key:\n";
//! cout << hex << k1 << endl; /// cout << hex << k1 << endl;
//! ///
//! cout << "Public key:\n"; /// cout << "Public key:\n";
//! cout << hex << k2 << endl;</pre> /// cout << hex << k2 << endl;</pre>
//! ///
//! \details Output of the program above will be similar to the following. /// \details Output of the program above will be similar to the following.
//! <pre> $ ./cryptest.exe /// <pre> $ ./cryptest.exe
//! Private key: /// Private key:
//! 72b45a42371545e9d4880f48589aefh /// 72b45a42371545e9d4880f48589aefh
//! Public key: /// Public key:
//! 45fdb13f97b1840626f0250cec1dba4a23b894100b51fb5d2dd13693d789948f8bfc88f9200014b2 /// 45fdb13f97b1840626f0250cec1dba4a23b894100b51fb5d2dd13693d789948f8bfc88f9200014b2
//! ba8dd8a6debc471c69ef1e2326c61184a2eca88ec866346bh</pre> /// ba8dd8a6debc471c69ef1e2326c61184a2eca88ec866346bh</pre>
//! \sa <a href="http://www.cryptopp.com/wiki/Diffie-Hellman">Diffie-Hellman on the Crypto++ wiki</a> and /// \sa <a href="http://www.cryptopp.com/wiki/Diffie-Hellman">Diffie-Hellman on the Crypto++ wiki</a> and
//! <a href="http://www.weidai.com/scan-mirror/ka.html#DH">Diffie-Hellman</a> in GF(p) with key validation /// <a href="http://www.weidai.com/scan-mirror/ka.html#DH">Diffie-Hellman</a> in GF(p) with key validation
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
struct DH : public DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime> struct DH : public DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>
{ {
@ -216,53 +216,53 @@ struct DH : public DH_Domain<DL_GroupParameters_GFP_DefaultSafePrime>
virtual ~DH() {} virtual ~DH() {}
//! \brief Create an uninitialized Diffie-Hellman object /// \brief Create an uninitialized Diffie-Hellman object
DH() : DH_Domain() {} DH() : DH_Domain() {}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param bt BufferedTransformation with group parameters and options /// \param bt BufferedTransformation with group parameters and options
DH(BufferedTransformation &bt) : DH_Domain(bt) {} DH(BufferedTransformation &bt) : DH_Domain(bt) {}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param params group parameters and options /// \param params group parameters and options
DH(const GroupParameters &params) : DH_Domain(params) {} DH(const GroupParameters &params) : DH_Domain(params) {}
//! \brief Create a Diffie-Hellman object /// \brief Create a Diffie-Hellman object
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param modulusBits the size of the modulus, in bits /// \param modulusBits the size of the modulus, in bits
//! \details This function overload of Initialize() creates a new Diffie-Hellman object because it /// \details This function overload of Initialize() creates a new Diffie-Hellman object because it
//! takes a RandomNumberGenerator() as a parameter. /// takes a RandomNumberGenerator() as a parameter.
DH(RandomNumberGenerator &rng, unsigned int modulusBits) : DH_Domain(rng, modulusBits) {} DH(RandomNumberGenerator &rng, unsigned int modulusBits) : DH_Domain(rng, modulusBits) {}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
DH(const Integer &p, const Integer &g) : DH_Domain(p, g) {} DH(const Integer &p, const Integer &g) : DH_Domain(p, g) {}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
DH(const Integer &p, const Integer &q, const Integer &g) : DH_Domain(p, q, g) {} DH(const Integer &p, const Integer &q, const Integer &g) : DH_Domain(p, q, g) {}
//! \brief Creates a Diffie-Hellman object /// \brief Creates a Diffie-Hellman object
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param modulusBits the size of the modulus, in bits /// \param modulusBits the size of the modulus, in bits
//! \details This function overload of Initialize() creates a new Diffie-Hellman object because it /// \details This function overload of Initialize() creates a new Diffie-Hellman object because it
//! takes a RandomNumberGenerator() as a parameter. /// takes a RandomNumberGenerator() as a parameter.
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits) void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
{AccessGroupParameters().Initialize(rng, modulusBits);} {AccessGroupParameters().Initialize(rng, modulusBits);}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
void Initialize(const Integer &p, const Integer &g) void Initialize(const Integer &p, const Integer &g)
{AccessGroupParameters().Initialize(p, g);} {AccessGroupParameters().Initialize(p, g);}
//! \brief Initialize a Diffie-Hellman object /// \brief Initialize a Diffie-Hellman object
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
void Initialize(const Integer &p, const Integer &q, const Integer &g) void Initialize(const Integer &p, const Integer &q, const Integer &g)
{AccessGroupParameters().Initialize(p, q, g);} {AccessGroupParameters().Initialize(p, q, g);}
}; };

22
dh2.h
View File

@ -1,7 +1,7 @@
// dh2.h - originally written and placed in the public domain by Wei Dai // dh2.h - originally written and placed in the public domain by Wei Dai
//! \file dh2.h /// \file dh2.h
//! \brief Classes for Unified Diffie-Hellman key exchange /// \brief Classes for Unified Diffie-Hellman key exchange
#ifndef CRYPTOPP_DH2_H #ifndef CRYPTOPP_DH2_H
#define CRYPTOPP_DH2_H #define CRYPTOPP_DH2_H
@ -10,22 +10,22 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class DH2 /// \class DH2
//! \brief Unified Diffie-Hellman in GF(p) /// \brief Unified Diffie-Hellman in GF(p)
//! \details A Diffie-Hellman domain is a set of parameters that must be shared /// \details A Diffie-Hellman domain is a set of parameters that must be shared
//! by two parties in a key agreement protocol, along with the algorithms /// by two parties in a key agreement protocol, along with the algorithms
//! for generating key pairs and deriving agreed values. /// for generating key pairs and deriving agreed values.
//! \sa AuthenticatedKeyAgreementDomain, <a href="http://www.weidai.com/scan-mirror/ka.html#DH2">Unified Diffie-Hellman</a> /// \sa AuthenticatedKeyAgreementDomain, <a href="http://www.weidai.com/scan-mirror/ka.html#DH2">Unified Diffie-Hellman</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class DH2 : public AuthenticatedKeyAgreementDomain class DH2 : public AuthenticatedKeyAgreementDomain
{ {
public: public:
virtual ~DH2() {} virtual ~DH2() {}
//! \brief Construct a DH2 /// \brief Construct a DH2
DH2(SimpleKeyAgreementDomain &domain) DH2(SimpleKeyAgreementDomain &domain)
: d1(domain), d2(domain) {} : d1(domain), d2(domain) {}
//! \brief Construct a DH2 /// \brief Construct a DH2
DH2(SimpleKeyAgreementDomain &staticDomain, SimpleKeyAgreementDomain &ephemeralDomain) DH2(SimpleKeyAgreementDomain &staticDomain, SimpleKeyAgreementDomain &ephemeralDomain)
: d1(staticDomain), d2(ephemeralDomain) {} : d1(staticDomain), d2(ephemeralDomain) {}

6
dll.h
View File

@ -1,8 +1,8 @@
// dll.h - originally written and placed in the public domain by Wei Dai // dll.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile dll.h /// \headerfile dll.h
//! \brief Functions and definitions required for building the FIPS-140 DLL on Windows /// \brief Functions and definitions required for building the FIPS-140 DLL on Windows
#ifndef CRYPTOPP_DLL_H #ifndef CRYPTOPP_DLL_H
#define CRYPTOPP_DLL_H #define CRYPTOPP_DLL_H

30
dmac.h
View File

@ -1,8 +1,8 @@
// dmac.h - originally written and placed in the public domain by Wei Dai // dmac.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile dmac.h /// \headerfile dmac.h
//! \brief Classes for DMAC message authentication code /// \brief Classes for DMAC message authentication code
#ifndef CRYPTOPP_DMAC_H #ifndef CRYPTOPP_DMAC_H
#define CRYPTOPP_DMAC_H #define CRYPTOPP_DMAC_H
@ -11,9 +11,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class DMAC_Base /// \class DMAC_Base
//! \brief DMAC message authentication code base class /// \brief DMAC message authentication code base class
//! \tparam T class derived from BlockCipherDocumentation /// \tparam T class derived from BlockCipherDocumentation
template <class T> template <class T>
class CRYPTOPP_NO_VTABLE DMAC_Base : public SameKeyLengthAs<T>, public MessageAuthenticationCode class CRYPTOPP_NO_VTABLE DMAC_Base : public SameKeyLengthAs<T>, public MessageAuthenticationCode
{ {
@ -39,21 +39,21 @@ private:
unsigned int m_counter; unsigned int m_counter;
}; };
//! \class DMAC /// \class DMAC
//! \brief DMAC message authentication code /// \brief DMAC message authentication code
//! \tparam T class derived from BlockCipherDocumentation /// \tparam T class derived from BlockCipherDocumentation
//! \sa <A HREF="https://eprint.iacr.org/1997/010">CBC MAC for Real-Time Data Sources (08.15.1997)</A> /// \sa <A HREF="https://eprint.iacr.org/1997/010">CBC MAC for Real-Time Data Sources (08.15.1997)</A>
//! by Erez Petrank and Charles Rackoff /// by Erez Petrank and Charles Rackoff
template <class T> template <class T>
class DMAC : public MessageAuthenticationCodeFinal<DMAC_Base<T> > class DMAC : public MessageAuthenticationCodeFinal<DMAC_Base<T> >
{ {
public: public:
//! \brief Construct a DMAC /// \brief Construct a DMAC
DMAC() {} DMAC() {}
//! \brief Construct a DMAC /// \brief Construct a DMAC
//! \param key a byte array used to key the cipher /// \param key a byte array used to key the cipher
//! \param length the size of the byte array, in bytes /// \param length the size of the byte array, in bytes
DMAC(const byte *key, size_t length=DMAC_Base<T>::DEFAULT_KEYLENGTH) DMAC(const byte *key, size_t length=DMAC_Base<T>::DEFAULT_KEYLENGTH)
{this->SetKey(key, length);} {this->SetKey(key, length);}
}; };

332
drbg.h
View File

@ -1,10 +1,10 @@
// drbg.h - written and placed in public domain by Jeffrey Walton. // drbg.h - written and placed in public domain by Jeffrey Walton.
//! \file drbg.h /// \file drbg.h
//! \brief Classes for NIST DRBGs from SP 800-90A /// \brief Classes for NIST DRBGs from SP 800-90A
//! \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation /// \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation
//! for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A> /// for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
#ifndef CRYPTOPP_NIST_DRBG_H #ifndef CRYPTOPP_NIST_DRBG_H
#define CRYPTOPP_NIST_DRBG_H #define CRYPTOPP_NIST_DRBG_H
@ -16,16 +16,16 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class NIST_DRBG /// \class NIST_DRBG
//! \brief Interface for NIST DRBGs from SP 800-90A /// \brief Interface for NIST DRBGs from SP 800-90A
//! \details NIST_DRBG is the base class interface for NIST DRBGs from SP 800-90A Rev 1 (June 2015) /// \details NIST_DRBG is the base class interface for NIST DRBGs from SP 800-90A Rev 1 (June 2015)
//! \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation /// \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation
//! for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A> /// for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class NIST_DRBG : public RandomNumberGenerator class NIST_DRBG : public RandomNumberGenerator
{ {
public: public:
//! \brief Exception thrown when a NIST DRBG encounters an error /// \brief Exception thrown when a NIST DRBG encounters an error
class Err : public Exception class Err : public Exception
{ {
public: public:
@ -36,105 +36,105 @@ public:
public: public:
virtual ~NIST_DRBG() {} virtual ~NIST_DRBG() {}
//! \brief Determines if a generator can accept additional entropy /// \brief Determines if a generator can accept additional entropy
//! \return true /// \return true
//! \details All NIST_DRBG return true /// \details All NIST_DRBG return true
virtual bool CanIncorporateEntropy() const {return true;} virtual bool CanIncorporateEntropy() const {return true;}
//! \brief Update RNG state with additional unpredictable values /// \brief Update RNG state with additional unpredictable values
//! \param input the entropy to add to the generator /// \param input the entropy to add to the generator
//! \param length the size of the input buffer /// \param length the size of the input buffer
//! \throws NIST_DRBG::Err if the generator is reseeded with insufficient entropy /// \throws NIST_DRBG::Err if the generator is reseeded with insufficient entropy
//! \details NIST instantiation and reseed requirements demand the generator is constructed /// \details NIST instantiation and reseed requirements demand the generator is constructed
//! with at least <tt>MINIMUM_ENTROPY</tt> entropy. The byte array for <tt>input</tt> must /// with at least <tt>MINIMUM_ENTROPY</tt> entropy. The byte array for <tt>input</tt> must
//! meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or /// meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or
//! SP 800-90C</A> requirements. /// SP 800-90C</A> requirements.
virtual void IncorporateEntropy(const byte *input, size_t length)=0; virtual void IncorporateEntropy(const byte *input, size_t length)=0;
//! \brief Update RNG state with additional unpredictable values /// \brief Update RNG state with additional unpredictable values
//! \param entropy the entropy to add to the generator /// \param entropy the entropy to add to the generator
//! \param entropyLength the size of the input buffer /// \param entropyLength the size of the input buffer
//! \param additional additional input to add to the generator /// \param additional additional input to add to the generator
//! \param additionaLength the size of the additional input buffer /// \param additionaLength the size of the additional input buffer
//! \throws NIST_DRBG::Err if the generator is reseeded with insufficient entropy /// \throws NIST_DRBG::Err if the generator is reseeded with insufficient entropy
//! \details IncorporateEntropy() is an overload provided to match NIST requirements. NIST /// \details IncorporateEntropy() is an overload provided to match NIST requirements. NIST
//! instantiation and reseed requirements demand the generator is constructed with at least /// instantiation and reseed requirements demand the generator is constructed with at least
//! <tt>MINIMUM_ENTROPY</tt> entropy. The byte array for <tt>entropy</tt> must meet /// <tt>MINIMUM_ENTROPY</tt> entropy. The byte array for <tt>entropy</tt> must meet
//! <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or /// <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or
//!! SP 800-90C</A> requirements. ///! SP 800-90C</A> requirements.
virtual void IncorporateEntropy(const byte *entropy, size_t entropyLength, const byte* additional, size_t additionaLength)=0; virtual void IncorporateEntropy(const byte *entropy, size_t entropyLength, const byte* additional, size_t additionaLength)=0;
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
//! \throws NIST_DRBG::Err if a reseed is required /// \throws NIST_DRBG::Err if a reseed is required
//! \throws NIST_DRBG::Err if the size exceeds <tt>MAXIMUM_BYTES_PER_REQUEST</tt> /// \throws NIST_DRBG::Err if the size exceeds <tt>MAXIMUM_BYTES_PER_REQUEST</tt>
virtual void GenerateBlock(byte *output, size_t size)=0; virtual void GenerateBlock(byte *output, size_t size)=0;
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param additional additional input to add to the generator /// \param additional additional input to add to the generator
//! \param additionaLength the size of the additional input buffer /// \param additionaLength the size of the additional input buffer
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
//! \throws NIST_DRBG::Err if a reseed is required /// \throws NIST_DRBG::Err if a reseed is required
//! \throws NIST_DRBG::Err if the size exceeds <tt>MAXIMUM_BYTES_PER_REQUEST</tt> /// \throws NIST_DRBG::Err if the size exceeds <tt>MAXIMUM_BYTES_PER_REQUEST</tt>
//! \details GenerateBlock() is an overload provided to match NIST requirements. The byte /// \details GenerateBlock() is an overload provided to match NIST requirements. The byte
//! array for <tt>additional</tt> input is optional. If present the additional randomness /// array for <tt>additional</tt> input is optional. If present the additional randomness
//! is mixed before generating the output bytes. /// is mixed before generating the output bytes.
virtual void GenerateBlock(const byte* additional, size_t additionaLength, byte *output, size_t size)=0; virtual void GenerateBlock(const byte* additional, size_t additionaLength, byte *output, size_t size)=0;
//! \brief Provides the security strength /// \brief Provides the security strength
//! \returns The security strength of the generator, in bytes /// \returns The security strength of the generator, in bytes
//! \details The equivalent class constant is <tt>SECURITY_STRENGTH</tt> /// \details The equivalent class constant is <tt>SECURITY_STRENGTH</tt>
virtual unsigned int SecurityStrength() const=0; virtual unsigned int SecurityStrength() const=0;
//! \brief Provides the seed length /// \brief Provides the seed length
//! \returns The seed size of the generator, in bytes /// \returns The seed size of the generator, in bytes
//! \details The equivalent class constant is <tt>SEED_LENGTH</tt>. The size is /// \details The equivalent class constant is <tt>SEED_LENGTH</tt>. The size is
//! used to maintain internal state of <tt>V</tt> and <tt>C</tt>. /// used to maintain internal state of <tt>V</tt> and <tt>C</tt>.
virtual unsigned int SeedLength() const=0; virtual unsigned int SeedLength() const=0;
//! \brief Provides the minimum entropy size /// \brief Provides the minimum entropy size
//! \returns The minimum entropy size required by the generator, in bytes /// \returns The minimum entropy size required by the generator, in bytes
//! \details The equivalent class constant is <tt>MINIMUM_ENTROPY</tt>. All NIST DRBGs must /// \details The equivalent class constant is <tt>MINIMUM_ENTROPY</tt>. All NIST DRBGs must
//! be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy. The bytes must /// be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy. The bytes must
//! meet <A HREF="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or /// meet <A HREF="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or
//! SP 800-90C</A> requirements. /// SP 800-90C</A> requirements.
virtual unsigned int MinEntropyLength() const=0; virtual unsigned int MinEntropyLength() const=0;
//! \brief Provides the maximum entropy size /// \brief Provides the maximum entropy size
//! \returns The maximum entropy size that can be consumed by the generator, in bytes /// \returns The maximum entropy size that can be consumed by the generator, in bytes
//! \details The equivalent class constant is <tt>MAXIMUM_ENTROPY</tt>. The bytes must /// \details The equivalent class constant is <tt>MAXIMUM_ENTROPY</tt>. The bytes must
//! meet <A HREF="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or /// meet <A HREF="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or
//! SP 800-90C</A> requirements. <tt>MAXIMUM_ENTROPY</tt> has been reduced from /// SP 800-90C</A> requirements. <tt>MAXIMUM_ENTROPY</tt> has been reduced from
//! 2<sup>35</sup> to <tt>INT_MAX</tt> to fit the underlying C++ datatype. /// 2<sup>35</sup> to <tt>INT_MAX</tt> to fit the underlying C++ datatype.
virtual unsigned int MaxEntropyLength() const=0; virtual unsigned int MaxEntropyLength() const=0;
//! \brief Provides the minimum nonce size /// \brief Provides the minimum nonce size
//! \returns The minimum nonce size recommended for the generator, in bytes /// \returns The minimum nonce size recommended for the generator, in bytes
//! \details The equivalent class constant is <tt>MINIMUM_NONCE</tt>. If a nonce is not /// \details The equivalent class constant is <tt>MINIMUM_NONCE</tt>. If a nonce is not
//! required then <tt>MINIMUM_NONCE</tt> is 0. <tt>Hash_DRBG</tt> does not require a /// required then <tt>MINIMUM_NONCE</tt> is 0. <tt>Hash_DRBG</tt> does not require a
//! nonce, while <tt>HMAC_DRBG</tt> and <tt>CTR_DRBG</tt> require a nonce. /// nonce, while <tt>HMAC_DRBG</tt> and <tt>CTR_DRBG</tt> require a nonce.
virtual unsigned int MinNonceLength() const=0; virtual unsigned int MinNonceLength() const=0;
//! \brief Provides the maximum nonce size /// \brief Provides the maximum nonce size
//! \returns The maximum nonce that can be consumed by the generator, in bytes /// \returns The maximum nonce that can be consumed by the generator, in bytes
//! \details The equivalent class constant is <tt>MAXIMUM_NONCE</tt>. <tt>MAXIMUM_NONCE</tt> /// \details The equivalent class constant is <tt>MAXIMUM_NONCE</tt>. <tt>MAXIMUM_NONCE</tt>
//! has been reduced from 2<sup>35</sup> to <tt>INT_MAX</tt> to fit the underlying C++ datatype. /// has been reduced from 2<sup>35</sup> to <tt>INT_MAX</tt> to fit the underlying C++ datatype.
//! If a nonce is not required then <tt>MINIMUM_NONCE</tt> is 0. <tt>Hash_DRBG</tt> does not /// If a nonce is not required then <tt>MINIMUM_NONCE</tt> is 0. <tt>Hash_DRBG</tt> does not
//! require a nonce, while <tt>HMAC_DRBG</tt> and <tt>CTR_DRBG</tt> require a nonce. /// require a nonce, while <tt>HMAC_DRBG</tt> and <tt>CTR_DRBG</tt> require a nonce.
virtual unsigned int MaxNonceLength() const=0; virtual unsigned int MaxNonceLength() const=0;
//! \brief Provides the maximum size of a request to GenerateBlock /// \brief Provides the maximum size of a request to GenerateBlock
//! \returns The the maximum size of a request to GenerateBlock(), in bytes /// \returns The the maximum size of a request to GenerateBlock(), in bytes
//! \details The equivalent class constant is <tt>MAXIMUM_BYTES_PER_REQUEST</tt> /// \details The equivalent class constant is <tt>MAXIMUM_BYTES_PER_REQUEST</tt>
virtual unsigned int MaxBytesPerRequest() const=0; virtual unsigned int MaxBytesPerRequest() const=0;
//! \brief Provides the maximum number of requests before a reseed /// \brief Provides the maximum number of requests before a reseed
//! \returns The the maximum number of requests before a reseed, in bytes /// \returns The the maximum number of requests before a reseed, in bytes
//! \details The equivalent class constant is <tt>MAXIMUM_REQUESTS_BEFORE_RESEED</tt>. /// \details The equivalent class constant is <tt>MAXIMUM_REQUESTS_BEFORE_RESEED</tt>.
//! <tt>MAXIMUM_REQUESTS_BEFORE_RESEED</tt> has been reduced from 2<sup>48</sup> to <tt>INT_MAX</tt> /// <tt>MAXIMUM_REQUESTS_BEFORE_RESEED</tt> has been reduced from 2<sup>48</sup> to <tt>INT_MAX</tt>
//! to fit the underlying C++ datatype. /// to fit the underlying C++ datatype.
virtual unsigned int MaxRequestBeforeReseed() const=0; virtual unsigned int MaxRequestBeforeReseed() const=0;
protected: protected:
@ -146,21 +146,21 @@ protected:
// ************************************************************* // *************************************************************
//! \class Hash_DRBG /// \class Hash_DRBG
//! \tparam HASH NIST approved hash derived from HashTransformation /// \tparam HASH NIST approved hash derived from HashTransformation
//! \tparam STRENGTH security strength, in bytes /// \tparam STRENGTH security strength, in bytes
//! \tparam SEEDLENGTH seed length, in bytes /// \tparam SEEDLENGTH seed length, in bytes
//! \brief Hash_DRBG from SP 800-90A Rev 1 (June 2015) /// \brief Hash_DRBG from SP 800-90A Rev 1 (June 2015)
//! \details The NIST Hash DRBG is instantiated with a number of parameters. Two of the parameters, /// \details The NIST Hash DRBG is instantiated with a number of parameters. Two of the parameters,
//! Security Strength and Seed Length, depend on the hash and are specified as template parameters. /// Security Strength and Seed Length, depend on the hash and are specified as template parameters.
//! The remaining parameters are included in the class. The parameters and their values are listed /// The remaining parameters are included in the class. The parameters and their values are listed
//! in NIST SP 800-90A Rev. 1, Table 2: Definitions for Hash-Based DRBG Mechanisms (p.38). /// in NIST SP 800-90A Rev. 1, Table 2: Definitions for Hash-Based DRBG Mechanisms (p.38).
//! \details Some parameters have been reduce to fit C++ datatypes. For example, NIST allows upto /// \details Some parameters have been reduce to fit C++ datatypes. For example, NIST allows upto
//! 2<sup>48</sup> requests before a reseed. However, Hash_DRBG limits it to <tt>INT_MAX</tt> due /// 2<sup>48</sup> requests before a reseed. However, Hash_DRBG limits it to <tt>INT_MAX</tt> due
//! to the limited data range of an int. /// to the limited data range of an int.
//! \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation /// \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation
//! for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A> /// for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <typename HASH=SHA256, unsigned int STRENGTH=128/8, unsigned int SEEDLENGTH=440/8> template <typename HASH=SHA256, unsigned int STRENGTH=128/8, unsigned int SEEDLENGTH=440/8>
class Hash_DRBG : public NIST_DRBG, public NotCopyable class Hash_DRBG : public NIST_DRBG, public NotCopyable
{ {
@ -180,31 +180,31 @@ public:
static std::string StaticAlgorithmName() { return std::string("Hash_DRBG(") + HASH::StaticAlgorithmName() + std::string(")"); } static std::string StaticAlgorithmName() { return std::string("Hash_DRBG(") + HASH::StaticAlgorithmName() + std::string(")"); }
//! \brief Construct a Hash DRBG /// \brief Construct a Hash DRBG
//! \param entropy the entropy to instantiate the generator /// \param entropy the entropy to instantiate the generator
//! \param entropyLength the size of the entropy buffer /// \param entropyLength the size of the entropy buffer
//! \param nonce additional input to instantiate the generator /// \param nonce additional input to instantiate the generator
//! \param nonceLength the size of the nonce buffer /// \param nonceLength the size of the nonce buffer
//! \param personalization additional input to instantiate the generator /// \param personalization additional input to instantiate the generator
//! \param personalizationLength the size of the personalization buffer /// \param personalizationLength the size of the personalization buffer
//! \throws NIST_DRBG::Err if the generator is instantiated with insufficient entropy /// \throws NIST_DRBG::Err if the generator is instantiated with insufficient entropy
//! \details All NIST DRBGs must be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy. /// \details All NIST DRBGs must be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy.
//! The byte array for <tt>entropy</tt> must meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST /// The byte array for <tt>entropy</tt> must meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST
//! SP 800-90B or SP 800-90C</A> requirements. /// SP 800-90B or SP 800-90C</A> requirements.
//! \details The <tt>nonce</tt> and <tt>personalization</tt> are optional byte arrays. If <tt>nonce</tt> is supplied, /// \details The <tt>nonce</tt> and <tt>personalization</tt> are optional byte arrays. If <tt>nonce</tt> is supplied,
//! then it should be at least <tt>MINIMUM_NONCE</tt> bytes of entropy. /// then it should be at least <tt>MINIMUM_NONCE</tt> bytes of entropy.
//! \details An example of instantiating a SHA256 generator is shown below. /// \details An example of instantiating a SHA256 generator is shown below.
//! The example provides more entropy than required for SHA256. The <tt>NonblockingRng</tt> meets the /// The example provides more entropy than required for SHA256. The <tt>NonblockingRng</tt> meets the
//! requirements of <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or SP 800-90C</A>. /// requirements of <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or SP 800-90C</A>.
//! RDRAND() and RDSEED() generators would work as well. /// RDRAND() and RDSEED() generators would work as well.
//! <pre> /// <pre>
//! SecByteBlock entropy(48), result(128); /// SecByteBlock entropy(48), result(128);
//! NonblockingRng prng; /// NonblockingRng prng;
//! RandomNumberSource rns(prng, entropy.size(), new ArraySink(entropy, entropy.size())); /// RandomNumberSource rns(prng, entropy.size(), new ArraySink(entropy, entropy.size()));
//! ///
//! Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy, 32, entropy+32, 16); /// Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy, 32, entropy+32, 16);
//! drbg.GenerateBlock(result, result.size()); /// drbg.GenerateBlock(result, result.size());
//! </pre> /// </pre>
Hash_DRBG(const byte* entropy=NULLPTR, size_t entropyLength=STRENGTH, const byte* nonce=NULLPTR, Hash_DRBG(const byte* entropy=NULLPTR, size_t entropyLength=STRENGTH, const byte* nonce=NULLPTR,
size_t nonceLength=0, const byte* personalization=NULLPTR, size_t personalizationLength=0) size_t nonceLength=0, const byte* personalization=NULLPTR, size_t personalizationLength=0)
: NIST_DRBG(), m_c(SEEDLENGTH), m_v(SEEDLENGTH), m_reseed(0) : NIST_DRBG(), m_c(SEEDLENGTH), m_v(SEEDLENGTH), m_reseed(0)
@ -261,20 +261,20 @@ private:
// ************************************************************* // *************************************************************
//! \class HMAC_DRBG /// \class HMAC_DRBG
//! \tparam HASH NIST approved hash derived from HashTransformation /// \tparam HASH NIST approved hash derived from HashTransformation
//! \tparam STRENGTH security strength, in bytes /// \tparam STRENGTH security strength, in bytes
//! \tparam SEEDLENGTH seed length, in bytes /// \tparam SEEDLENGTH seed length, in bytes
//! \brief HMAC_DRBG from SP 800-90A Rev 1 (June 2015) /// \brief HMAC_DRBG from SP 800-90A Rev 1 (June 2015)
//! \details The NIST HMAC DRBG is instantiated with a number of parameters. Two of the parameters, /// \details The NIST HMAC DRBG is instantiated with a number of parameters. Two of the parameters,
//! Security Strength and Seed Length, depend on the hash and are specified as template parameters. /// Security Strength and Seed Length, depend on the hash and are specified as template parameters.
//! The remaining parameters are included in the class. The parameters and their values are listed /// The remaining parameters are included in the class. The parameters and their values are listed
//! in NIST SP 800-90A Rev. 1, Table 2: Definitions for Hash-Based DRBG Mechanisms (p.38). /// in NIST SP 800-90A Rev. 1, Table 2: Definitions for Hash-Based DRBG Mechanisms (p.38).
//! \details Some parameters have been reduce to fit C++ datatypes. For example, NIST allows upto 2<sup>48</sup> requests /// \details Some parameters have been reduce to fit C++ datatypes. For example, NIST allows upto 2<sup>48</sup> requests
//! before a reseed. However, HMAC_DRBG limits it to <tt>INT_MAX</tt> due to the limited data range of an int. /// before a reseed. However, HMAC_DRBG limits it to <tt>INT_MAX</tt> due to the limited data range of an int.
//! \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation /// \sa <A HREF="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-90Ar1.pdf">Recommendation
//! for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A> /// for Random Number Generation Using Deterministic Random Bit Generators, Rev 1 (June 2015)</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <typename HASH=SHA256, unsigned int STRENGTH=128/8, unsigned int SEEDLENGTH=440/8> template <typename HASH=SHA256, unsigned int STRENGTH=128/8, unsigned int SEEDLENGTH=440/8>
class HMAC_DRBG : public NIST_DRBG, public NotCopyable class HMAC_DRBG : public NIST_DRBG, public NotCopyable
{ {
@ -294,31 +294,31 @@ public:
static std::string StaticAlgorithmName() { return std::string("HMAC_DRBG(") + HASH::StaticAlgorithmName() + std::string(")"); } static std::string StaticAlgorithmName() { return std::string("HMAC_DRBG(") + HASH::StaticAlgorithmName() + std::string(")"); }
//! \brief Construct a HMAC DRBG /// \brief Construct a HMAC DRBG
//! \param entropy the entropy to instantiate the generator /// \param entropy the entropy to instantiate the generator
//! \param entropyLength the size of the entropy buffer /// \param entropyLength the size of the entropy buffer
//! \param nonce additional input to instantiate the generator /// \param nonce additional input to instantiate the generator
//! \param nonceLength the size of the nonce buffer /// \param nonceLength the size of the nonce buffer
//! \param personalization additional input to instantiate the generator /// \param personalization additional input to instantiate the generator
//! \param personalizationLength the size of the personalization buffer /// \param personalizationLength the size of the personalization buffer
//! \throws NIST_DRBG::Err if the generator is instantiated with insufficient entropy /// \throws NIST_DRBG::Err if the generator is instantiated with insufficient entropy
//! \details All NIST DRBGs must be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy. /// \details All NIST DRBGs must be instaniated with at least <tt>MINIMUM_ENTROPY</tt> bytes of entropy.
//! The byte array for <tt>entropy</tt> must meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST /// The byte array for <tt>entropy</tt> must meet <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST
//! SP 800-90B or SP 800-90C</A> requirements. /// SP 800-90B or SP 800-90C</A> requirements.
//! \details The <tt>nonce</tt> and <tt>personalization</tt> are optional byte arrays. If <tt>nonce</tt> is supplied, /// \details The <tt>nonce</tt> and <tt>personalization</tt> are optional byte arrays. If <tt>nonce</tt> is supplied,
//! then it should be at least <tt>MINIMUM_NONCE</tt> bytes of entropy. /// then it should be at least <tt>MINIMUM_NONCE</tt> bytes of entropy.
//! \details An example of instantiating a SHA256 generator is shown below. /// \details An example of instantiating a SHA256 generator is shown below.
//! The example provides more entropy than required for SHA256. The <tt>NonblockingRng</tt> meets the /// The example provides more entropy than required for SHA256. The <tt>NonblockingRng</tt> meets the
//! requirements of <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or SP 800-90C</A>. /// requirements of <A HREF ="http://csrc.nist.gov/publications/PubsSPs.html">NIST SP 800-90B or SP 800-90C</A>.
//! RDRAND() and RDSEED() generators would work as well. /// RDRAND() and RDSEED() generators would work as well.
//! <pre> /// <pre>
//! SecByteBlock entropy(48), result(128); /// SecByteBlock entropy(48), result(128);
//! NonblockingRng prng; /// NonblockingRng prng;
//! RandomNumberSource rns(prng, entropy.size(), new ArraySink(entropy, entropy.size())); /// RandomNumberSource rns(prng, entropy.size(), new ArraySink(entropy, entropy.size()));
//! ///
//! HMAC_DRBG<SHA256, 128/8, 440/8> drbg(entropy, 32, entropy+32, 16); /// HMAC_DRBG<SHA256, 128/8, 440/8> drbg(entropy, 32, entropy+32, 16);
//! drbg.GenerateBlock(result, result.size()); /// drbg.GenerateBlock(result, result.size());
//! </pre> /// </pre>
HMAC_DRBG(const byte* entropy=NULLPTR, size_t entropyLength=STRENGTH, const byte* nonce=NULLPTR, HMAC_DRBG(const byte* entropy=NULLPTR, size_t entropyLength=STRENGTH, const byte* nonce=NULLPTR,
size_t nonceLength=0, const byte* personalization=NULLPTR, size_t personalizationLength=0) size_t nonceLength=0, const byte* personalization=NULLPTR, size_t personalizationLength=0)
: NIST_DRBG(), m_k(HASH::DIGESTSIZE), m_v(HASH::DIGESTSIZE), m_reseed(0) : NIST_DRBG(), m_k(HASH::DIGESTSIZE), m_v(HASH::DIGESTSIZE), m_reseed(0)

38
dsa.h
View File

@ -1,7 +1,7 @@
// dsa.h - originally written and placed in the public domain by Wei Dai // dsa.h - originally written and placed in the public domain by Wei Dai
//! \file dsa.h /// \file dsa.h
//! \brief Classes for the DSA signature algorithm /// \brief Classes for the DSA signature algorithm
#ifndef CRYPTOPP_DSA_H #ifndef CRYPTOPP_DSA_H
#define CRYPTOPP_DSA_H #define CRYPTOPP_DSA_H
@ -11,29 +11,29 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief DSA Signature Format /// \brief DSA Signature Format
//! \details The DSA signature format used by Crypto++ is as defined by IEEE P1363. /// \details The DSA signature format used by Crypto++ is as defined by IEEE P1363.
//! Java nad .Net use the DER format, and OpenPGP uses the OpenPGP format. /// Java nad .Net use the DER format, and OpenPGP uses the OpenPGP format.
enum DSASignatureFormat { enum DSASignatureFormat {
//! \brief Crypto++ native signature encoding format /// \brief Crypto++ native signature encoding format
DSA_P1363, DSA_P1363,
//! \brief signature encoding format used by Java and .Net /// \brief signature encoding format used by Java and .Net
DSA_DER, DSA_DER,
//! \brief OpenPGP signature encoding format /// \brief OpenPGP signature encoding format
DSA_OPENPGP DSA_OPENPGP
}; };
//! \brief Converts between signature encoding formats /// \brief Converts between signature encoding formats
//! \param buffer byte buffer for the converted signature encoding /// \param buffer byte buffer for the converted signature encoding
//! \param bufferSize the length of the converted signature encoding buffer /// \param bufferSize the length of the converted signature encoding buffer
//! \param toFormat the source signature format /// \param toFormat the source signature format
//! \param signature byte buffer for the existing signature encoding /// \param signature byte buffer for the existing signature encoding
//! \param signatureLen the length of the existing signature encoding buffer /// \param signatureLen the length of the existing signature encoding buffer
//! \param fromFormat the source signature format /// \param fromFormat the source signature format
//! \details This function converts between these formats, and returns length /// \details This function converts between these formats, and returns length
//! of signature in the target format. If <tt>toFormat == DSA_P1363</tt>, then /// of signature in the target format. If <tt>toFormat == DSA_P1363</tt>, then
//! <tt>bufferSize</tt> must equal <tt>publicKey.SignatureLength()</tt> /// <tt>bufferSize</tt> must equal <tt>publicKey.SignatureLength()</tt>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
size_t DSAConvertSignatureFormat(byte *buffer, size_t bufferSize, DSASignatureFormat toFormat, size_t DSAConvertSignatureFormat(byte *buffer, size_t bufferSize, DSASignatureFormat toFormat,
const byte *signature, size_t signatureLen, DSASignatureFormat fromFormat); const byte *signature, size_t signatureLen, DSASignatureFormat fromFormat);

40
eax.h
View File

@ -1,7 +1,7 @@
// eax.h - originally written and placed in the public domain by Wei Dai // eax.h - originally written and placed in the public domain by Wei Dai
//! \file eax.h /// \file eax.h
//! \brief EAX block cipher mode of operation /// \brief EAX block cipher mode of operation
#ifndef CRYPTOPP_EAX_H #ifndef CRYPTOPP_EAX_H
#define CRYPTOPP_EAX_H #define CRYPTOPP_EAX_H
@ -12,10 +12,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class EAX_Base /// \class EAX_Base
//! \brief EAX block cipher base implementation /// \brief EAX block cipher base implementation
//! \details Base implementation of the AuthenticatedSymmetricCipher interface /// \details Base implementation of the AuthenticatedSymmetricCipher interface
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
class CRYPTOPP_NO_VTABLE EAX_Base : public AuthenticatedSymmetricCipherBase class CRYPTOPP_NO_VTABLE EAX_Base : public AuthenticatedSymmetricCipherBase
{ {
public: public:
@ -67,11 +67,11 @@ protected:
CTR_Mode_ExternalCipher::Encryption m_ctr; CTR_Mode_ExternalCipher::Encryption m_ctr;
}; };
//! \class EAX_Final /// \class EAX_Final
//! \brief EAX block cipher final implementation /// \brief EAX block cipher final implementation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \tparam T_IsEncryption direction in which to operate the cipher /// \tparam T_IsEncryption direction in which to operate the cipher
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher, bool T_IsEncryption> template <class T_BlockCipher, bool T_IsEncryption>
class EAX_Final : public EAX_Base class EAX_Final : public EAX_Base
{ {
@ -90,15 +90,15 @@ private:
#undef EAX #undef EAX
#endif #endif
//! \class EAX /// \class EAX
//! \brief EAX block cipher mode of operation /// \brief EAX block cipher mode of operation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \details \p EAX provides the \p Encryption and \p Decryption typedef. See EAX_Base /// \details \p EAX provides the \p Encryption and \p Decryption typedef. See EAX_Base
//! and EAX_Final for the AuthenticatedSymmetricCipher implementation. /// and EAX_Final for the AuthenticatedSymmetricCipher implementation.
//! \sa <a href="http://www.cryptopp.com/wiki/EAX_Mode">EAX Mode</a> and /// \sa <a href="http://www.cryptopp.com/wiki/EAX_Mode">EAX Mode</a> and
//! <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher> template <class T_BlockCipher>
struct EAX : public AuthenticatedSymmetricCipherDocumentation struct EAX : public AuthenticatedSymmetricCipherDocumentation
{ {

44
ec2n.h
View File

@ -1,8 +1,8 @@
// ec2n.h - originally written and placed in the public domain by Wei Dai // ec2n.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile ec2n.h /// \headerfile ec2n.h
//! \brief Classes for Elliptic Curves over binary fields /// \brief Classes for Elliptic Curves over binary fields
#ifndef CRYPTOPP_EC2N_H #ifndef CRYPTOPP_EC2N_H
@ -24,8 +24,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class EC2N /// \class EC2N
//! \brief Elliptic Curve over GF(2^n) /// \brief Elliptic Curve over GF(2^n)
class CRYPTOPP_DLL EC2N : public AbstractGroup<EC2NPoint>, public EncodedPoint<EC2NPoint> class CRYPTOPP_DLL EC2N : public AbstractGroup<EC2NPoint>, public EncodedPoint<EC2NPoint>
{ {
public: public:
@ -35,23 +35,23 @@ public:
virtual ~EC2N() {} virtual ~EC2N() {}
//! \brief Construct an EC2N /// \brief Construct an EC2N
EC2N() {} EC2N() {}
//! \brief Construct an EC2N /// \brief Construct an EC2N
//! \param field Field, GF2NP derived class /// \param field Field, GF2NP derived class
//! \param a Field::Element /// \param a Field::Element
//! \param b Field::Element /// \param b Field::Element
EC2N(const Field &field, const Field::Element &a, const Field::Element &b) EC2N(const Field &field, const Field::Element &a, const Field::Element &b)
: m_field(field), m_a(a), m_b(b) {} : m_field(field), m_a(a), m_b(b) {}
//! \brief Construct an EC2N from BER encoded parameters /// \brief Construct an EC2N from BER encoded parameters
//! \param bt BufferedTransformation derived object /// \param bt BufferedTransformation derived object
//! \details This constructor will decode and extract the the fields fieldID and curve of the sequence ECParameters /// \details This constructor will decode and extract the the fields fieldID and curve of the sequence ECParameters
EC2N(BufferedTransformation &bt); EC2N(BufferedTransformation &bt);
//! \brief Encode the fields fieldID and curve of the sequence ECParameters /// \brief Encode the fields fieldID and curve of the sequence ECParameters
//! \param bt BufferedTransformation derived object /// \param bt BufferedTransformation derived object
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
bool Equal(const Point &P, const Point &Q) const; bool Equal(const Point &P, const Point &Q) const;
@ -97,15 +97,15 @@ private:
CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<EC2N::Point>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<EC2N::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<EC2N::Point>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<EC2N::Point>;
//! \class EcPrecomputation /// \class EcPrecomputation
//! \brief Elliptic Curve precomputation /// \brief Elliptic Curve precomputation
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> class EcPrecomputation; template <class EC> class EcPrecomputation;
//! \class EcPrecomputation<EC2N> /// \class EcPrecomputation<EC2N>
//! \brief EC2N precomputation specialization /// \brief EC2N precomputation specialization
//! \details Implementation of <tt>DL_GroupPrecomputation<EC2N::Point></tt> /// \details Implementation of <tt>DL_GroupPrecomputation<EC2N::Point></tt>
//! \sa DL_GroupPrecomputation /// \sa DL_GroupPrecomputation
template<> class EcPrecomputation<EC2N> : public DL_GroupPrecomputation<EC2N::Point> template<> class EcPrecomputation<EC2N> : public DL_GroupPrecomputation<EC2N::Point>
{ {
public: public:

View File

@ -1,8 +1,8 @@
// eccrypto.h - originally written and placed in the public domain by Wei Dai // eccrypto.h - originally written and placed in the public domain by Wei Dai
// deterministic signatures added by by Douglas Roark // deterministic signatures added by by Douglas Roark
//! \file eccrypto.h /// \file eccrypto.h
//! \brief Classes and functions for Elliptic Curves over prime and binary fields /// \brief Classes and functions for Elliptic Curves over prime and binary fields
#ifndef CRYPTOPP_ECCRYPTO_H #ifndef CRYPTOPP_ECCRYPTO_H
#define CRYPTOPP_ECCRYPTO_H #define CRYPTOPP_ECCRYPTO_H
@ -29,10 +29,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Elliptic Curve Parameters /// \brief Elliptic Curve Parameters
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \details This class corresponds to the ASN.1 sequence of the same name /// \details This class corresponds to the ASN.1 sequence of the same name
//! in ANSI X9.62 and SEC 1. EC is currently defined for ECP and EC2N. /// in ANSI X9.62 and SEC 1. EC is currently defined for ECP and EC2N.
template <class EC> template <class EC>
class DL_GroupParameters_EC : public DL_GroupParametersImpl<EcPrecomputation<EC> > class DL_GroupParameters_EC : public DL_GroupParametersImpl<EcPrecomputation<EC> >
{ {
@ -46,33 +46,33 @@ public:
virtual ~DL_GroupParameters_EC() {} virtual ~DL_GroupParameters_EC() {}
//! \brief Construct an EC GroupParameters /// \brief Construct an EC GroupParameters
DL_GroupParameters_EC() : m_compress(false), m_encodeAsOID(true) {} DL_GroupParameters_EC() : m_compress(false), m_encodeAsOID(true) {}
//! \brief Construct an EC GroupParameters /// \brief Construct an EC GroupParameters
//! \param oid the OID of a curve /// \param oid the OID of a curve
DL_GroupParameters_EC(const OID &oid) DL_GroupParameters_EC(const OID &oid)
: m_compress(false), m_encodeAsOID(true) {Initialize(oid);} : m_compress(false), m_encodeAsOID(true) {Initialize(oid);}
//! \brief Construct an EC GroupParameters /// \brief Construct an EC GroupParameters
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param k the cofactor /// \param k the cofactor
DL_GroupParameters_EC(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero()) DL_GroupParameters_EC(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
: m_compress(false), m_encodeAsOID(true) {Initialize(ec, G, n, k);} : m_compress(false), m_encodeAsOID(true) {Initialize(ec, G, n, k);}
//! \brief Construct an EC GroupParameters /// \brief Construct an EC GroupParameters
//! \param bt BufferedTransformation with group parameters /// \param bt BufferedTransformation with group parameters
DL_GroupParameters_EC(BufferedTransformation &bt) DL_GroupParameters_EC(BufferedTransformation &bt)
: m_compress(false), m_encodeAsOID(true) {BERDecode(bt);} : m_compress(false), m_encodeAsOID(true) {BERDecode(bt);}
//! \brief Initialize an EC GroupParameters using {EC,G,n,k} /// \brief Initialize an EC GroupParameters using {EC,G,n,k}
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param k the cofactor /// \param k the cofactor
//! \details This Initialize() function overload initializes group parameters from existing parameters. /// \details This Initialize() function overload initializes group parameters from existing parameters.
void Initialize(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero()) void Initialize(const EllipticCurve &ec, const Point &G, const Integer &n, const Integer &k = Integer::Zero())
{ {
this->m_groupPrecomputation.SetCurve(ec); this->m_groupPrecomputation.SetCurve(ec);
@ -81,9 +81,9 @@ public:
m_k = k; m_k = k;
} }
//! \brief Initialize a DL_GroupParameters_EC {EC,G,n,k} /// \brief Initialize a DL_GroupParameters_EC {EC,G,n,k}
//! \param oid the OID of a curve /// \param oid the OID of a curve
//! \details This Initialize() function overload initializes group parameters from existing parameters. /// \details This Initialize() function overload initializes group parameters from existing parameters.
void Initialize(const OID &oid); void Initialize(const OID &oid);
// NameValuePairs // NameValuePairs
@ -91,7 +91,7 @@ public:
void AssignFrom(const NameValuePairs &source); void AssignFrom(const NameValuePairs &source);
// GeneratibleCryptoMaterial interface // GeneratibleCryptoMaterial interface
//! this implementation doesn't actually generate a curve, it just initializes the parameters with existing values /// this implementation doesn't actually generate a curve, it just initializes the parameters with existing values
/*! parameters: (Curve, SubgroupGenerator, SubgroupOrder, Cofactor (optional)), or (GroupOID) */ /*! parameters: (Curve, SubgroupGenerator, SubgroupOrder, Cofactor (optional)), or (GroupOID) */
void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg); void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg);
@ -174,9 +174,9 @@ protected:
mutable bool m_compress, m_encodeAsOID; // presentation details mutable bool m_compress, m_encodeAsOID; // presentation details
}; };
//! \class DL_PublicKey_EC /// \class DL_PublicKey_EC
//! \brief Elliptic Curve Discrete Log (DL) public key /// \brief Elliptic Curve Discrete Log (DL) public key
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> > class DL_PublicKey_EC : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
{ {
@ -185,19 +185,19 @@ public:
virtual ~DL_PublicKey_EC() {} virtual ~DL_PublicKey_EC() {}
//! \brief Initialize an EC Public Key using {GP,Q} /// \brief Initialize an EC Public Key using {GP,Q}
//! \param params group parameters /// \param params group parameters
//! \param Q the public point /// \param Q the public point
//! \details This Initialize() function overload initializes a public key from existing parameters. /// \details This Initialize() function overload initializes a public key from existing parameters.
void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q) void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
{this->AccessGroupParameters() = params; this->SetPublicElement(Q);} {this->AccessGroupParameters() = params; this->SetPublicElement(Q);}
//! \brief Initialize an EC Public Key using {EC,G,n,Q} /// \brief Initialize an EC Public Key using {EC,G,n,Q}
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param Q the public point /// \param Q the public point
//! \details This Initialize() function overload initializes a public key from existing parameters. /// \details This Initialize() function overload initializes a public key from existing parameters.
void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q) void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);} {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}
@ -206,9 +206,9 @@ public:
void DEREncodePublicKey(BufferedTransformation &bt) const; void DEREncodePublicKey(BufferedTransformation &bt) const;
}; };
//! \class DL_PrivateKey_EC /// \class DL_PrivateKey_EC
//! \brief Elliptic Curve Discrete Log (DL) private key /// \brief Elliptic Curve Discrete Log (DL) private key
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> > class DL_PrivateKey_EC : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
{ {
@ -217,39 +217,39 @@ public:
virtual ~DL_PrivateKey_EC(); virtual ~DL_PrivateKey_EC();
//! \brief Initialize an EC Private Key using {GP,x} /// \brief Initialize an EC Private Key using {GP,x}
//! \param params group parameters /// \param params group parameters
//! \param x the private exponent /// \param x the private exponent
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x) void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
{this->AccessGroupParameters() = params; this->SetPrivateExponent(x);} {this->AccessGroupParameters() = params; this->SetPrivateExponent(x);}
//! \brief Initialize an EC Private Key using {EC,G,n,x} /// \brief Initialize an EC Private Key using {EC,G,n,x}
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param x the private exponent /// \param x the private exponent
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x) void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);} {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPrivateExponent(x);}
//! \brief Create an EC private key /// \brief Create an EC private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param params the EC group parameters /// \param params the EC group parameters
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params) void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
{this->GenerateRandom(rng, params);} {this->GenerateRandom(rng, params);}
//! \brief Create an EC private key /// \brief Create an EC private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n) void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
{this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));} {this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}
@ -262,21 +262,21 @@ public:
template<class EC> template<class EC>
DL_PrivateKey_EC<EC>::~DL_PrivateKey_EC() {} DL_PrivateKey_EC<EC>::~DL_PrivateKey_EC() {}
//! \class ECDH /// \class ECDH
//! \brief Elliptic Curve Diffie-Hellman /// \brief Elliptic Curve Diffie-Hellman
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">Elliptic Curve Diffie-Hellman, AKA ECDH</a> /// \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECDH">Elliptic Curve Diffie-Hellman, AKA ECDH</a>
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption> template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECDH struct ECDH
{ {
typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain; typedef DH_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
}; };
//! \class ECMQV /// \class ECMQV
//! \brief Elliptic Curve Menezes-Qu-Vanstone /// \brief Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
/// \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECMQV">Elliptic Curve Menezes-Qu-Vanstone, AKA ECMQV</a> /// \sa CofactorMultiplicationOption, <a href="http://www.weidai.com/scan-mirror/ka.html#ECMQV">Elliptic Curve Menezes-Qu-Vanstone, AKA ECMQV</a>
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption> template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption>
struct ECMQV struct ECMQV
@ -284,13 +284,13 @@ struct ECMQV
typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain; typedef MQV_Domain<DL_GroupParameters_EC<EC>, COFACTOR_OPTION> Domain;
}; };
//! \class ECHMQV /// \class ECHMQV
//! \brief Hashed Elliptic Curve Menezes-Qu-Vanstone /// \brief Hashed Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance /// \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance
//! Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided. /// Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided.
//! \sa CofactorMultiplicationOption /// \sa CofactorMultiplicationOption
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256> template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
struct ECHMQV struct ECHMQV
{ {
@ -302,14 +302,14 @@ typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA256
typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECHMQV384; typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECHMQV384;
typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECHMQV512; typedef ECHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECHMQV512;
//! \class ECFHMQV /// \class ECFHMQV
//! \brief Fully Hashed Elliptic Curve Menezes-Qu-Vanstone /// \brief Fully Hashed Elliptic Curve Menezes-Qu-Vanstone
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's /// \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's
//! <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>. /// <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>.
//! Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C. /// Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C.
//! \sa CofactorMultiplicationOption /// \sa CofactorMultiplicationOption
template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256> template <class EC, class COFACTOR_OPTION = typename DL_GroupParameters_EC<EC>::DefaultCofactorOption, class HASH = SHA256>
struct ECFHMQV struct ECFHMQV
{ {
@ -321,9 +321,9 @@ typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA25
typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECFHMQV384; typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA384 >::Domain ECFHMQV384;
typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECFHMQV512; typedef ECFHMQV< ECP, DL_GroupParameters_EC< ECP >::DefaultCofactorOption, SHA512 >::Domain ECFHMQV512;
//! \class DL_Keys_EC /// \class DL_Keys_EC
//! \brief Elliptic Curve Discrete Log (DL) keys /// \brief Elliptic Curve Discrete Log (DL) keys
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
struct DL_Keys_EC struct DL_Keys_EC
{ {
@ -335,9 +335,9 @@ struct DL_Keys_EC
template <class EC, class H> template <class EC, class H>
struct ECDSA; struct ECDSA;
//! \class DL_Keys_ECDSA /// \class DL_Keys_ECDSA
//! \brief Elliptic Curve DSA keys /// \brief Elliptic Curve DSA keys
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
struct DL_Keys_ECDSA struct DL_Keys_ECDSA
{ {
@ -345,9 +345,9 @@ struct DL_Keys_ECDSA
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey; typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_EC<EC>, ECDSA<EC, SHA256> > PrivateKey;
}; };
//! \class DL_Algorithm_ECDSA /// \class DL_Algorithm_ECDSA
//! \brief Elliptic Curve DSA (ECDSA) signature algorithm /// \brief Elliptic Curve DSA (ECDSA) signature algorithm
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point> class DL_Algorithm_ECDSA : public DL_Algorithm_GDSA<typename EC::Point>
{ {
@ -355,12 +355,12 @@ public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";} CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA";}
}; };
//! \class DL_Algorithm_ECDSA_RFC6979 /// \class DL_Algorithm_ECDSA_RFC6979
//! \brief Elliptic Curve DSA (ECDSA) signature algorithm based on RFC 6979 /// \brief Elliptic Curve DSA (ECDSA) signature algorithm based on RFC 6979
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the
//! Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a> /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC, class H> template <class EC, class H>
class DL_Algorithm_ECDSA_RFC6979 : public DL_Algorithm_DSA_RFC6979<typename EC::Point, H> class DL_Algorithm_ECDSA_RFC6979 : public DL_Algorithm_DSA_RFC6979<typename EC::Point, H>
{ {
@ -368,9 +368,9 @@ public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA-RFC6979";} CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECDSA-RFC6979";}
}; };
//! \class DL_Algorithm_ECNR /// \class DL_Algorithm_ECNR
//! \brief Elliptic Curve NR (ECNR) signature algorithm /// \brief Elliptic Curve NR (ECNR) signature algorithm
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> template <class EC>
class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point> class DL_Algorithm_ECNR : public DL_Algorithm_NR<typename EC::Point>
{ {
@ -378,22 +378,22 @@ public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECNR";} CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECNR";}
}; };
//! \class ECDSA /// \class ECDSA
//! \brief Elliptic Curve DSA (ECDSA) signature scheme /// \brief Elliptic Curve DSA (ECDSA) signature scheme
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#ECDSA">ECDSA</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#ECDSA">ECDSA</a>
template <class EC, class H> template <class EC, class H>
struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H> struct ECDSA : public DL_SS<DL_Keys_ECDSA<EC>, DL_Algorithm_ECDSA<EC>, DL_SignatureMessageEncodingMethod_DSA, H>
{ {
}; };
//! \class ECDSA_RFC6979 /// \class ECDSA_RFC6979
//! \brief Elliptic Curve DSA (ECDSA) deterministic signature scheme /// \brief Elliptic Curve DSA (ECDSA) deterministic signature scheme
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">Deterministic Usage of the /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">Deterministic Usage of the
//! Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a> /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
template <class EC, class H> template <class EC, class H>
struct ECDSA_RFC6979 : public DL_SS< struct ECDSA_RFC6979 : public DL_SS<
DL_Keys_ECDSA<EC>, DL_Keys_ECDSA<EC>,
@ -405,10 +405,10 @@ struct ECDSA_RFC6979 : public DL_SS<
static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECDSA-RFC6979/") + H::StaticAlgorithmName();} static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("ECDSA-RFC6979/") + H::StaticAlgorithmName();}
}; };
//! \class ECNR /// \class ECNR
//! \brief Elliptic Curve NR (ECNR) signature scheme /// \brief Elliptic Curve NR (ECNR) signature scheme
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
template <class EC, class H = SHA1> template <class EC, class H = SHA1>
struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H> struct ECNR : public DL_SS<DL_Keys_EC<EC>, DL_Algorithm_ECNR<EC>, DL_SignatureMessageEncodingMethod_NR, H>
{ {
@ -421,11 +421,11 @@ class DL_PublicKey_ECGDSA_ISO15946;
template <class EC> template <class EC>
class DL_PrivateKey_ECGDSA_ISO15946; class DL_PrivateKey_ECGDSA_ISO15946;
//! \class DL_PrivateKey_ECGDSA_ISO15946 /// \class DL_PrivateKey_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA key for ISO/IEC 15946 /// \brief Elliptic Curve German DSA key for ISO/IEC 15946
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946 /// \sa ECGDSA_ISO15946
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC> template <class EC>
class DL_PrivateKey_ECGDSA_ISO15946 : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> > class DL_PrivateKey_ECGDSA_ISO15946 : public DL_PrivateKeyImpl<DL_GroupParameters_EC<EC> >
{ {
@ -434,10 +434,10 @@ public:
virtual ~DL_PrivateKey_ECGDSA_ISO15946() {} virtual ~DL_PrivateKey_ECGDSA_ISO15946() {}
//! \brief Initialize an EC Private Key using {GP,x} /// \brief Initialize an EC Private Key using {GP,x}
//! \param params group parameters /// \param params group parameters
//! \param x the private exponent /// \param x the private exponent
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x) void Initialize(const DL_GroupParameters_EC<EC> &params, const Integer &x)
{ {
this->AccessGroupParameters() = params; this->AccessGroupParameters() = params;
@ -445,12 +445,12 @@ public:
CRYPTOPP_ASSERT(x>=1 && x<=params.GetSubgroupOrder()-1); CRYPTOPP_ASSERT(x>=1 && x<=params.GetSubgroupOrder()-1);
} }
//! \brief Initialize an EC Private Key using {EC,G,n,x} /// \brief Initialize an EC Private Key using {EC,G,n,x}
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param x the private exponent /// \param x the private exponent
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x) void Initialize(const EC &ec, const Element &G, const Integer &n, const Integer &x)
{ {
this->AccessGroupParameters().Initialize(ec, G, n); this->AccessGroupParameters().Initialize(ec, G, n);
@ -458,23 +458,23 @@ public:
CRYPTOPP_ASSERT(x>=1 && x<=this->AccessGroupParameters().GetSubgroupOrder()-1); CRYPTOPP_ASSERT(x>=1 && x<=this->AccessGroupParameters().GetSubgroupOrder()-1);
} }
//! \brief Create an EC private key /// \brief Create an EC private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param params the EC group parameters /// \param params the EC group parameters
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params) void Initialize(RandomNumberGenerator &rng, const DL_GroupParameters_EC<EC> &params)
{this->GenerateRandom(rng, params);} {this->GenerateRandom(rng, params);}
//! \brief Create an EC private key /// \brief Create an EC private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n) void Initialize(RandomNumberGenerator &rng, const EC &ec, const Element &G, const Integer &n)
{this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));} {this->GenerateRandom(rng, DL_GroupParameters_EC<EC>(ec, G, n));}
@ -504,11 +504,11 @@ public:
void DEREncodePrivateKey(BufferedTransformation &bt) const; void DEREncodePrivateKey(BufferedTransformation &bt) const;
}; };
//! \class DL_PublicKey_ECGDSA_ISO15946 /// \class DL_PublicKey_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA key for ISO/IEC 15946 /// \brief Elliptic Curve German DSA key for ISO/IEC 15946
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946 /// \sa ECGDSA_ISO15946
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC> template <class EC>
class DL_PublicKey_ECGDSA_ISO15946 : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> > class DL_PublicKey_ECGDSA_ISO15946 : public DL_PublicKeyImpl<DL_GroupParameters_EC<EC> >
{ {
@ -519,19 +519,19 @@ public:
virtual ~DL_PublicKey_ECGDSA_ISO15946() {} virtual ~DL_PublicKey_ECGDSA_ISO15946() {}
//! \brief Initialize an EC Public Key using {GP,Q} /// \brief Initialize an EC Public Key using {GP,Q}
//! \param params group parameters /// \param params group parameters
//! \param Q the public point /// \param Q the public point
//! \details This Initialize() function overload initializes a public key from existing parameters. /// \details This Initialize() function overload initializes a public key from existing parameters.
void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q) void Initialize(const DL_GroupParameters_EC<EC> &params, const Element &Q)
{this->AccessGroupParameters() = params; this->SetPublicElement(Q);} {this->AccessGroupParameters() = params; this->SetPublicElement(Q);}
//! \brief Initialize an EC Public Key using {EC,G,n,Q} /// \brief Initialize an EC Public Key using {EC,G,n,Q}
//! \param ec the elliptic curve /// \param ec the elliptic curve
//! \param G the base point /// \param G the base point
//! \param n the order of the base point /// \param n the order of the base point
//! \param Q the public point /// \param Q the public point
//! \details This Initialize() function overload initializes a public key from existing parameters. /// \details This Initialize() function overload initializes a public key from existing parameters.
void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q) void Initialize(const EC &ec, const Element &G, const Integer &n, const Element &Q)
{this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);} {this->AccessGroupParameters().Initialize(ec, G, n); this->SetPublicElement(Q);}
@ -557,11 +557,11 @@ public:
void DEREncodePublicKey(BufferedTransformation &bt) const; void DEREncodePublicKey(BufferedTransformation &bt) const;
}; };
//! \class DL_Keys_ECGDSA_ISO15946 /// \class DL_Keys_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA keys for ISO/IEC 15946 /// \brief Elliptic Curve German DSA keys for ISO/IEC 15946
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946 /// \sa ECGDSA_ISO15946
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC> template <class EC>
struct DL_Keys_ECGDSA_ISO15946 struct DL_Keys_ECGDSA_ISO15946
{ {
@ -569,11 +569,11 @@ struct DL_Keys_ECGDSA_ISO15946
typedef DL_PrivateKey_ECGDSA_ISO15946<EC> PrivateKey; typedef DL_PrivateKey_ECGDSA_ISO15946<EC> PrivateKey;
}; };
//! \class DL_Algorithm_ECGDSA_ISO15946 /// \class DL_Algorithm_ECGDSA_ISO15946
//! \brief Elliptic Curve German DSA signature algorithm /// \brief Elliptic Curve German DSA signature algorithm
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \sa ECGDSA_ISO15946 /// \sa ECGDSA_ISO15946
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC> template <class EC>
class DL_Algorithm_ECGDSA_ISO15946 : public DL_Algorithm_GDSA_ISO15946<typename EC::Point> class DL_Algorithm_ECGDSA_ISO15946 : public DL_Algorithm_GDSA_ISO15946<typename EC::Point>
{ {
@ -581,14 +581,14 @@ public:
CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECGDSA";} CRYPTOPP_STATIC_CONSTEXPR const char* CRYPTOPP_API StaticAlgorithmName() {return "ECGDSA";}
}; };
//! \class ECGDSA /// \class ECGDSA
//! \brief Elliptic Curve German Digital Signature Algorithm signature scheme /// \brief Elliptic Curve German Digital Signature Algorithm signature scheme
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A /// \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A
//! HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf">The Digital Signature Scheme /// HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf">The Digital Signature Scheme
//! ECGDSA (October 24, 2006)</A> /// ECGDSA (October 24, 2006)</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class EC, class H> template <class EC, class H>
struct ECGDSA : public DL_SS< struct ECGDSA : public DL_SS<
DL_Keys_ECGDSA_ISO15946<EC>, DL_Keys_ECGDSA_ISO15946<EC>,
@ -601,40 +601,40 @@ struct ECGDSA : public DL_SS<
// ****************************************** // ******************************************
//! \class ECIES /// \class ECIES
//! \brief Elliptic Curve Integrated Encryption Scheme /// \brief Elliptic Curve Integrated Encryption Scheme
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \tparam HASH HashTransformation derived class used for key drivation and MAC computation /// \tparam HASH HashTransformation derived class used for key drivation and MAC computation
//! \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as <em>u·V</em>, <em>v·U</em> and label /// \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as <em>u·V</em>, <em>v·U</em> and label
//! \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits /// \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
//! \details ECIES is an Elliptic Curve based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation /// \details ECIES is an Elliptic Curve based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation
//! Method (KEM) with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is /// Method (KEM) with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
//! <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security. /// <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security.
//! You should prefer an Integrated Encryption Scheme over homegrown schemes. /// You should prefer an Integrated Encryption Scheme over homegrown schemes.
//! \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom /// \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom
//! SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption /// SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption
//! Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the ECIES template class with /// \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the ECIES template class with
//! <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES /// \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES
//! template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>. /// template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
//! \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of /// \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of
//! <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security. /// <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
//! SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the /// SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the
//! security provided by the MAC. The hash is also used in the key derivation function as a PRF. /// security provided by the MAC. The hash is also used in the key derivation function as a PRF.
//! \details Below is an example of constructing a Crypto++ 4.2 compatible ECIES encryptor and decryptor. /// \details Below is an example of constructing a Crypto++ 4.2 compatible ECIES encryptor and decryptor.
//! <pre> /// <pre>
//! AutoSeededRandomPool prng; /// AutoSeededRandomPool prng;
//! DL_PrivateKey_EC<ECP> key; /// DL_PrivateKey_EC<ECP> key;
//! key.Initialize(prng, ASN1::secp160r1()); /// key.Initialize(prng, ASN1::secp160r1());
//! ///
//! ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key); /// ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key);
//! ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor); /// ECIES<ECP,SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor);
//! </pre> /// </pre>
//! \sa DLIES, <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">Elliptic Curve Integrated Encryption Scheme (ECIES)</a>, /// \sa DLIES, <a href="http://www.weidai.com/scan-mirror/ca.html#ECIES">Elliptic Curve Integrated Encryption Scheme (ECIES)</a>,
//! Martínez, Encinas, and Ávila's <A HREF="http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf">A Survey of the Elliptic /// Martínez, Encinas, and Ávila's <A HREF="http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf">A Survey of the Elliptic
//! Curve Integrated Encryption Schemes</A> /// Curve Integrated Encryption Schemes</A>
//! \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility /// \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
template <class EC, class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false> template <class EC, class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false>
struct ECIES struct ECIES
: public DL_ES< : public DL_ES<

52
ecp.h
View File

@ -1,7 +1,7 @@
// ecp.h - originally written and placed in the public domain by Wei Dai // ecp.h - originally written and placed in the public domain by Wei Dai
//! \file ecp.h /// \file ecp.h
//! \brief Classes for Elliptic Curves over prime fields /// \brief Classes for Elliptic Curves over prime fields
#ifndef CRYPTOPP_ECP_H #ifndef CRYPTOPP_ECP_H
#define CRYPTOPP_ECP_H #define CRYPTOPP_ECP_H
@ -22,8 +22,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ECP /// \class ECP
//! \brief Elliptic Curve over GF(p), where p is prime /// \brief Elliptic Curve over GF(p), where p is prime
class CRYPTOPP_DLL ECP : public AbstractGroup<ECPPoint>, public EncodedPoint<ECPPoint> class CRYPTOPP_DLL ECP : public AbstractGroup<ECPPoint>, public EncodedPoint<ECPPoint>
{ {
public: public:
@ -33,29 +33,29 @@ public:
virtual ~ECP() {} virtual ~ECP() {}
//! \brief Construct an ECP /// \brief Construct an ECP
ECP() {} ECP() {}
//! \brief Copy construct an ECP /// \brief Copy construct an ECP
//! \param ecp the other ECP object /// \param ecp the other ECP object
//! \param convertToMontgomeryRepresentation flag indicating if the curve should be converted to a MontgomeryRepresentation /// \param convertToMontgomeryRepresentation flag indicating if the curve should be converted to a MontgomeryRepresentation
//! \sa ModularArithmetic, MontgomeryRepresentation /// \sa ModularArithmetic, MontgomeryRepresentation
ECP(const ECP &ecp, bool convertToMontgomeryRepresentation = false); ECP(const ECP &ecp, bool convertToMontgomeryRepresentation = false);
//! \brief Construct an ECP /// \brief Construct an ECP
//! \param modulus the prime modulus /// \param modulus the prime modulus
//! \param a Field::Element /// \param a Field::Element
//! \param b Field::Element /// \param b Field::Element
ECP(const Integer &modulus, const FieldElement &a, const FieldElement &b) ECP(const Integer &modulus, const FieldElement &a, const FieldElement &b)
: m_fieldPtr(new Field(modulus)), m_a(a.IsNegative() ? modulus+a : a), m_b(b) {} : m_fieldPtr(new Field(modulus)), m_a(a.IsNegative() ? modulus+a : a), m_b(b) {}
//! \brief Construct an ECP from BER encoded parameters /// \brief Construct an ECP from BER encoded parameters
//! \param bt BufferedTransformation derived object /// \param bt BufferedTransformation derived object
//! \details This constructor will decode and extract the the fields fieldID and curve of the sequence ECParameters /// \details This constructor will decode and extract the the fields fieldID and curve of the sequence ECParameters
ECP(BufferedTransformation &bt); ECP(BufferedTransformation &bt);
//! \brief Encode the fields fieldID and curve of the sequence ECParameters /// \brief Encode the fields fieldID and curve of the sequence ECParameters
//! \param bt BufferedTransformation derived object /// \param bt BufferedTransformation derived object
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
bool Equal(const Point &P, const Point &Q) const; bool Equal(const Point &P, const Point &Q) const;
@ -104,16 +104,16 @@ private:
CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<ECP::Point>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_FixedBasePrecomputationImpl<ECP::Point>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<ECP::Point>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupPrecomputation<ECP::Point>;
//! \class EcPrecomputation /// \class EcPrecomputation
//! \brief Elliptic Curve precomputation /// \brief Elliptic Curve precomputation
//! \tparam EC elliptic curve field /// \tparam EC elliptic curve field
template <class EC> class EcPrecomputation; template <class EC> class EcPrecomputation;
//! \class EcPrecomputation<ECP> /// \class EcPrecomputation<ECP>
//! \brief ECP precomputation specialization /// \brief ECP precomputation specialization
//! \details Implementation of <tt>DL_GroupPrecomputation<ECP::Point></tt> with input and output /// \details Implementation of <tt>DL_GroupPrecomputation<ECP::Point></tt> with input and output
//! conversions for Montgomery modular multiplication. /// conversions for Montgomery modular multiplication.
//! \sa DL_GroupPrecomputation, ModularArithmetic, MontgomeryRepresentation /// \sa DL_GroupPrecomputation, ModularArithmetic, MontgomeryRepresentation
template<> class EcPrecomputation<ECP> : public DL_GroupPrecomputation<ECP::Point> template<> class EcPrecomputation<ECP> : public DL_GroupPrecomputation<ECP::Point>
{ {
public: public:

134
ecpoint.h
View File

@ -1,9 +1,9 @@
// ecpoint.h - written and placed in the public domain by Jeffrey Walton // ecpoint.h - written and placed in the public domain by Jeffrey Walton
// Data structures moved from ecp.h and ec2n.h. Added EncodedPoint interface // Data structures moved from ecp.h and ec2n.h. Added EncodedPoint interface
//! \file ecpoint.h /// \file ecpoint.h
//! \brief Classes for Elliptic Curve points /// \brief Classes for Elliptic Curve points
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
#ifndef CRYPTOPP_ECPOINT_H #ifndef CRYPTOPP_ECPOINT_H
#define CRYPTOPP_ECPOINT_H #define CRYPTOPP_ECPOINT_H
@ -15,31 +15,31 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ECPPoint /// \class ECPPoint
//! \brief Elliptical Curve Point over GF(p), where p is prime /// \brief Elliptical Curve Point over GF(p), where p is prime
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
struct CRYPTOPP_DLL ECPPoint struct CRYPTOPP_DLL ECPPoint
{ {
virtual ~ECPPoint() {} virtual ~ECPPoint() {}
//! \brief Construct an ECPPoint /// \brief Construct an ECPPoint
//! \details identity is set to <tt>true</tt> /// \details identity is set to <tt>true</tt>
ECPPoint() : identity(true) {} ECPPoint() : identity(true) {}
//! \brief Construct an ECPPoint from coordinates /// \brief Construct an ECPPoint from coordinates
//! \details identity is set to <tt>false</tt> /// \details identity is set to <tt>false</tt>
ECPPoint(const Integer &x, const Integer &y) ECPPoint(const Integer &x, const Integer &y)
: x(x), y(y), identity(false) {} : x(x), y(y), identity(false) {}
//! \brief Tests points for equality /// \brief Tests points for equality
//! \param t the other point /// \param t the other point
//! \returns true if the points are equal, false otherwise /// \returns true if the points are equal, false otherwise
bool operator==(const ECPPoint &t) const bool operator==(const ECPPoint &t) const
{return (identity && t.identity) || (!identity && !t.identity && x==t.x && y==t.y);} {return (identity && t.identity) || (!identity && !t.identity && x==t.x && y==t.y);}
//! \brief Tests points for ordering /// \brief Tests points for ordering
//! \param t the other point /// \param t the other point
//! \returns true if this point is less than other, false otherwise /// \returns true if this point is less than other, false otherwise
bool operator< (const ECPPoint &t) const bool operator< (const ECPPoint &t) const
{return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));} {return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));}
@ -49,31 +49,31 @@ struct CRYPTOPP_DLL ECPPoint
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<ECPPoint>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<ECPPoint>;
//! \class EC2NPoint /// \class EC2NPoint
//! \brief Elliptical Curve Point over GF(2^n) /// \brief Elliptical Curve Point over GF(2^n)
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
struct CRYPTOPP_DLL EC2NPoint struct CRYPTOPP_DLL EC2NPoint
{ {
virtual ~EC2NPoint() {} virtual ~EC2NPoint() {}
//! \brief Construct an EC2NPoint /// \brief Construct an EC2NPoint
//! \details identity is set to <tt>true</tt> /// \details identity is set to <tt>true</tt>
EC2NPoint() : identity(true) {} EC2NPoint() : identity(true) {}
//! \brief Construct an EC2NPoint from coordinates /// \brief Construct an EC2NPoint from coordinates
//! \details identity is set to <tt>false</tt> /// \details identity is set to <tt>false</tt>
EC2NPoint(const PolynomialMod2 &x, const PolynomialMod2 &y) EC2NPoint(const PolynomialMod2 &x, const PolynomialMod2 &y)
: x(x), y(y), identity(false) {} : x(x), y(y), identity(false) {}
//! \brief Tests points for equality /// \brief Tests points for equality
//! \param t the other point /// \param t the other point
//! \returns true if the points are equal, false otherwise /// \returns true if the points are equal, false otherwise
bool operator==(const EC2NPoint &t) const bool operator==(const EC2NPoint &t) const
{return (identity && t.identity) || (!identity && !t.identity && x==t.x && y==t.y);} {return (identity && t.identity) || (!identity && !t.identity && x==t.x && y==t.y);}
//! \brief Tests points for ordering /// \brief Tests points for ordering
//! \param t the other point /// \param t the other point
//! \returns true if this point is less than other, false otherwise /// \returns true if this point is less than other, false otherwise
bool operator< (const EC2NPoint &t) const bool operator< (const EC2NPoint &t) const
{return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));} {return identity ? !t.identity : (!t.identity && (x<t.x || (x==t.x && y<t.y)));}
@ -83,64 +83,64 @@ struct CRYPTOPP_DLL EC2NPoint
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<EC2NPoint>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<EC2NPoint>;
//! \class EncodedPoint /// \class EncodedPoint
//! \brief Abstract class for encoding and decoding ellicptic curve points /// \brief Abstract class for encoding and decoding ellicptic curve points
//! \tparam Point ellicptic curve point /// \tparam Point ellicptic curve point
//! \details EncodedPoint is an interface for encoding and decoding elliptic curve points. /// \details EncodedPoint is an interface for encoding and decoding elliptic curve points.
//! The template parameter <tt>Point</tt> should be a class like ECP or EC2N. /// The template parameter <tt>Point</tt> should be a class like ECP or EC2N.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class Point> template <class Point>
class EncodedPoint class EncodedPoint
{ {
public: public:
virtual ~EncodedPoint() {} virtual ~EncodedPoint() {}
//! \brief Decodes an elliptic curve point /// \brief Decodes an elliptic curve point
//! \param P point which is decoded /// \param P point which is decoded
//! \param bt source BufferedTransformation /// \param bt source BufferedTransformation
//! \param len number of bytes to read from the BufferedTransformation /// \param len number of bytes to read from the BufferedTransformation
//! \returns true if a point was decoded, false otherwise /// \returns true if a point was decoded, false otherwise
virtual bool DecodePoint(Point &P, BufferedTransformation &bt, size_t len) const =0; virtual bool DecodePoint(Point &P, BufferedTransformation &bt, size_t len) const =0;
//! \brief Decodes an elliptic curve point /// \brief Decodes an elliptic curve point
//! \param P point which is decoded /// \param P point which is decoded
//! \param encodedPoint byte array with the encoded point /// \param encodedPoint byte array with the encoded point
//! \param len the size of the array /// \param len the size of the array
//! \returns true if a point was decoded, false otherwise /// \returns true if a point was decoded, false otherwise
virtual bool DecodePoint(Point &P, const byte *encodedPoint, size_t len) const =0; virtual bool DecodePoint(Point &P, const byte *encodedPoint, size_t len) const =0;
//! \brief Verifies points on elliptic curve /// \brief Verifies points on elliptic curve
//! \param P point to verify /// \param P point to verify
//! \returns true if the point is valid, false otherwise /// \returns true if the point is valid, false otherwise
virtual bool VerifyPoint(const Point &P) const =0; virtual bool VerifyPoint(const Point &P) const =0;
//! \brief Determines encoded point size /// \brief Determines encoded point size
//! \param compressed flag indicating if the point is compressed /// \param compressed flag indicating if the point is compressed
//! \returns the minimum number of bytes required to encode the point /// \returns the minimum number of bytes required to encode the point
virtual unsigned int EncodedPointSize(bool compressed = false) const =0; virtual unsigned int EncodedPointSize(bool compressed = false) const =0;
//! \brief Encodes an elliptic curve point /// \brief Encodes an elliptic curve point
//! \param P point which is decoded /// \param P point which is decoded
//! \param encodedPoint byte array for the encoded point /// \param encodedPoint byte array for the encoded point
//! \param compressed flag indicating if the point is compressed /// \param compressed flag indicating if the point is compressed
//! \details <tt>encodedPoint</tt> must be at least EncodedPointSize() in length /// \details <tt>encodedPoint</tt> must be at least EncodedPointSize() in length
virtual void EncodePoint(byte *encodedPoint, const Point &P, bool compressed) const =0; virtual void EncodePoint(byte *encodedPoint, const Point &P, bool compressed) const =0;
//! \brief Encodes an elliptic curve point /// \brief Encodes an elliptic curve point
//! \param bt target BufferedTransformation /// \param bt target BufferedTransformation
//! \param P point which is encoded /// \param P point which is encoded
//! \param compressed flag indicating if the point is compressed /// \param compressed flag indicating if the point is compressed
virtual void EncodePoint(BufferedTransformation &bt, const Point &P, bool compressed) const =0; virtual void EncodePoint(BufferedTransformation &bt, const Point &P, bool compressed) const =0;
//! \brief BER Decodes an elliptic curve point /// \brief BER Decodes an elliptic curve point
//! \param bt source BufferedTransformation /// \param bt source BufferedTransformation
//! \returns the decoded elliptic curve point /// \returns the decoded elliptic curve point
virtual Point BERDecodePoint(BufferedTransformation &bt) const =0; virtual Point BERDecodePoint(BufferedTransformation &bt) const =0;
//! \brief DER Encodes an elliptic curve point /// \brief DER Encodes an elliptic curve point
//! \param bt target BufferedTransformation /// \param bt target BufferedTransformation
//! \param P point which is encoded /// \param P point which is encoded
//! \param compressed flag indicating if the point is compressed /// \param compressed flag indicating if the point is compressed
virtual void DEREncodePoint(BufferedTransformation &bt, const Point &P, bool compressed) const =0; virtual void DEREncodePoint(BufferedTransformation &bt, const Point &P, bool compressed) const =0;
}; };

View File

@ -1,7 +1,7 @@
// elgamal.h - originally written and placed in the public domain by Wei Dai // elgamal.h - originally written and placed in the public domain by Wei Dai
//! \file elgamal.h /// \file elgamal.h
//! \brief Classes and functions for ElGamal key agreement and encryption schemes /// \brief Classes and functions for ElGamal key agreement and encryption schemes
#ifndef CRYPTOPP_ELGAMAL_H #ifndef CRYPTOPP_ELGAMAL_H
#define CRYPTOPP_ELGAMAL_H #define CRYPTOPP_ELGAMAL_H
@ -16,9 +16,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ElGamalBase /// \class ElGamalBase
//! \brief ElGamal key agreement and encryption schemes base class /// \brief ElGamal key agreement and encryption schemes base class
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class CRYPTOPP_NO_VTABLE ElGamalBase : public DL_KeyAgreementAlgorithm_DH<Integer, NoCofactorMultiplication>, class CRYPTOPP_NO_VTABLE ElGamalBase : public DL_KeyAgreementAlgorithm_DH<Integer, NoCofactorMultiplication>,
public DL_KeyDerivationAlgorithm<Integer>, public DL_KeyDerivationAlgorithm<Integer>,
public DL_SymmetricEncryptionAlgorithm public DL_SymmetricEncryptionAlgorithm
@ -93,9 +93,9 @@ public:
virtual const DL_GroupParameters_GFP & GetGroupParameters() const =0; virtual const DL_GroupParameters_GFP & GetGroupParameters() const =0;
}; };
//! \class ElGamalObjectImpl /// \class ElGamalObjectImpl
//! \brief ElGamal key agreement and encryption schemes default implementation /// \brief ElGamal key agreement and encryption schemes default implementation
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
template <class BASE, class SCHEME_OPTIONS, class KEY> template <class BASE, class SCHEME_OPTIONS, class KEY>
class ElGamalObjectImpl : public DL_ObjectImplBase<BASE, SCHEME_OPTIONS, KEY>, public ElGamalBase class ElGamalObjectImpl : public DL_ObjectImplBase<BASE, SCHEME_OPTIONS, KEY>, public ElGamalBase
{ {
@ -116,8 +116,8 @@ protected:
const DL_SymmetricEncryptionAlgorithm & GetSymmetricEncryptionAlgorithm() const {return *this;} const DL_SymmetricEncryptionAlgorithm & GetSymmetricEncryptionAlgorithm() const {return *this;}
}; };
//! \class ElGamalKeys /// \class ElGamalKeys
//! \brief ElGamal key agreement and encryption schemes keys /// \brief ElGamal key agreement and encryption schemes keys
struct ElGamalKeys struct ElGamalKeys
{ {
typedef DL_CryptoKeys_GFP::GroupParameters GroupParameters; typedef DL_CryptoKeys_GFP::GroupParameters GroupParameters;
@ -125,9 +125,9 @@ struct ElGamalKeys
typedef DL_PublicKey_GFP_OldFormat<DL_CryptoKeys_GFP::PublicKey> PublicKey; typedef DL_PublicKey_GFP_OldFormat<DL_CryptoKeys_GFP::PublicKey> PublicKey;
}; };
//! \class ElGamal /// \class ElGamal
//! \brief ElGamal encryption scheme with non-standard padding /// \brief ElGamal encryption scheme with non-standard padding
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
struct ElGamal struct ElGamal
{ {
typedef DL_CryptoSchemeOptions<ElGamal, ElGamalKeys, int, int, int> SchemeOptions; typedef DL_CryptoSchemeOptions<ElGamal, ElGamalKeys, int, int, int> SchemeOptions;
@ -135,9 +135,9 @@ struct ElGamal
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ElgamalEnc/Crypto++Padding";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "ElgamalEnc/Crypto++Padding";}
typedef SchemeOptions::GroupParameters GroupParameters; typedef SchemeOptions::GroupParameters GroupParameters;
//! implements PK_Encryptor interface /// implements PK_Encryptor interface
typedef PK_FinalTemplate<ElGamalObjectImpl<DL_EncryptorBase<Integer>, SchemeOptions, SchemeOptions::PublicKey> > Encryptor; typedef PK_FinalTemplate<ElGamalObjectImpl<DL_EncryptorBase<Integer>, SchemeOptions, SchemeOptions::PublicKey> > Encryptor;
//! implements PK_Decryptor interface /// implements PK_Decryptor interface
typedef PK_FinalTemplate<ElGamalObjectImpl<DL_DecryptorBase<Integer>, SchemeOptions, SchemeOptions::PrivateKey> > Decryptor; typedef PK_FinalTemplate<ElGamalObjectImpl<DL_DecryptorBase<Integer>, SchemeOptions, SchemeOptions::PrivateKey> > Decryptor;
}; };

View File

@ -1,7 +1,7 @@
// emsa2.h - originally written and placed in the public domain by Wei Dai // emsa2.h - originally written and placed in the public domain by Wei Dai
//! \file emsa2.h /// \file emsa2.h
//! \brief Classes and functions for various padding schemes used in public key algorithms /// \brief Classes and functions for various padding schemes used in public key algorithms
#ifndef CRYPTOPP_EMSA2_H #ifndef CRYPTOPP_EMSA2_H
#define CRYPTOPP_EMSA2_H #define CRYPTOPP_EMSA2_H
@ -57,7 +57,7 @@ CRYPTOPP_DLL_TEMPLATE_CLASS EMSA2HashId<SHA384>;
CRYPTOPP_DLL_TEMPLATE_CLASS EMSA2HashId<SHA512>; CRYPTOPP_DLL_TEMPLATE_CLASS EMSA2HashId<SHA512>;
#endif #endif
//! _ /// _
class CRYPTOPP_DLL EMSA2Pad : public EMSA2HashIdLookup<PK_DeterministicSignatureMessageEncodingMethod> class CRYPTOPP_DLL EMSA2Pad : public EMSA2HashIdLookup<PK_DeterministicSignatureMessageEncodingMethod>
{ {
public: public:
@ -72,7 +72,7 @@ public:
byte *representative, size_t representativeBitLength) const; byte *representative, size_t representativeBitLength) const;
}; };
//! EMSA2, for use with RWSS and RSA_ISO /// EMSA2, for use with RWSS and RSA_ISO
/*! Only the following hash functions are supported by this signature standard: /*! Only the following hash functions are supported by this signature standard:
\dontinclude emsa2.h \dontinclude emsa2.h
\skip EMSA2HashId can be instantiated \skip EMSA2HashId can be instantiated

View File

@ -1,7 +1,7 @@
// eprecomp.h - originally written and placed in the public domain by Wei Dai // eprecomp.h - originally written and placed in the public domain by Wei Dai
//! \file eprecomp.h /// \file eprecomp.h
//! \brief Classes for precomputation in a group /// \brief Classes for precomputation in a group
#ifndef CRYPTOPP_EPRECOMP_H #ifndef CRYPTOPP_EPRECOMP_H
#define CRYPTOPP_EPRECOMP_H #define CRYPTOPP_EPRECOMP_H

72
esign.h
View File

@ -1,8 +1,8 @@
// esign.h - originally written and placed in the public domain by Wei Dai // esign.h - originally written and placed in the public domain by Wei Dai
//! \file esign.h /// \file esign.h
//! \brief Classes providing ESIGN signature schemes as defined in IEEE P1363a /// \brief Classes providing ESIGN signature schemes as defined in IEEE P1363a
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
#ifndef CRYPTOPP_ESIGN_H #ifndef CRYPTOPP_ESIGN_H
#define CRYPTOPP_ESIGN_H #define CRYPTOPP_ESIGN_H
@ -15,18 +15,18 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ESIGNFunction /// \class ESIGNFunction
//! \brief ESIGN trapdoor function using the public key /// \brief ESIGN trapdoor function using the public key
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
class ESIGNFunction : public TrapdoorFunction, public ASN1CryptoMaterial<PublicKey> class ESIGNFunction : public TrapdoorFunction, public ASN1CryptoMaterial<PublicKey>
{ {
typedef ESIGNFunction ThisClass; typedef ESIGNFunction ThisClass;
public: public:
//! \brief Initialize a ESIGN public key with {n,e} /// \brief Initialize a ESIGN public key with {n,e}
//! \param n the modulus /// \param n the modulus
//! \param e the public exponent /// \param e the public exponent
void Initialize(const Integer &n, const Integer &e) void Initialize(const Integer &n, const Integer &e)
{m_n = n; m_e = e;} {m_n = n; m_e = e;}
@ -58,30 +58,30 @@ protected:
Integer m_n, m_e; Integer m_n, m_e;
}; };
//! \class InvertibleESIGNFunction /// \class InvertibleESIGNFunction
//! \brief ESIGN trapdoor function using the private key /// \brief ESIGN trapdoor function using the private key
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
class InvertibleESIGNFunction : public ESIGNFunction, public RandomizedTrapdoorFunctionInverse, public PrivateKey class InvertibleESIGNFunction : public ESIGNFunction, public RandomizedTrapdoorFunctionInverse, public PrivateKey
{ {
typedef InvertibleESIGNFunction ThisClass; typedef InvertibleESIGNFunction ThisClass;
public: public:
//! \brief Initialize a ESIGN private key with {n,e,p,q} /// \brief Initialize a ESIGN private key with {n,e,p,q}
//! \param n modulus /// \param n modulus
//! \param e public exponent /// \param e public exponent
//! \param p first prime factor /// \param p first prime factor
//! \param q second prime factor /// \param q second prime factor
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const Integer &n, const Integer &e, const Integer &p, const Integer &q) void Initialize(const Integer &n, const Integer &e, const Integer &p, const Integer &q)
{m_n = n; m_e = e; m_p = p; m_q = q;} {m_n = n; m_e = e; m_p = p; m_q = q;}
//! \brief Create a ESIGN private key /// \brief Create a ESIGN private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param modulusBits the size of the modulud, in bits /// \param modulusBits the size of the modulud, in bits
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits) void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
{GenerateRandomWithKeySize(rng, modulusBits);} {GenerateRandomWithKeySize(rng, modulusBits);}
@ -115,10 +115,10 @@ protected:
Integer m_p, m_q; Integer m_p, m_q;
}; };
//! \class EMSA5Pad /// \class EMSA5Pad
//! \brief EMSA5 padding method /// \brief EMSA5 padding method
//! \tparam T Mask Generation Function /// \tparam T Mask Generation Function
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
template <class T> template <class T>
class EMSA5Pad : public PK_DeterministicSignatureMessageEncodingMethod class EMSA5Pad : public PK_DeterministicSignatureMessageEncodingMethod
{ {
@ -142,9 +142,9 @@ public:
} }
}; };
//! \class P1363_EMSA5 /// \class P1363_EMSA5
//! \brief EMSA5 padding method, for use with ESIGN /// \brief EMSA5 padding method, for use with ESIGN
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
struct P1363_EMSA5 : public SignatureStandard struct P1363_EMSA5 : public SignatureStandard
{ {
typedef EMSA5Pad<P1363_MGF1> SignatureMessageEncodingMethod; typedef EMSA5Pad<P1363_MGF1> SignatureMessageEncodingMethod;
@ -157,11 +157,11 @@ struct ESIGN_Keys
typedef InvertibleESIGNFunction PrivateKey; typedef InvertibleESIGNFunction PrivateKey;
}; };
//! \class ESIGN /// \class ESIGN
//! \brief ESIGN signature scheme, IEEE P1363a /// \brief ESIGN signature scheme, IEEE P1363a
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \tparam STANDARD Signature encoding method /// \tparam STANDARD Signature encoding method
//! \since Crypto++ 5.0 /// \since Crypto++ 5.0
template <class H, class STANDARD = P1363_EMSA5> template <class H, class STANDARD = P1363_EMSA5>
struct ESIGN : public TF_SS<ESIGN_Keys, STANDARD, H> struct ESIGN : public TF_SS<ESIGN_Keys, STANDARD, H>
{ {

View File

@ -1,7 +1,7 @@
// factory.h - originally written and placed in the public domain by Wei Dai // factory.h - originally written and placed in the public domain by Wei Dai
//! \file factory.h /// \file factory.h
//! \brief Classes and functions for registering and locating library objects /// \brief Classes and functions for registering and locating library objects
#ifndef CRYPTOPP_OBJFACT_H #ifndef CRYPTOPP_OBJFACT_H
#define CRYPTOPP_OBJFACT_H #define CRYPTOPP_OBJFACT_H
@ -12,9 +12,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class ObjectFactory /// \class ObjectFactory
//! \brief Object factory interface for registering objects /// \brief Object factory interface for registering objects
//! \tparam AbstractClass Base class interface of the object /// \tparam AbstractClass Base class interface of the object
template <class AbstractClass> template <class AbstractClass>
class ObjectFactory class ObjectFactory
{ {
@ -23,10 +23,10 @@ public:
virtual AbstractClass * CreateObject() const =0; virtual AbstractClass * CreateObject() const =0;
}; };
//! \class DefaultObjectFactory /// \class DefaultObjectFactory
//! \brief Object factory for registering objects /// \brief Object factory for registering objects
//! \tparam AbstractClass Base class interface of the object /// \tparam AbstractClass Base class interface of the object
//! \tparam ConcreteClass Class object /// \tparam ConcreteClass Class object
template <class AbstractClass, class ConcreteClass> template <class AbstractClass, class ConcreteClass>
class DefaultObjectFactory : public ObjectFactory<AbstractClass> class DefaultObjectFactory : public ObjectFactory<AbstractClass>
{ {
@ -37,10 +37,10 @@ public:
} }
}; };
//! \class ObjectFactoryRegistry /// \class ObjectFactoryRegistry
//! \brief Object factory registry /// \brief Object factory registry
//! \tparam AbstractClass Base class interface of the object /// \tparam AbstractClass Base class interface of the object
//! \tparam instance unique identifier /// \tparam instance unique identifier
template <class AbstractClass, int instance=0> template <class AbstractClass, int instance=0>
class ObjectFactoryRegistry class ObjectFactoryRegistry
{ {
@ -105,11 +105,11 @@ ObjectFactoryRegistry<AbstractClass, instance> & ObjectFactoryRegistry<AbstractC
return s_registry; return s_registry;
} }
//! \class RegisterDefaultFactoryFor /// \class RegisterDefaultFactoryFor
//! \brief Object factory registry helper /// \brief Object factory registry helper
//! \tparam AbstractClass Base class interface of the object /// \tparam AbstractClass Base class interface of the object
//! \tparam ConcreteClass Class object /// \tparam ConcreteClass Class object
//! \tparam instance unique identifier /// \tparam instance unique identifier
template <class AbstractClass, class ConcreteClass, int instance = 0> template <class AbstractClass, class ConcreteClass, int instance = 0>
struct RegisterDefaultFactoryFor struct RegisterDefaultFactoryFor
{ {
@ -122,13 +122,13 @@ struct RegisterDefaultFactoryFor
} }
}; };
//! \fn RegisterAsymmetricCipherDefaultFactories /// \fn RegisterAsymmetricCipherDefaultFactories
//! \brief Register asymmetric ciphers /// \brief Register asymmetric ciphers
//! \tparam SchemeClass interface of the object under a scheme /// \tparam SchemeClass interface of the object under a scheme
//! \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>), /// signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>),
//! symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc. /// authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc.
template <class SchemeClass> template <class SchemeClass>
void RegisterAsymmetricCipherDefaultFactories(const char *name=NULLPTR) void RegisterAsymmetricCipherDefaultFactories(const char *name=NULLPTR)
{ {
@ -136,13 +136,13 @@ void RegisterAsymmetricCipherDefaultFactories(const char *name=NULLPTR)
RegisterDefaultFactoryFor<PK_Decryptor, typename SchemeClass::Decryptor>((const char *)name); RegisterDefaultFactoryFor<PK_Decryptor, typename SchemeClass::Decryptor>((const char *)name);
} }
//! \fn RegisterSignatureSchemeDefaultFactories /// \fn RegisterSignatureSchemeDefaultFactories
//! \brief Register signature schemes /// \brief Register signature schemes
//! \tparam SchemeClass interface of the object under a scheme /// \tparam SchemeClass interface of the object under a scheme
//! \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>), /// signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>),
//! symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc. /// authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc.
template <class SchemeClass> template <class SchemeClass>
void RegisterSignatureSchemeDefaultFactories(const char *name=NULLPTR) void RegisterSignatureSchemeDefaultFactories(const char *name=NULLPTR)
{ {
@ -150,13 +150,13 @@ void RegisterSignatureSchemeDefaultFactories(const char *name=NULLPTR)
RegisterDefaultFactoryFor<PK_Verifier, typename SchemeClass::Verifier>((const char *)name); RegisterDefaultFactoryFor<PK_Verifier, typename SchemeClass::Verifier>((const char *)name);
} }
//! \fn RegisterSymmetricCipherDefaultFactories /// \fn RegisterSymmetricCipherDefaultFactories
//! \brief Register symmetric ciphers /// \brief Register symmetric ciphers
//! \tparam SchemeClass interface of the object under a scheme /// \tparam SchemeClass interface of the object under a scheme
//! \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>), /// signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>),
//! symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc. /// authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc.
template <class SchemeClass> template <class SchemeClass>
void RegisterSymmetricCipherDefaultFactories(const char *name=NULLPTR) void RegisterSymmetricCipherDefaultFactories(const char *name=NULLPTR)
{ {
@ -164,13 +164,13 @@ void RegisterSymmetricCipherDefaultFactories(const char *name=NULLPTR)
RegisterDefaultFactoryFor<SymmetricCipher, typename SchemeClass::Decryption, DECRYPTION>((const char *)name); RegisterDefaultFactoryFor<SymmetricCipher, typename SchemeClass::Decryption, DECRYPTION>((const char *)name);
} }
//! \fn RegisterAuthenticatedSymmetricCipherDefaultFactories /// \fn RegisterAuthenticatedSymmetricCipherDefaultFactories
//! \brief Register authenticated symmetric ciphers /// \brief Register authenticated symmetric ciphers
//! \tparam SchemeClass interface of the object under a scheme /// \tparam SchemeClass interface of the object under a scheme
//! \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// \details Schemes include asymmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>), /// signature schemes (registers <tt>SchemeClass::Signer</tt> and <tt>SchemeClass::Verifier</tt>),
//! symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), /// symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>),
//! authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc. /// authenticated symmetric ciphers (registers <tt>SchemeClass::Encryptor</tt> and <tt>SchemeClass::Decryptor</tt>), etc.
template <class SchemeClass> template <class SchemeClass>
void RegisterAuthenticatedSymmetricCipherDefaultFactories(const char *name=NULLPTR) void RegisterAuthenticatedSymmetricCipherDefaultFactories(const char *name=NULLPTR)
{ {

46
fhmqv.h
View File

@ -4,9 +4,9 @@
#ifndef CRYPTOPP_FHMQV_H #ifndef CRYPTOPP_FHMQV_H
#define CRYPTOPP_FHMQV_H #define CRYPTOPP_FHMQV_H
//! \file fhmqv.h /// \file fhmqv.h
//! \brief Classes for Fully Hashed Menezes-Qu-Vanstone key agreement in GF(p) /// \brief Classes for Fully Hashed Menezes-Qu-Vanstone key agreement in GF(p)
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
#include "gfpcrypt.h" #include "gfpcrypt.h"
#include "algebra.h" #include "algebra.h"
@ -14,12 +14,12 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Fully Hashed Menezes-Qu-Vanstone in GF(p) /// \brief Fully Hashed Menezes-Qu-Vanstone in GF(p)
//! \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's /// \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's
//! <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>. /// <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>.
//! Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C. /// Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C.
//! \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain /// \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption, class HASH = SHA512> template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption, class HASH = SHA512>
class FHMQV_Domain : public AuthenticatedKeyAgreementDomain class FHMQV_Domain : public AuthenticatedKeyAgreementDomain
{ {
@ -66,14 +66,14 @@ public:
CryptoParameters & AccessCryptoParameters(){return AccessAbstractGroupParameters();} CryptoParameters & AccessCryptoParameters(){return AccessAbstractGroupParameters();}
//! return length of agreed value produced /// return length of agreed value produced
unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);} unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);}
//! return length of static private keys in this domain /// return length of static private keys in this domain
unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();} unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();}
//! return length of static public keys in this domain /// return length of static public keys in this domain
unsigned int StaticPublicKeyLength() const{return GetAbstractGroupParameters().GetEncodedElementSize(true);} unsigned int StaticPublicKeyLength() const{return GetAbstractGroupParameters().GetEncodedElementSize(true);}
//! generate static private key /// generate static private key
/*! \pre size of privateKey == PrivateStaticKeyLength() */ /*! \pre size of privateKey == PrivateStaticKeyLength() */
void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
{ {
@ -81,7 +81,7 @@ public:
x.Encode(privateKey, StaticPrivateKeyLength()); x.Encode(privateKey, StaticPrivateKeyLength());
} }
//! generate static public key /// generate static public key
/*! \pre size of publicKey == PublicStaticKeyLength() */ /*! \pre size of publicKey == PublicStaticKeyLength() */
void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
@ -95,7 +95,7 @@ public:
unsigned int EphemeralPrivateKeyLength() const {return StaticPrivateKeyLength() + StaticPublicKeyLength();} unsigned int EphemeralPrivateKeyLength() const {return StaticPrivateKeyLength() + StaticPublicKeyLength();}
unsigned int EphemeralPublicKeyLength() const{return StaticPublicKeyLength();} unsigned int EphemeralPublicKeyLength() const{return StaticPublicKeyLength();}
//! return length of ephemeral private keys in this domain /// return length of ephemeral private keys in this domain
void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
{ {
const DL_GroupParameters<Element> &params = GetAbstractGroupParameters(); const DL_GroupParameters<Element> &params = GetAbstractGroupParameters();
@ -105,14 +105,14 @@ public:
params.EncodeElement(true, y, privateKey+StaticPrivateKeyLength()); params.EncodeElement(true, y, privateKey+StaticPrivateKeyLength());
} }
//! return length of ephemeral public keys in this domain /// return length of ephemeral public keys in this domain
void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(rng);
memcpy(publicKey, privateKey+StaticPrivateKeyLength(), EphemeralPublicKeyLength()); memcpy(publicKey, privateKey+StaticPrivateKeyLength(), EphemeralPublicKeyLength());
} }
//! derive agreed value from your private keys and couterparty's public keys, return false in case of failure /// derive agreed value from your private keys and couterparty's public keys, return false in case of failure
/*! \note The ephemeral public key will always be validated. /*! \note The ephemeral public key will always be validated.
If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time. If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time.
\pre size of agreedValue == AgreedValueLength() \pre size of agreedValue == AgreedValueLength()
@ -289,12 +289,12 @@ private:
KeyAgreementRole m_role; KeyAgreementRole m_role;
}; };
//! \brief Fully Hashed Menezes-Qu-Vanstone in GF(p) /// \brief Fully Hashed Menezes-Qu-Vanstone in GF(p)
//! \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's /// \details This implementation follows Augustin P. Sarr and Philippe ElbazVincent, and JeanClaude Bajard's
//! <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>. /// <a href="http://eprint.iacr.org/2009/408">A Secure and Efficient Authenticated Diffie-Hellman Protocol</a>.
//! Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C. /// Note: this is FHMQV, Protocol 5, from page 11; and not FHMQV-C.
//! \sa FHMQV, MQV_Domain, HMQV_Domain, AuthenticatedKeyAgreementDomain /// \sa FHMQV, MQV_Domain, HMQV_Domain, AuthenticatedKeyAgreementDomain
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef FHMQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> FHMQV; typedef FHMQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> FHMQV;
NAMESPACE_END NAMESPACE_END

118
files.h
View File

@ -1,8 +1,8 @@
// files.h - originally written and placed in the public domain by Wei Dai // files.h - originally written and placed in the public domain by Wei Dai
//! \file files.h /// \file files.h
//! \brief Classes providing file-based library services /// \brief Classes providing file-based library services
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
#ifndef CRYPTOPP_FILES_H #ifndef CRYPTOPP_FILES_H
#define CRYPTOPP_FILES_H #define CRYPTOPP_FILES_H
@ -17,50 +17,50 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class FileStore /// \class FileStore
//! \brief Implementation of Store interface /// \brief Implementation of Store interface
//! \details file-based implementation of Store interface /// \details file-based implementation of Store interface
class CRYPTOPP_DLL FileStore : public Store, private FilterPutSpaceHelper, public NotCopyable class CRYPTOPP_DLL FileStore : public Store, private FilterPutSpaceHelper, public NotCopyable
{ {
public: public:
//! \brief Exception thrown when file-based error is encountered /// \brief Exception thrown when file-based error is encountered
class Err : public Exception class Err : public Exception
{ {
public: public:
Err(const std::string &s) : Exception(IO_ERROR, s) {} Err(const std::string &s) : Exception(IO_ERROR, s) {}
}; };
//! \brief Exception thrown when file-based open error is encountered /// \brief Exception thrown when file-based open error is encountered
class OpenErr : public Err {public: OpenErr(const std::string &filename) : Err("FileStore: error opening file for reading: " + filename) {}}; class OpenErr : public Err {public: OpenErr(const std::string &filename) : Err("FileStore: error opening file for reading: " + filename) {}};
//! \brief Exception thrown when file-based read error is encountered /// \brief Exception thrown when file-based read error is encountered
class ReadErr : public Err {public: ReadErr() : Err("FileStore: error reading file") {}}; class ReadErr : public Err {public: ReadErr() : Err("FileStore: error reading file") {}};
//! \brief Construct a FileStore /// \brief Construct a FileStore
FileStore() : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0) {} FileStore() : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0) {}
//! \brief Construct a FileStore /// \brief Construct a FileStore
//! \param in an existing stream /// \param in an existing stream
FileStore(std::istream &in) : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0) FileStore(std::istream &in) : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0)
{StoreInitialize(MakeParameters(Name::InputStreamPointer(), &in));} {StoreInitialize(MakeParameters(Name::InputStreamPointer(), &in));}
//! \brief Construct a FileStore /// \brief Construct a FileStore
//! \param filename the narrow name of the file to open /// \param filename the narrow name of the file to open
FileStore(const char *filename) : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0) FileStore(const char *filename) : m_stream(NULLPTR), m_space(NULLPTR), m_len(0), m_waiting(0)
{StoreInitialize(MakeParameters(Name::InputFileName(), filename ? filename : ""));} {StoreInitialize(MakeParameters(Name::InputFileName(), filename ? filename : ""));}
#if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) || _MSC_VER >= 1400 #if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) || _MSC_VER >= 1400
//! \brief Construct a FileStore /// \brief Construct a FileStore
//! \param filename the Unicode name of the file to open /// \param filename the Unicode name of the file to open
//! \details On non-Windows OS, this function assumes that setlocale() has been called. /// \details On non-Windows OS, this function assumes that setlocale() has been called.
FileStore(const wchar_t *filename) FileStore(const wchar_t *filename)
{StoreInitialize(MakeParameters(Name::InputFileNameWide(), filename));} {StoreInitialize(MakeParameters(Name::InputFileNameWide(), filename));}
#endif #endif
//! \brief Retrieves the internal stream /// \brief Retrieves the internal stream
//! \returns the internal stream pointer /// \returns the internal stream pointer
std::istream* GetStream() {return m_stream;} std::istream* GetStream() {return m_stream;}
//! \brief Retrieves the internal stream /// \brief Retrieves the internal stream
//! \returns the internal stream pointer /// \returns the internal stream pointer
const std::istream* GetStream() const {return m_stream;} const std::istream* GetStream() const {return m_stream;}
lword MaxRetrievable() const; lword MaxRetrievable() const;
@ -78,9 +78,9 @@ private:
bool m_waiting; bool m_waiting;
}; };
//! \class FileSource /// \class FileSource
//! \brief Implementation of Store interface /// \brief Implementation of Store interface
//! \details file-based implementation of Store interface /// \details file-based implementation of Store interface
class CRYPTOPP_DLL FileSource : public SourceTemplate<FileStore> class CRYPTOPP_DLL FileSource : public SourceTemplate<FileStore>
{ {
public: public:
@ -88,82 +88,82 @@ public:
typedef FileStore::OpenErr OpenErr; typedef FileStore::OpenErr OpenErr;
typedef FileStore::ReadErr ReadErr; typedef FileStore::ReadErr ReadErr;
//! \brief Construct a FileSource /// \brief Construct a FileSource
FileSource(BufferedTransformation *attachment = NULLPTR) FileSource(BufferedTransformation *attachment = NULLPTR)
: SourceTemplate<FileStore>(attachment) {} : SourceTemplate<FileStore>(attachment) {}
//! \brief Construct a FileSource /// \brief Construct a FileSource
//! \param in an existing stream /// \param in an existing stream
//! \param pumpAll flag indicating if source data should be pumped to its attached transformation /// \param pumpAll flag indicating if source data should be pumped to its attached transformation
//! \param attachment an optional attached transformation /// \param attachment an optional attached transformation
FileSource(std::istream &in, bool pumpAll, BufferedTransformation *attachment = NULLPTR) FileSource(std::istream &in, bool pumpAll, BufferedTransformation *attachment = NULLPTR)
: SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputStreamPointer(), &in));} : SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputStreamPointer(), &in));}
//! \brief Construct a FileSource /// \brief Construct a FileSource
//! \param filename the narrow name of the file to open /// \param filename the narrow name of the file to open
//! \param pumpAll flag indicating if source data should be pumped to its attached transformation /// \param pumpAll flag indicating if source data should be pumped to its attached transformation
//! \param attachment an optional attached transformation /// \param attachment an optional attached transformation
//! \param binary flag indicating if the file is binary /// \param binary flag indicating if the file is binary
FileSource(const char *filename, bool pumpAll, BufferedTransformation *attachment = NULLPTR, bool binary=true) FileSource(const char *filename, bool pumpAll, BufferedTransformation *attachment = NULLPTR, bool binary=true)
: SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputFileName(), filename)(Name::InputBinaryMode(), binary));} : SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputFileName(), filename)(Name::InputBinaryMode(), binary));}
#if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) || _MSC_VER >= 1400 #if defined(CRYPTOPP_UNIX_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) || _MSC_VER >= 1400
//! \brief Construct a FileSource /// \brief Construct a FileSource
//! \param filename the Unicode name of the file to open /// \param filename the Unicode name of the file to open
//! \param pumpAll flag indicating if source data should be pumped to its attached transformation /// \param pumpAll flag indicating if source data should be pumped to its attached transformation
//! \param attachment an optional attached transformation /// \param attachment an optional attached transformation
//! \param binary flag indicating if the file is binary /// \param binary flag indicating if the file is binary
//! \details On non-Windows OS, this function assumes that setlocale() has been called. /// \details On non-Windows OS, this function assumes that setlocale() has been called.
FileSource(const wchar_t *filename, bool pumpAll, BufferedTransformation *attachment = NULLPTR, bool binary=true) FileSource(const wchar_t *filename, bool pumpAll, BufferedTransformation *attachment = NULLPTR, bool binary=true)
: SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputFileNameWide(), filename)(Name::InputBinaryMode(), binary));} : SourceTemplate<FileStore>(attachment) {SourceInitialize(pumpAll, MakeParameters(Name::InputFileNameWide(), filename)(Name::InputBinaryMode(), binary));}
#endif #endif
//! \brief Retrieves the internal stream /// \brief Retrieves the internal stream
//! \returns the internal stream pointer /// \returns the internal stream pointer
std::istream* GetStream() {return m_store.GetStream();} std::istream* GetStream() {return m_store.GetStream();}
}; };
//! \class FileSink /// \class FileSink
//! \brief Implementation of Store interface /// \brief Implementation of Store interface
//! \details file-based implementation of Sink interface /// \details file-based implementation of Sink interface
class CRYPTOPP_DLL FileSink : public Sink, public NotCopyable class CRYPTOPP_DLL FileSink : public Sink, public NotCopyable
{ {
public: public:
//! \brief Exception thrown when file-based error is encountered /// \brief Exception thrown when file-based error is encountered
class Err : public Exception class Err : public Exception
{ {
public: public:
Err(const std::string &s) : Exception(IO_ERROR, s) {} Err(const std::string &s) : Exception(IO_ERROR, s) {}
}; };
//! \brief Exception thrown when file-based open error is encountered /// \brief Exception thrown when file-based open error is encountered
class OpenErr : public Err {public: OpenErr(const std::string &filename) : Err("FileSink: error opening file for writing: " + filename) {}}; class OpenErr : public Err {public: OpenErr(const std::string &filename) : Err("FileSink: error opening file for writing: " + filename) {}};
//! \brief Exception thrown when file-based write error is encountered /// \brief Exception thrown when file-based write error is encountered
class WriteErr : public Err {public: WriteErr() : Err("FileSink: error writing file") {}}; class WriteErr : public Err {public: WriteErr() : Err("FileSink: error writing file") {}};
//! \brief Construct a FileSink /// \brief Construct a FileSink
FileSink() : m_stream(NULLPTR) {} FileSink() : m_stream(NULLPTR) {}
//! \brief Construct a FileSink /// \brief Construct a FileSink
//! \param out an existing stream /// \param out an existing stream
FileSink(std::ostream &out) FileSink(std::ostream &out)
{IsolatedInitialize(MakeParameters(Name::OutputStreamPointer(), &out));} {IsolatedInitialize(MakeParameters(Name::OutputStreamPointer(), &out));}
//! \brief Construct a FileSink /// \brief Construct a FileSink
//! \param filename the narrow name of the file to open /// \param filename the narrow name of the file to open
//! \param binary flag indicating if the file is binary /// \param binary flag indicating if the file is binary
FileSink(const char *filename, bool binary=true) FileSink(const char *filename, bool binary=true)
{IsolatedInitialize(MakeParameters(Name::OutputFileName(), filename)(Name::OutputBinaryMode(), binary));} {IsolatedInitialize(MakeParameters(Name::OutputFileName(), filename)(Name::OutputBinaryMode(), binary));}
#if defined(CRYPTOPP_UNIX_AVAILABLE) || _MSC_VER >= 1400 #if defined(CRYPTOPP_UNIX_AVAILABLE) || _MSC_VER >= 1400
//! \brief Construct a FileSink /// \brief Construct a FileSink
//! \param filename the Unicode name of the file to open /// \param filename the Unicode name of the file to open
//! \details On non-Windows OS, this function assumes that setlocale() has been called. /// \details On non-Windows OS, this function assumes that setlocale() has been called.
FileSink(const wchar_t *filename, bool binary=true) FileSink(const wchar_t *filename, bool binary=true)
{IsolatedInitialize(MakeParameters(Name::OutputFileNameWide(), filename)(Name::OutputBinaryMode(), binary));} {IsolatedInitialize(MakeParameters(Name::OutputFileNameWide(), filename)(Name::OutputBinaryMode(), binary));}
#endif #endif
//! \brief Retrieves the internal stream /// \brief Retrieves the internal stream
//! \returns the internal stream pointer /// \returns the internal stream pointer
std::ostream* GetStream() {return m_stream;} std::ostream* GetStream() {return m_stream;}
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);

1098
filters.h

File diff suppressed because it is too large Load Diff

106
fips140.h
View File

@ -1,12 +1,12 @@
// fips140.h - originally written and placed in the public domain by Wei Dai // fips140.h - originally written and placed in the public domain by Wei Dai
//! \file fips140.h /// \file fips140.h
//! \brief Classes and functions for the FIPS 140-2 validated library /// \brief Classes and functions for the FIPS 140-2 validated library
//! \details The FIPS validated library is only available on Windows as a DLL. Once compiled, /// \details The FIPS validated library is only available on Windows as a DLL. Once compiled,
//! the library is always in FIPS mode contingent upon successful execution of /// the library is always in FIPS mode contingent upon successful execution of
//! DoPowerUpSelfTest() or DoDllPowerUpSelfTest(). /// DoPowerUpSelfTest() or DoDllPowerUpSelfTest().
//! \sa <A HREF="http://cryptopp.com/wiki/Visual_Studio">Visual Studio</A> and /// \sa <A HREF="http://cryptopp.com/wiki/Visual_Studio">Visual Studio</A> and
//! <A HREF="http://cryptopp.com/wiki/config.h">config.h</A> on the Crypto++ wiki. /// <A HREF="http://cryptopp.com/wiki/config.h">config.h</A> on the Crypto++ wiki.
#ifndef CRYPTOPP_FIPS140_H #ifndef CRYPTOPP_FIPS140_H
#define CRYPTOPP_FIPS140_H #define CRYPTOPP_FIPS140_H
@ -16,76 +16,76 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class SelfTestFailure /// \class SelfTestFailure
//! Exception thrown when a crypto algorithm is used after a self test fails /// Exception thrown when a crypto algorithm is used after a self test fails
//! \details The self tests for an algorithm are performed by Algortihm class /// \details The self tests for an algorithm are performed by Algortihm class
//! when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined. /// when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined.
class CRYPTOPP_DLL SelfTestFailure : public Exception class CRYPTOPP_DLL SelfTestFailure : public Exception
{ {
public: public:
explicit SelfTestFailure(const std::string &s) : Exception(OTHER_ERROR, s) {} explicit SelfTestFailure(const std::string &s) : Exception(OTHER_ERROR, s) {}
}; };
//! \brief Determines whether the library provides FIPS validated cryptography /// \brief Determines whether the library provides FIPS validated cryptography
//! \returns true if FIPS 140-2 validated features were enabled at compile time. /// \returns true if FIPS 140-2 validated features were enabled at compile time.
//! \details true if FIPS 140-2 validated features were enabled at compile time, /// \details true if FIPS 140-2 validated features were enabled at compile time,
//! false otherwise. /// false otherwise.
//! \note FIPS mode is enabled at compile time. A program or other module cannot /// \note FIPS mode is enabled at compile time. A program or other module cannot
//! arbitrarily enter or exit the mode. /// arbitrarily enter or exit the mode.
CRYPTOPP_DLL bool CRYPTOPP_API FIPS_140_2_ComplianceEnabled(); CRYPTOPP_DLL bool CRYPTOPP_API FIPS_140_2_ComplianceEnabled();
//! \brief Status of the power-up self test /// \brief Status of the power-up self test
enum PowerUpSelfTestStatus { enum PowerUpSelfTestStatus {
//! \brief The self tests have not been performed. /// \brief The self tests have not been performed.
POWER_UP_SELF_TEST_NOT_DONE, POWER_UP_SELF_TEST_NOT_DONE,
//! \brief The self tests were executed via DoPowerUpSelfTest() or /// \brief The self tests were executed via DoPowerUpSelfTest() or
//! DoDllPowerUpSelfTest(), but the result was failure. /// DoDllPowerUpSelfTest(), but the result was failure.
POWER_UP_SELF_TEST_FAILED, POWER_UP_SELF_TEST_FAILED,
//! \brief The self tests were executed via DoPowerUpSelfTest() or /// \brief The self tests were executed via DoPowerUpSelfTest() or
//! DoDllPowerUpSelfTest(), and the result was success. /// DoDllPowerUpSelfTest(), and the result was success.
POWER_UP_SELF_TEST_PASSED POWER_UP_SELF_TEST_PASSED
}; };
//! \brief Performs the power-up self test /// \brief Performs the power-up self test
//! \param moduleFilename the fully qualified name of the module /// \param moduleFilename the fully qualified name of the module
//! \param expectedModuleMac the expected MAC of the components protected by the integrity check /// \param expectedModuleMac the expected MAC of the components protected by the integrity check
//! \details Performs the power-up self test, and sets the self test status to /// \details Performs the power-up self test, and sets the self test status to
//! POWER_UP_SELF_TEST_PASSED or POWER_UP_SELF_TEST_FAILED. /// POWER_UP_SELF_TEST_PASSED or POWER_UP_SELF_TEST_FAILED.
//! \details The self tests for an algorithm are performed by the Algortihm class /// \details The self tests for an algorithm are performed by the Algortihm class
//! when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined. /// when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined.
CRYPTOPP_DLL void CRYPTOPP_API DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleMac); CRYPTOPP_DLL void CRYPTOPP_API DoPowerUpSelfTest(const char *moduleFilename, const byte *expectedModuleMac);
//! \brief Performs the power-up self test on the DLL /// \brief Performs the power-up self test on the DLL
//! \details Performs the power-up self test using the filename of this DLL and the /// \details Performs the power-up self test using the filename of this DLL and the
//! embedded module MAC, and sets the self test status to POWER_UP_SELF_TEST_PASSED or /// embedded module MAC, and sets the self test status to POWER_UP_SELF_TEST_PASSED or
//! POWER_UP_SELF_TEST_FAILED. /// POWER_UP_SELF_TEST_FAILED.
//! \details The self tests for an algorithm are performed by the Algortihm class /// \details The self tests for an algorithm are performed by the Algortihm class
//! when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined. /// when CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined.
CRYPTOPP_DLL void CRYPTOPP_API DoDllPowerUpSelfTest(); CRYPTOPP_DLL void CRYPTOPP_API DoDllPowerUpSelfTest();
//! \brief Sets the power-up self test status to POWER_UP_SELF_TEST_FAILED /// \brief Sets the power-up self test status to POWER_UP_SELF_TEST_FAILED
//! \details Sets the power-up self test status to POWER_UP_SELF_TEST_FAILED to simulate failure. /// \details Sets the power-up self test status to POWER_UP_SELF_TEST_FAILED to simulate failure.
CRYPTOPP_DLL void CRYPTOPP_API SimulatePowerUpSelfTestFailure(); CRYPTOPP_DLL void CRYPTOPP_API SimulatePowerUpSelfTestFailure();
//! \brief Provides the current power-up self test status /// \brief Provides the current power-up self test status
//! \returns the current power-up self test status /// \returns the current power-up self test status
CRYPTOPP_DLL PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus(); CRYPTOPP_DLL PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus();
#ifndef CRYPTOPP_DOXYGEN_PROCESSING #ifndef CRYPTOPP_DOXYGEN_PROCESSING
typedef PowerUpSelfTestStatus (CRYPTOPP_API * PGetPowerUpSelfTestStatus)(); typedef PowerUpSelfTestStatus (CRYPTOPP_API * PGetPowerUpSelfTestStatus)();
#endif #endif
//! \brief Class object that calculates the MAC on the module /// \brief Class object that calculates the MAC on the module
//! \returns the MAC for the module /// \returns the MAC for the module
CRYPTOPP_DLL MessageAuthenticationCode * CRYPTOPP_API NewIntegrityCheckingMAC(); CRYPTOPP_DLL MessageAuthenticationCode * CRYPTOPP_API NewIntegrityCheckingMAC();
//! \brief Verifies the MAC on the module /// \brief Verifies the MAC on the module
//! \param moduleFilename the fully qualified name of the module /// \param moduleFilename the fully qualified name of the module
//! \param expectedModuleMac the expected MAC of the components protected by the integrity check /// \param expectedModuleMac the expected MAC of the components protected by the integrity check
//! \param pActualMac the actual MAC of the components calculated by the integrity check /// \param pActualMac the actual MAC of the components calculated by the integrity check
//! \param pMacFileLocation the offest of the MAC in the PE/PE+ module /// \param pMacFileLocation the offest of the MAC in the PE/PE+ module
//! \returns true if the MAC is valid, false otherwise /// \returns true if the MAC is valid, false otherwise
CRYPTOPP_DLL bool CRYPTOPP_API IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac = NULLPTR, unsigned long *pMacFileLocation = NULLPTR); CRYPTOPP_DLL bool CRYPTOPP_API IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac = NULLPTR, unsigned long *pMacFileLocation = NULLPTR);
#ifndef CRYPTOPP_DOXYGEN_PROCESSING #ifndef CRYPTOPP_DOXYGEN_PROCESSING
@ -101,11 +101,11 @@ void SignaturePairwiseConsistencyTest_FIPS_140_Only(const PK_Signer &signer, con
void EncryptionPairwiseConsistencyTest_FIPS_140_Only(const PK_Encryptor &encryptor, const PK_Decryptor &decryptor); void EncryptionPairwiseConsistencyTest_FIPS_140_Only(const PK_Encryptor &encryptor, const PK_Decryptor &decryptor);
#endif #endif
//! \brief The placeholder used prior to embedding the actual MAC in the module. /// \brief The placeholder used prior to embedding the actual MAC in the module.
//! \details After the DLL is built but before it is MAC'd, the string CRYPTOPP_DUMMY_DLL_MAC /// \details After the DLL is built but before it is MAC'd, the string CRYPTOPP_DUMMY_DLL_MAC
//! is used as a placeholder for the actual MAC. A post-build step is performed which calculates /// is used as a placeholder for the actual MAC. A post-build step is performed which calculates
//! the MAC of the DLL and embeds it in the module. The actual MAC is written by the /// the MAC of the DLL and embeds it in the module. The actual MAC is written by the
//! <tt>cryptest.exe</tt> program using the <tt>mac_dll</tt> subcommand. /// <tt>cryptest.exe</tt> program using the <tt>mac_dll</tt> subcommand.
#define CRYPTOPP_DUMMY_DLL_MAC "MAC_51f34b8db820ae8" #define CRYPTOPP_DUMMY_DLL_MAC "MAC_51f34b8db820ae8"
NAMESPACE_END NAMESPACE_END

54
gcm.h
View File

@ -1,8 +1,8 @@
// gcm.h - originally written and placed in the public domain by Wei Dai // gcm.h - originally written and placed in the public domain by Wei Dai
//! \file gcm.h /// \file gcm.h
//! \brief GCM block cipher mode of operation /// \brief GCM block cipher mode of operation
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
#ifndef CRYPTOPP_GCM_H #ifndef CRYPTOPP_GCM_H
#define CRYPTOPP_GCM_H #define CRYPTOPP_GCM_H
@ -12,18 +12,18 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \enum GCM_TablesOption /// \enum GCM_TablesOption
//! \brief GCM table size options /// \brief GCM table size options
enum GCM_TablesOption { enum GCM_TablesOption {
//! \brief Use a table with 2K entries /// \brief Use a table with 2K entries
GCM_2K_Tables, GCM_2K_Tables,
//! \brief Use a table with 64K entries /// \brief Use a table with 64K entries
GCM_64K_Tables}; GCM_64K_Tables};
//! \class GCM_Base /// \class GCM_Base
//! \brief GCM block cipher base implementation /// \brief GCM block cipher base implementation
//! \details Base implementation of the AuthenticatedSymmetricCipher interface /// \details Base implementation of the AuthenticatedSymmetricCipher interface
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GCM_Base : public AuthenticatedSymmetricCipherBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GCM_Base : public AuthenticatedSymmetricCipherBase
{ {
public: public:
@ -91,12 +91,12 @@ protected:
enum {REQUIRED_BLOCKSIZE = 16, HASH_BLOCKSIZE = 16}; enum {REQUIRED_BLOCKSIZE = 16, HASH_BLOCKSIZE = 16};
}; };
//! \class GCM_Final /// \class GCM_Final
//! \brief GCM block cipher final implementation /// \brief GCM block cipher final implementation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \tparam T_TablesOption table size, either \p GCM_2K_Tables or \p GCM_64K_Tables /// \tparam T_TablesOption table size, either \p GCM_2K_Tables or \p GCM_64K_Tables
//! \tparam T_IsEncryption direction in which to operate the cipher /// \tparam T_IsEncryption direction in which to operate the cipher
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher, GCM_TablesOption T_TablesOption, bool T_IsEncryption> template <class T_BlockCipher, GCM_TablesOption T_TablesOption, bool T_IsEncryption>
class GCM_Final : public GCM_Base class GCM_Final : public GCM_Base
{ {
@ -112,16 +112,16 @@ private:
typename T_BlockCipher::Encryption m_cipher; typename T_BlockCipher::Encryption m_cipher;
}; };
//! \class GCM /// \class GCM
//! \brief GCM block cipher mode of operation /// \brief GCM block cipher mode of operation
//! \tparam T_BlockCipher block cipher /// \tparam T_BlockCipher block cipher
//! \tparam T_TablesOption table size, either \p GCM_2K_Tables or \p GCM_64K_Tables /// \tparam T_TablesOption table size, either \p GCM_2K_Tables or \p GCM_64K_Tables
//! \details \p GCM provides the \p Encryption and \p Decryption typedef. See GCM_Base /// \details \p GCM provides the \p Encryption and \p Decryption typedef. See GCM_Base
//! and GCM_Final for the AuthenticatedSymmetricCipher implementation. /// and GCM_Final for the AuthenticatedSymmetricCipher implementation.
//! \sa <a href="http://www.cryptopp.com/wiki/GCM_Mode">GCM Mode</a> and /// \sa <a href="http://www.cryptopp.com/wiki/GCM_Mode">GCM Mode</a> and
//! <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
//! \since Crypto++ 5.6.0 /// \since Crypto++ 5.6.0
template <class T_BlockCipher, GCM_TablesOption T_TablesOption=GCM_2K_Tables> template <class T_BlockCipher, GCM_TablesOption T_TablesOption=GCM_2K_Tables>
struct GCM : public AuthenticatedSymmetricCipherDocumentation struct GCM : public AuthenticatedSymmetricCipherDocumentation
{ {

View File

@ -1,7 +1,7 @@
// gf256.h - originally written and placed in the public domain by Wei Dai // gf256.h - originally written and placed in the public domain by Wei Dai
//! \file gf256.h /// \file gf256.h
//! \brief Classes and functions for schemes over GF(256) /// \brief Classes and functions for schemes over GF(256)
#ifndef CRYPTOPP_GF256_H #ifndef CRYPTOPP_GF256_H
#define CRYPTOPP_GF256_H #define CRYPTOPP_GF256_H
@ -11,7 +11,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief GF(256) with polynomial basis /// \brief GF(256) with polynomial basis
class GF256 class GF256
{ {
public: public:

View File

@ -1,7 +1,7 @@
// gf2_32.h - originally written and placed in the public domain by Wei Dai // gf2_32.h - originally written and placed in the public domain by Wei Dai
//! \file gf2_32.h /// \file gf2_32.h
//! \brief Classes and functions for schemes over GF(2^32) /// \brief Classes and functions for schemes over GF(2^32)
#ifndef CRYPTOPP_GF2_32_H #ifndef CRYPTOPP_GF2_32_H
#define CRYPTOPP_GF2_32_H #define CRYPTOPP_GF2_32_H
@ -12,7 +12,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief GF(2^32) with polynomial basis /// \brief GF(2^32) with polynomial basis
class GF2_32 class GF2_32
{ {
public: public:

216
gf2n.h
View File

@ -1,7 +1,7 @@
// gf2n.h - originally written and placed in the public domain by Wei Dai // gf2n.h - originally written and placed in the public domain by Wei Dai
//! \file gf2n.h /// \file gf2n.h
//! \brief Classes and functions for schemes over GF(2^n) /// \brief Classes and functions for schemes over GF(2^n)
#ifndef CRYPTOPP_GF2N_H #ifndef CRYPTOPP_GF2N_H
#define CRYPTOPP_GF2N_H #define CRYPTOPP_GF2N_H
@ -21,14 +21,14 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Polynomial with Coefficients in GF(2) /// \brief Polynomial with Coefficients in GF(2)
/*! \nosubgrouping */ /*! \nosubgrouping */
class CRYPTOPP_DLL PolynomialMod2 class CRYPTOPP_DLL PolynomialMod2
{ {
public: public:
//! \name ENUMS, EXCEPTIONS, and TYPEDEFS /// \name ENUMS, EXCEPTIONS, and TYPEDEFS
//@{ //@{
//! \brief Excpetion thrown when divide by zero is encountered /// \brief Excpetion thrown when divide by zero is encountered
class DivideByZero : public Exception class DivideByZero : public Exception
{ {
public: public:
@ -38,209 +38,209 @@ public:
typedef unsigned int RandomizationParameter; typedef unsigned int RandomizationParameter;
//@} //@}
//! \name CREATORS /// \name CREATORS
//@{ //@{
//! \brief Construct the zero polynomial /// \brief Construct the zero polynomial
PolynomialMod2(); PolynomialMod2();
//! Copy construct a PolynomialMod2 /// Copy construct a PolynomialMod2
PolynomialMod2(const PolynomialMod2& t); PolynomialMod2(const PolynomialMod2& t);
//! \brief Construct a PolynomialMod2 from a word /// \brief Construct a PolynomialMod2 from a word
//! \details value should be encoded with the least significant bit as coefficient to x^0 /// \details value should be encoded with the least significant bit as coefficient to x^0
//! and most significant bit as coefficient to x^(WORD_BITS-1) /// and most significant bit as coefficient to x^(WORD_BITS-1)
//! bitLength denotes how much memory to allocate initially /// bitLength denotes how much memory to allocate initially
PolynomialMod2(word value, size_t bitLength=WORD_BITS); PolynomialMod2(word value, size_t bitLength=WORD_BITS);
//! \brief Construct a PolynomialMod2 from big-endian byte array /// \brief Construct a PolynomialMod2 from big-endian byte array
PolynomialMod2(const byte *encodedPoly, size_t byteCount) PolynomialMod2(const byte *encodedPoly, size_t byteCount)
{Decode(encodedPoly, byteCount);} {Decode(encodedPoly, byteCount);}
//! \brief Construct a PolynomialMod2 from big-endian form stored in a BufferedTransformation /// \brief Construct a PolynomialMod2 from big-endian form stored in a BufferedTransformation
PolynomialMod2(BufferedTransformation &encodedPoly, size_t byteCount) PolynomialMod2(BufferedTransformation &encodedPoly, size_t byteCount)
{Decode(encodedPoly, byteCount);} {Decode(encodedPoly, byteCount);}
//! \brief Create a uniformly distributed random polynomial /// \brief Create a uniformly distributed random polynomial
//! \details Create a random polynomial uniformly distributed over all polynomials with degree less than bitcount /// \details Create a random polynomial uniformly distributed over all polynomials with degree less than bitcount
PolynomialMod2(RandomNumberGenerator &rng, size_t bitcount) PolynomialMod2(RandomNumberGenerator &rng, size_t bitcount)
{Randomize(rng, bitcount);} {Randomize(rng, bitcount);}
//! \brief Provides x^i /// \brief Provides x^i
//! \returns x^i /// \returns x^i
static PolynomialMod2 CRYPTOPP_API Monomial(size_t i); static PolynomialMod2 CRYPTOPP_API Monomial(size_t i);
//! \brief Provides x^t0 + x^t1 + x^t2 /// \brief Provides x^t0 + x^t1 + x^t2
//! \returns x^t0 + x^t1 + x^t2 /// \returns x^t0 + x^t1 + x^t2
static PolynomialMod2 CRYPTOPP_API Trinomial(size_t t0, size_t t1, size_t t2); static PolynomialMod2 CRYPTOPP_API Trinomial(size_t t0, size_t t1, size_t t2);
//! \brief Provides x^t0 + x^t1 + x^t2 + x^t3 + x^t4 /// \brief Provides x^t0 + x^t1 + x^t2 + x^t3 + x^t4
//! \returns x^t0 + x^t1 + x^t2 + x^t3 + x^t4 /// \returns x^t0 + x^t1 + x^t2 + x^t3 + x^t4
static PolynomialMod2 CRYPTOPP_API Pentanomial(size_t t0, size_t t1, size_t t2, size_t t3, size_t t4); static PolynomialMod2 CRYPTOPP_API Pentanomial(size_t t0, size_t t1, size_t t2, size_t t3, size_t t4);
//! \brief Provides x^(n-1) + ... + x + 1 /// \brief Provides x^(n-1) + ... + x + 1
//! \returns x^(n-1) + ... + x + 1 /// \returns x^(n-1) + ... + x + 1
static PolynomialMod2 CRYPTOPP_API AllOnes(size_t n); static PolynomialMod2 CRYPTOPP_API AllOnes(size_t n);
//! \brief The Zero polinomial /// \brief The Zero polinomial
//! \returns the zero polynomial /// \returns the zero polynomial
static const PolynomialMod2 & CRYPTOPP_API Zero(); static const PolynomialMod2 & CRYPTOPP_API Zero();
//! \brief The One polinomial /// \brief The One polinomial
//! \returns the one polynomial /// \returns the one polynomial
static const PolynomialMod2 & CRYPTOPP_API One(); static const PolynomialMod2 & CRYPTOPP_API One();
//@} //@}
//! \name ENCODE/DECODE /// \name ENCODE/DECODE
//@{ //@{
//! minimum number of bytes to encode this polynomial /// minimum number of bytes to encode this polynomial
/*! MinEncodedSize of 0 is 1 */ /*! MinEncodedSize of 0 is 1 */
unsigned int MinEncodedSize() const {return STDMAX(1U, ByteCount());} unsigned int MinEncodedSize() const {return STDMAX(1U, ByteCount());}
//! encode in big-endian format /// encode in big-endian format
//! \details if outputLen < MinEncodedSize, the most significant bytes will be dropped /// \details if outputLen < MinEncodedSize, the most significant bytes will be dropped
//! if outputLen > MinEncodedSize, the most significant bytes will be padded /// if outputLen > MinEncodedSize, the most significant bytes will be padded
void Encode(byte *output, size_t outputLen) const; void Encode(byte *output, size_t outputLen) const;
//! ///
void Encode(BufferedTransformation &bt, size_t outputLen) const; void Encode(BufferedTransformation &bt, size_t outputLen) const;
//! ///
void Decode(const byte *input, size_t inputLen); void Decode(const byte *input, size_t inputLen);
//! ///
//* Precondition: bt.MaxRetrievable() >= inputLen //* Precondition: bt.MaxRetrievable() >= inputLen
void Decode(BufferedTransformation &bt, size_t inputLen); void Decode(BufferedTransformation &bt, size_t inputLen);
//! encode value as big-endian octet string /// encode value as big-endian octet string
void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const; void DEREncodeAsOctetString(BufferedTransformation &bt, size_t length) const;
//! decode value as big-endian octet string /// decode value as big-endian octet string
void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length); void BERDecodeAsOctetString(BufferedTransformation &bt, size_t length);
//@} //@}
//! \name ACCESSORS /// \name ACCESSORS
//@{ //@{
//! number of significant bits = Degree() + 1 /// number of significant bits = Degree() + 1
unsigned int BitCount() const; unsigned int BitCount() const;
//! number of significant bytes = ceiling(BitCount()/8) /// number of significant bytes = ceiling(BitCount()/8)
unsigned int ByteCount() const; unsigned int ByteCount() const;
//! number of significant words = ceiling(ByteCount()/sizeof(word)) /// number of significant words = ceiling(ByteCount()/sizeof(word))
unsigned int WordCount() const; unsigned int WordCount() const;
//! return the n-th bit, n=0 being the least significant bit /// return the n-th bit, n=0 being the least significant bit
bool GetBit(size_t n) const {return GetCoefficient(n)!=0;} bool GetBit(size_t n) const {return GetCoefficient(n)!=0;}
//! return the n-th byte /// return the n-th byte
byte GetByte(size_t n) const; byte GetByte(size_t n) const;
//! the zero polynomial will return a degree of -1 /// the zero polynomial will return a degree of -1
signed int Degree() const {return (signed int)(BitCount()-1U);} signed int Degree() const {return (signed int)(BitCount()-1U);}
//! degree + 1 /// degree + 1
unsigned int CoefficientCount() const {return BitCount();} unsigned int CoefficientCount() const {return BitCount();}
//! return coefficient for x^i /// return coefficient for x^i
int GetCoefficient(size_t i) const int GetCoefficient(size_t i) const
{return (i/WORD_BITS < reg.size()) ? int(reg[i/WORD_BITS] >> (i % WORD_BITS)) & 1 : 0;} {return (i/WORD_BITS < reg.size()) ? int(reg[i/WORD_BITS] >> (i % WORD_BITS)) & 1 : 0;}
//! return coefficient for x^i /// return coefficient for x^i
int operator[](unsigned int i) const {return GetCoefficient(i);} int operator[](unsigned int i) const {return GetCoefficient(i);}
//! ///
bool IsZero() const {return !*this;} bool IsZero() const {return !*this;}
//! ///
bool Equals(const PolynomialMod2 &rhs) const; bool Equals(const PolynomialMod2 &rhs) const;
//@} //@}
//! \name MANIPULATORS /// \name MANIPULATORS
//@{ //@{
//! ///
PolynomialMod2& operator=(const PolynomialMod2& t); PolynomialMod2& operator=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator&=(const PolynomialMod2& t); PolynomialMod2& operator&=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator^=(const PolynomialMod2& t); PolynomialMod2& operator^=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator+=(const PolynomialMod2& t) {return *this ^= t;} PolynomialMod2& operator+=(const PolynomialMod2& t) {return *this ^= t;}
//! ///
PolynomialMod2& operator-=(const PolynomialMod2& t) {return *this ^= t;} PolynomialMod2& operator-=(const PolynomialMod2& t) {return *this ^= t;}
//! ///
PolynomialMod2& operator*=(const PolynomialMod2& t); PolynomialMod2& operator*=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator/=(const PolynomialMod2& t); PolynomialMod2& operator/=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator%=(const PolynomialMod2& t); PolynomialMod2& operator%=(const PolynomialMod2& t);
//! ///
PolynomialMod2& operator<<=(unsigned int); PolynomialMod2& operator<<=(unsigned int);
//! ///
PolynomialMod2& operator>>=(unsigned int); PolynomialMod2& operator>>=(unsigned int);
//! ///
void Randomize(RandomNumberGenerator &rng, size_t bitcount); void Randomize(RandomNumberGenerator &rng, size_t bitcount);
//! ///
void SetBit(size_t i, int value = 1); void SetBit(size_t i, int value = 1);
//! set the n-th byte to value /// set the n-th byte to value
void SetByte(size_t n, byte value); void SetByte(size_t n, byte value);
//! ///
void SetCoefficient(size_t i, int value) {SetBit(i, value);} void SetCoefficient(size_t i, int value) {SetBit(i, value);}
//! ///
void swap(PolynomialMod2 &a) {reg.swap(a.reg);} void swap(PolynomialMod2 &a) {reg.swap(a.reg);}
//@} //@}
//! \name UNARY OPERATORS /// \name UNARY OPERATORS
//@{ //@{
//! ///
bool operator!() const; bool operator!() const;
//! ///
PolynomialMod2 operator+() const {return *this;} PolynomialMod2 operator+() const {return *this;}
//! ///
PolynomialMod2 operator-() const {return *this;} PolynomialMod2 operator-() const {return *this;}
//@} //@}
//! \name BINARY OPERATORS /// \name BINARY OPERATORS
//@{ //@{
//! ///
PolynomialMod2 And(const PolynomialMod2 &b) const; PolynomialMod2 And(const PolynomialMod2 &b) const;
//! ///
PolynomialMod2 Xor(const PolynomialMod2 &b) const; PolynomialMod2 Xor(const PolynomialMod2 &b) const;
//! ///
PolynomialMod2 Plus(const PolynomialMod2 &b) const {return Xor(b);} PolynomialMod2 Plus(const PolynomialMod2 &b) const {return Xor(b);}
//! ///
PolynomialMod2 Minus(const PolynomialMod2 &b) const {return Xor(b);} PolynomialMod2 Minus(const PolynomialMod2 &b) const {return Xor(b);}
//! ///
PolynomialMod2 Times(const PolynomialMod2 &b) const; PolynomialMod2 Times(const PolynomialMod2 &b) const;
//! ///
PolynomialMod2 DividedBy(const PolynomialMod2 &b) const; PolynomialMod2 DividedBy(const PolynomialMod2 &b) const;
//! ///
PolynomialMod2 Modulo(const PolynomialMod2 &b) const; PolynomialMod2 Modulo(const PolynomialMod2 &b) const;
//! ///
PolynomialMod2 operator>>(unsigned int n) const; PolynomialMod2 operator>>(unsigned int n) const;
//! ///
PolynomialMod2 operator<<(unsigned int n) const; PolynomialMod2 operator<<(unsigned int n) const;
//@} //@}
//! \name OTHER ARITHMETIC FUNCTIONS /// \name OTHER ARITHMETIC FUNCTIONS
//@{ //@{
//! sum modulo 2 of all coefficients /// sum modulo 2 of all coefficients
unsigned int Parity() const; unsigned int Parity() const;
//! check for irreducibility /// check for irreducibility
bool IsIrreducible() const; bool IsIrreducible() const;
//! is always zero since we're working modulo 2 /// is always zero since we're working modulo 2
PolynomialMod2 Doubled() const {return Zero();} PolynomialMod2 Doubled() const {return Zero();}
//! ///
PolynomialMod2 Squared() const; PolynomialMod2 Squared() const;
//! only 1 is a unit /// only 1 is a unit
bool IsUnit() const {return Equals(One());} bool IsUnit() const {return Equals(One());}
//! return inverse if *this is a unit, otherwise return 0 /// return inverse if *this is a unit, otherwise return 0
PolynomialMod2 MultiplicativeInverse() const {return IsUnit() ? One() : Zero();} PolynomialMod2 MultiplicativeInverse() const {return IsUnit() ? One() : Zero();}
//! greatest common divisor /// greatest common divisor
static PolynomialMod2 CRYPTOPP_API Gcd(const PolynomialMod2 &a, const PolynomialMod2 &n); static PolynomialMod2 CRYPTOPP_API Gcd(const PolynomialMod2 &a, const PolynomialMod2 &n);
//! calculate multiplicative inverse of *this mod n /// calculate multiplicative inverse of *this mod n
PolynomialMod2 InverseMod(const PolynomialMod2 &) const; PolynomialMod2 InverseMod(const PolynomialMod2 &) const;
//! calculate r and q such that (a == d*q + r) && (deg(r) < deg(d)) /// calculate r and q such that (a == d*q + r) && (deg(r) < deg(d))
static void CRYPTOPP_API Divide(PolynomialMod2 &r, PolynomialMod2 &q, const PolynomialMod2 &a, const PolynomialMod2 &d); static void CRYPTOPP_API Divide(PolynomialMod2 &r, PolynomialMod2 &q, const PolynomialMod2 &a, const PolynomialMod2 &d);
//@} //@}
//! \name INPUT/OUTPUT /// \name INPUT/OUTPUT
//@{ //@{
//! ///
friend std::ostream& operator<<(std::ostream& out, const PolynomialMod2 &a); friend std::ostream& operator<<(std::ostream& out, const PolynomialMod2 &a);
//@} //@}
@ -250,37 +250,37 @@ private:
SecWordBlock reg; SecWordBlock reg;
}; };
//! ///
inline bool operator==(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator==(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return a.Equals(b);} {return a.Equals(b);}
//! ///
inline bool operator!=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator!=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return !(a==b);} {return !(a==b);}
//! compares degree /// compares degree
inline bool operator> (const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator> (const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return a.Degree() > b.Degree();} {return a.Degree() > b.Degree();}
//! compares degree /// compares degree
inline bool operator>=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator>=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return a.Degree() >= b.Degree();} {return a.Degree() >= b.Degree();}
//! compares degree /// compares degree
inline bool operator< (const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator< (const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return a.Degree() < b.Degree();} {return a.Degree() < b.Degree();}
//! compares degree /// compares degree
inline bool operator<=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) inline bool operator<=(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b)
{return a.Degree() <= b.Degree();} {return a.Degree() <= b.Degree();}
//! ///
inline CryptoPP::PolynomialMod2 operator&(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.And(b);} inline CryptoPP::PolynomialMod2 operator&(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.And(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator^(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Xor(b);} inline CryptoPP::PolynomialMod2 operator^(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Xor(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator+(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Plus(b);} inline CryptoPP::PolynomialMod2 operator+(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Plus(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator-(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Minus(b);} inline CryptoPP::PolynomialMod2 operator-(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Minus(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator*(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Times(b);} inline CryptoPP::PolynomialMod2 operator*(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Times(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator/(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.DividedBy(b);} inline CryptoPP::PolynomialMod2 operator/(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.DividedBy(b);}
//! ///
inline CryptoPP::PolynomialMod2 operator%(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Modulo(b);} inline CryptoPP::PolynomialMod2 operator%(const CryptoPP::PolynomialMod2 &a, const CryptoPP::PolynomialMod2 &b) {return a.Modulo(b);}
// CodeWarrior 8 workaround: put these template instantiations after overloaded operator declarations, // CodeWarrior 8 workaround: put these template instantiations after overloaded operator declarations,
@ -291,7 +291,7 @@ CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<PolynomialMod2>;
CRYPTOPP_DLL_TEMPLATE_CLASS EuclideanDomainOf<PolynomialMod2>; CRYPTOPP_DLL_TEMPLATE_CLASS EuclideanDomainOf<PolynomialMod2>;
CRYPTOPP_DLL_TEMPLATE_CLASS QuotientRing<EuclideanDomainOf<PolynomialMod2> >; CRYPTOPP_DLL_TEMPLATE_CLASS QuotientRing<EuclideanDomainOf<PolynomialMod2> >;
//! \brief GF(2^n) with Polynomial Basis /// \brief GF(2^n) with Polynomial Basis
class CRYPTOPP_DLL GF2NP : public QuotientRing<EuclideanDomainOf<PolynomialMod2> > class CRYPTOPP_DLL GF2NP : public QuotientRing<EuclideanDomainOf<PolynomialMod2> >
{ {
public: public:
@ -327,7 +327,7 @@ protected:
unsigned int m; unsigned int m;
}; };
//! \brief GF(2^n) with Trinomial Basis /// \brief GF(2^n) with Trinomial Basis
class CRYPTOPP_DLL GF2NT : public GF2NP class CRYPTOPP_DLL GF2NT : public GF2NP
{ {
public: public:
@ -351,7 +351,7 @@ private:
mutable PolynomialMod2 result; mutable PolynomialMod2 result;
}; };
//! \brief GF(2^n) with Pentanomial Basis /// \brief GF(2^n) with Pentanomial Basis
class CRYPTOPP_DLL GF2NPP : public GF2NP class CRYPTOPP_DLL GF2NPP : public GF2NP
{ {
public: public:

View File

@ -2,8 +2,8 @@
// RFC6979 deterministic signatures added by Douglas Roark // RFC6979 deterministic signatures added by Douglas Roark
// ECGDSA added by Jeffrey Walton // ECGDSA added by Jeffrey Walton
//! \file gfpcrypt.h /// \file gfpcrypt.h
//! \brief Classes and functions for schemes based on Discrete Logs (DL) over GF(p) /// \brief Classes and functions for schemes based on Discrete Logs (DL) over GF(p)
#ifndef CRYPTOPP_GFPCRYPT_H #ifndef CRYPTOPP_GFPCRYPT_H
#define CRYPTOPP_GFPCRYPT_H #define CRYPTOPP_GFPCRYPT_H
@ -30,8 +30,8 @@ NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters<Integer>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters<Integer>;
//! \class DL_GroupParameters_IntegerBased /// \class DL_GroupParameters_IntegerBased
//! \brief Integer-based GroupParameters specialization /// \brief Integer-based GroupParameters specialization
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public ASN1CryptoMaterial<DL_GroupParameters<Integer> > class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public ASN1CryptoMaterial<DL_GroupParameters<Integer> >
{ {
typedef DL_GroupParameters_IntegerBased ThisClass; typedef DL_GroupParameters_IntegerBased ThisClass;
@ -39,30 +39,30 @@ class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBased : public A
public: public:
virtual ~DL_GroupParameters_IntegerBased() {} virtual ~DL_GroupParameters_IntegerBased() {}
//! \brief Initialize a group parameters over integers /// \brief Initialize a group parameters over integers
//! \param params the group parameters /// \param params the group parameters
void Initialize(const DL_GroupParameters_IntegerBased &params) void Initialize(const DL_GroupParameters_IntegerBased &params)
{Initialize(params.GetModulus(), params.GetSubgroupOrder(), params.GetSubgroupGenerator());} {Initialize(params.GetModulus(), params.GetSubgroupOrder(), params.GetSubgroupGenerator());}
//! \brief Create a group parameters over integers /// \brief Create a group parameters over integers
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param pbits the size of p, in bits /// \param pbits the size of p, in bits
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, unsigned int pbits) void Initialize(RandomNumberGenerator &rng, unsigned int pbits)
{GenerateRandom(rng, MakeParameters("ModulusSize", (int)pbits));} {GenerateRandom(rng, MakeParameters("ModulusSize", (int)pbits));}
//! \brief Initialize a group parameters over integers /// \brief Initialize a group parameters over integers
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
void Initialize(const Integer &p, const Integer &g) void Initialize(const Integer &p, const Integer &g)
{SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(ComputeGroupOrder(p)/2);} {SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(ComputeGroupOrder(p)/2);}
//! \brief Initialize a group parameters over integers /// \brief Initialize a group parameters over integers
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
void Initialize(const Integer &p, const Integer &q, const Integer &g) void Initialize(const Integer &p, const Integer &q, const Integer &g)
{SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(q);} {SetModulusAndSubgroupGenerator(p, g); SetSubgroupOrder(q);}
@ -113,10 +113,10 @@ private:
Integer m_q; Integer m_q;
}; };
//! \class DL_GroupParameters_IntegerBasedImpl /// \class DL_GroupParameters_IntegerBasedImpl
//! \brief Integer-based GroupParameters default implementation /// \brief Integer-based GroupParameters default implementation
//! \tparam GROUP_PRECOMP group parameters precomputation specialization /// \tparam GROUP_PRECOMP group parameters precomputation specialization
//! \tparam BASE_PRECOMP base class precomputation specialization /// \tparam BASE_PRECOMP base class precomputation specialization
template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<typename GROUP_PRECOMP::Element> > template <class GROUP_PRECOMP, class BASE_PRECOMP = DL_FixedBasePrecomputationImpl<typename GROUP_PRECOMP::Element> >
class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBasedImpl : public DL_GroupParametersImpl<GROUP_PRECOMP, BASE_PRECOMP, DL_GroupParameters_IntegerBased> class CRYPTOPP_NO_VTABLE DL_GroupParameters_IntegerBasedImpl : public DL_GroupParametersImpl<GROUP_PRECOMP, BASE_PRECOMP, DL_GroupParameters_IntegerBased>
{ {
@ -154,8 +154,8 @@ public:
CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>;
//! \class DL_GroupParameters_GFP /// \class DL_GroupParameters_GFP
//! \brief GF(p) group parameters /// \brief GF(p) group parameters
class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation> class CRYPTOPP_DLL DL_GroupParameters_GFP : public DL_GroupParameters_IntegerBasedImpl<ModExpPrecomputation>
{ {
public: public:
@ -179,8 +179,8 @@ protected:
int GetFieldType() const {return 1;} int GetFieldType() const {return 1;}
}; };
//! \class DL_GroupParameters_GFP /// \class DL_GroupParameters_GFP
//! \brief GF(p) group parameters that default to safe primes /// \brief GF(p) group parameters that default to safe primes
class CRYPTOPP_DLL DL_GroupParameters_GFP_DefaultSafePrime : public DL_GroupParameters_GFP class CRYPTOPP_DLL DL_GroupParameters_GFP_DefaultSafePrime : public DL_GroupParameters_GFP
{ {
public: public:
@ -192,9 +192,9 @@ protected:
unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;} unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;}
}; };
//! \class DL_Algorithm_GDSA /// \class DL_Algorithm_GDSA
//! \brief GDSA algorithm /// \brief GDSA algorithm
//! \tparam T FieldElement type or class /// \tparam T FieldElement type or class
template <class T> template <class T>
class DL_Algorithm_GDSA : public DL_ElgamalLikeSignatureAlgorithm<T> class DL_Algorithm_GDSA : public DL_ElgamalLikeSignatureAlgorithm<T>
{ {
@ -226,13 +226,13 @@ public:
} }
}; };
//! \class DL_Algorithm_DSA_RFC6979 /// \class DL_Algorithm_DSA_RFC6979
//! \brief DSA signature algorithm based on RFC 6979 /// \brief DSA signature algorithm based on RFC 6979
//! \tparam T FieldElement type or class /// \tparam T FieldElement type or class
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the /// \sa <a href="http://tools.ietf.org/rfc/rfc6979.txt">RFC 6979, Deterministic Usage of the
//! Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a> /// Digital Signature Algorithm (DSA) and Elliptic Curve Digital Signature Algorithm (ECDSA)</a>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T, class H> template <class T, class H>
class DL_Algorithm_DSA_RFC6979 : public DL_Algorithm_GDSA<T>, public DeterministicSignatureAlgorithm class DL_Algorithm_DSA_RFC6979 : public DL_Algorithm_GDSA<T>, public DeterministicSignatureAlgorithm
{ {
@ -394,14 +394,14 @@ private:
mutable HMAC<H> m_hmac; mutable HMAC<H> m_hmac;
}; };
//! \class DL_Algorithm_GDSA_ISO15946 /// \class DL_Algorithm_GDSA_ISO15946
//! \brief German Digital Signature Algorithm /// \brief German Digital Signature Algorithm
//! \tparam T FieldElement type or class /// \tparam T FieldElement type or class
//! \details The Digital Signature Scheme ECGDSA does not define the algorithm over integers. Rather, the /// \details The Digital Signature Scheme ECGDSA does not define the algorithm over integers. Rather, the
//! signature algorithm is only defined over elliptic curves. However, The library design is such that the /// signature algorithm is only defined over elliptic curves. However, The library design is such that the
//! generic algorithm reside in <tt>gfpcrypt.h</tt>. /// generic algorithm reside in <tt>gfpcrypt.h</tt>.
//! \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf"> /// \sa Erwin Hess, Marcus Schafheutle, and Pascale Serf <A HREF="http://www.teletrust.de/fileadmin/files/oid/ecgdsa_final.pdf">
//! The Digital Signature Scheme ECGDSA (October 24, 2006)</A> /// The Digital Signature Scheme ECGDSA (October 24, 2006)</A>
template <class T> template <class T>
class DL_Algorithm_GDSA_ISO15946 : public DL_ElgamalLikeSignatureAlgorithm<T> class DL_Algorithm_GDSA_ISO15946 : public DL_ElgamalLikeSignatureAlgorithm<T>
{ {
@ -441,9 +441,9 @@ CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_DSA_RFC6979<Integer, SHA256>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_DSA_RFC6979<Integer, SHA384>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_DSA_RFC6979<Integer, SHA384>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_DSA_RFC6979<Integer, SHA512>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_Algorithm_DSA_RFC6979<Integer, SHA512>;
//! \class DL_Algorithm_NR /// \class DL_Algorithm_NR
//! \brief NR algorithm /// \brief NR algorithm
//! \tparam T FieldElement type or class /// \tparam T FieldElement type or class
template <class T> template <class T>
class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T> class DL_Algorithm_NR : public DL_ElgamalLikeSignatureAlgorithm<T>
{ {
@ -471,34 +471,34 @@ public:
} }
}; };
//! \class DL_PublicKey_GFP /// \class DL_PublicKey_GFP
//! \brief Discrete Log (DL) public key in GF(p) groups /// \brief Discrete Log (DL) public key in GF(p) groups
//! \tparam GP GroupParameters derived class /// \tparam GP GroupParameters derived class
//! \details DSA public key format is defined in 7.3.3 of RFC 2459. The private key format is defined in 12.9 of PKCS #11 v2.10. /// \details DSA public key format is defined in 7.3.3 of RFC 2459. The private key format is defined in 12.9 of PKCS #11 v2.10.
template <class GP> template <class GP>
class DL_PublicKey_GFP : public DL_PublicKeyImpl<GP> class DL_PublicKey_GFP : public DL_PublicKeyImpl<GP>
{ {
public: public:
virtual ~DL_PublicKey_GFP() {} virtual ~DL_PublicKey_GFP() {}
//! \brief Initialize a public key over GF(p) /// \brief Initialize a public key over GF(p)
//! \param params the group parameters /// \param params the group parameters
//! \param y the public element /// \param y the public element
void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &y) void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &y)
{this->AccessGroupParameters().Initialize(params); this->SetPublicElement(y);} {this->AccessGroupParameters().Initialize(params); this->SetPublicElement(y);}
//! \brief Initialize a public key over GF(p) /// \brief Initialize a public key over GF(p)
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
//! \param y the public element /// \param y the public element
void Initialize(const Integer &p, const Integer &g, const Integer &y) void Initialize(const Integer &p, const Integer &g, const Integer &y)
{this->AccessGroupParameters().Initialize(p, g); this->SetPublicElement(y);} {this->AccessGroupParameters().Initialize(p, g); this->SetPublicElement(y);}
//! \brief Initialize a public key over GF(p) /// \brief Initialize a public key over GF(p)
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
//! \param y the public element /// \param y the public element
void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &y) void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &y)
{this->AccessGroupParameters().Initialize(p, q, g); this->SetPublicElement(y);} {this->AccessGroupParameters().Initialize(p, q, g); this->SetPublicElement(y);}
@ -509,63 +509,63 @@ public:
{this->GetPublicElement().DEREncode(bt);} {this->GetPublicElement().DEREncode(bt);}
}; };
//! \class DL_PrivateKey_GFP /// \class DL_PrivateKey_GFP
//! \brief Discrete Log (DL) private key in GF(p) groups /// \brief Discrete Log (DL) private key in GF(p) groups
//! \tparam GP GroupParameters derived class /// \tparam GP GroupParameters derived class
template <class GP> template <class GP>
class DL_PrivateKey_GFP : public DL_PrivateKeyImpl<GP> class DL_PrivateKey_GFP : public DL_PrivateKeyImpl<GP>
{ {
public: public:
virtual ~DL_PrivateKey_GFP(); virtual ~DL_PrivateKey_GFP();
//! \brief Create a private key /// \brief Create a private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param modulusBits the size of the modulus, in bits /// \param modulusBits the size of the modulus, in bits
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits) void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits)
{this->GenerateRandomWithKeySize(rng, modulusBits);} {this->GenerateRandomWithKeySize(rng, modulusBits);}
//! \brief Create a private key /// \brief Create a private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &g) void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &g)
{this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupGenerator", g));} {this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupGenerator", g));}
//! \brief Create a private key /// \brief Create a private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &q, const Integer &g) void Initialize(RandomNumberGenerator &rng, const Integer &p, const Integer &q, const Integer &g)
{this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupOrder", q)("SubgroupGenerator", g));} {this->GenerateRandom(rng, MakeParameters("Modulus", p)("SubgroupOrder", q)("SubgroupGenerator", g));}
//! \brief Initialize a private key over GF(p) /// \brief Initialize a private key over GF(p)
//! \param params the group parameters /// \param params the group parameters
//! \param x the private exponent /// \param x the private exponent
void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &x) void Initialize(const DL_GroupParameters_IntegerBased &params, const Integer &x)
{this->AccessGroupParameters().Initialize(params); this->SetPrivateExponent(x);} {this->AccessGroupParameters().Initialize(params); this->SetPrivateExponent(x);}
//! \brief Initialize a private key over GF(p) /// \brief Initialize a private key over GF(p)
//! \param p the modulus /// \param p the modulus
//! \param g the generator /// \param g the generator
//! \param x the private exponent /// \param x the private exponent
void Initialize(const Integer &p, const Integer &g, const Integer &x) void Initialize(const Integer &p, const Integer &g, const Integer &x)
{this->AccessGroupParameters().Initialize(p, g); this->SetPrivateExponent(x);} {this->AccessGroupParameters().Initialize(p, g); this->SetPrivateExponent(x);}
//! \brief Initialize a private key over GF(p) /// \brief Initialize a private key over GF(p)
//! \param p the modulus /// \param p the modulus
//! \param q the subgroup order /// \param q the subgroup order
//! \param g the generator /// \param g the generator
//! \param x the private exponent /// \param x the private exponent
void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &x) void Initialize(const Integer &p, const Integer &q, const Integer &g, const Integer &x)
{this->AccessGroupParameters().Initialize(p, q, g); this->SetPrivateExponent(x);} {this->AccessGroupParameters().Initialize(p, q, g); this->SetPrivateExponent(x);}
}; };
@ -574,8 +574,8 @@ public:
template <class GP> template <class GP>
DL_PrivateKey_GFP<GP>::~DL_PrivateKey_GFP() {} DL_PrivateKey_GFP<GP>::~DL_PrivateKey_GFP() {}
//! \class DL_SignatureKeys_GFP /// \class DL_SignatureKeys_GFP
//! \brief Discrete Log (DL) signing/verification keys in GF(p) groups /// \brief Discrete Log (DL) signing/verification keys in GF(p) groups
struct DL_SignatureKeys_GFP struct DL_SignatureKeys_GFP
{ {
typedef DL_GroupParameters_GFP GroupParameters; typedef DL_GroupParameters_GFP GroupParameters;
@ -583,8 +583,8 @@ struct DL_SignatureKeys_GFP
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey; typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
}; };
//! \class DL_CryptoKeys_GFP /// \class DL_CryptoKeys_GFP
//! \brief Discrete Log (DL) encryption/decryption keys in GF(p) groups /// \brief Discrete Log (DL) encryption/decryption keys in GF(p) groups
struct DL_CryptoKeys_GFP struct DL_CryptoKeys_GFP
{ {
typedef DL_GroupParameters_GFP_DefaultSafePrime GroupParameters; typedef DL_GroupParameters_GFP_DefaultSafePrime GroupParameters;
@ -592,11 +592,11 @@ struct DL_CryptoKeys_GFP
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey; typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
}; };
//! \class DL_PublicKey_GFP_OldFormat /// \class DL_PublicKey_GFP_OldFormat
//! \brief Discrete Log (DL) public key in GF(p) groups /// \brief Discrete Log (DL) public key in GF(p) groups
//! \tparam BASE GroupParameters derived class /// \tparam BASE GroupParameters derived class
//! \deprecated This implementation uses a non-standard Crypto++ key format. New implementations /// \deprecated This implementation uses a non-standard Crypto++ key format. New implementations
//! should use DL_PublicKey_GFP and DL_PrivateKey_GFP /// should use DL_PublicKey_GFP and DL_PrivateKey_GFP
template <class BASE> template <class BASE>
class DL_PublicKey_GFP_OldFormat : public BASE class DL_PublicKey_GFP_OldFormat : public BASE
{ {
@ -637,11 +637,11 @@ public:
} }
}; };
//! \class DL_PrivateKey_GFP_OldFormat /// \class DL_PrivateKey_GFP_OldFormat
//! \brief Discrete Log (DL) private key in GF(p) groups /// \brief Discrete Log (DL) private key in GF(p) groups
//! \tparam BASE GroupParameters derived class /// \tparam BASE GroupParameters derived class
//! \deprecated This implementation uses a non-standard Crypto++ key format. New implementations /// \deprecated This implementation uses a non-standard Crypto++ key format. New implementations
//! should use DL_PublicKey_GFP and DL_PrivateKey_GFP /// should use DL_PublicKey_GFP and DL_PrivateKey_GFP
template <class BASE> template <class BASE>
class DL_PrivateKey_GFP_OldFormat : public BASE class DL_PrivateKey_GFP_OldFormat : public BASE
{ {
@ -684,11 +684,11 @@ public:
} }
}; };
//! \class GDSA /// \class GDSA
//! \brief DSA signature scheme /// \brief DSA signature scheme
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a>
//! \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2
template <class H> template <class H>
struct GDSA : public DL_SS< struct GDSA : public DL_SS<
DL_SignatureKeys_GFP, DL_SignatureKeys_GFP,
@ -698,10 +698,10 @@ struct GDSA : public DL_SS<
{ {
}; };
//! \class NR /// \class NR
//! \brief NR signature scheme /// \brief NR signature scheme
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#NR">NR</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#NR">NR</a>
template <class H> template <class H>
struct NR : public DL_SS< struct NR : public DL_SS<
DL_SignatureKeys_GFP, DL_SignatureKeys_GFP,
@ -711,10 +711,10 @@ struct NR : public DL_SS<
{ {
}; };
//! \class DL_GroupParameters_DSA /// \class DL_GroupParameters_DSA
//! \brief DSA group parameters /// \brief DSA group parameters
//! \details These are GF(p) group parameters that are allowed by the DSA standard /// \details These are GF(p) group parameters that are allowed by the DSA standard
//! \sa DL_Keys_DSA /// \sa DL_Keys_DSA
class CRYPTOPP_DLL DL_GroupParameters_DSA : public DL_GroupParameters_GFP class CRYPTOPP_DLL DL_GroupParameters_DSA : public DL_GroupParameters_GFP
{ {
public: public:
@ -735,21 +735,21 @@ public:
template <class H> template <class H>
class DSA2; class DSA2;
//! \class DL_Keys_DSA /// \class DL_Keys_DSA
//! \brief DSA keys /// \brief DSA keys
//! \sa DL_GroupParameters_DSA /// \sa DL_GroupParameters_DSA
struct DL_Keys_DSA struct DL_Keys_DSA
{ {
typedef DL_PublicKey_GFP<DL_GroupParameters_DSA> PublicKey; typedef DL_PublicKey_GFP<DL_GroupParameters_DSA> PublicKey;
typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA2<SHA1> > PrivateKey; typedef DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA2<SHA1> > PrivateKey;
}; };
//! \class DSA2 /// \class DSA2
//! \brief DSA signature scheme /// \brief DSA signature scheme
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \details The class is named DSA2 instead of DSA for backwards compatibility because DSA was a non-template class. /// \details The class is named DSA2 instead of DSA for backwards compatibility because DSA was a non-template class.
//! \sa <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">DSA</a>, as specified in FIPS 186-3 /// \sa <a href="http://en.wikipedia.org/wiki/Digital_Signature_Algorithm">DSA</a>, as specified in FIPS 186-3
//! \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2
template <class H> template <class H>
class DSA2 : public DL_SS< class DSA2 : public DL_SS<
DL_Keys_DSA, DL_Keys_DSA,
@ -762,11 +762,11 @@ public:
static std::string CRYPTOPP_API StaticAlgorithmName() {return "DSA/" + (std::string)H::StaticAlgorithmName();} static std::string CRYPTOPP_API StaticAlgorithmName() {return "DSA/" + (std::string)H::StaticAlgorithmName();}
}; };
//! \class DSA_RFC6979 /// \class DSA_RFC6979
//! \brief DSA deterministic signature scheme /// \brief DSA deterministic signature scheme
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#DSA-1363">DSA-1363</a>
//! \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2 /// \since Crypto++ 1.0 for DSA, Crypto++ 5.6.2 for DSA2
template <class H> template <class H>
struct DSA_RFC6979 : public DL_SS< struct DSA_RFC6979 : public DL_SS<
DL_SignatureKeys_GFP, DL_SignatureKeys_GFP,
@ -778,27 +778,27 @@ struct DSA_RFC6979 : public DL_SS<
static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("DSA-RFC6979/") + H::StaticAlgorithmName();} static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string("DSA-RFC6979/") + H::StaticAlgorithmName();}
}; };
//! DSA with SHA-1, typedef'd for backwards compatibility /// DSA with SHA-1, typedef'd for backwards compatibility
typedef DSA2<SHA1> DSA; typedef DSA2<SHA1> DSA;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_GFP<DL_GroupParameters_DSA>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_PublicKey_GFP<DL_GroupParameters_DSA>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_GFP<DL_GroupParameters_DSA>; CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_GFP<DL_GroupParameters_DSA>;
CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA2<SHA1> >; CRYPTOPP_DLL_TEMPLATE_CLASS DL_PrivateKey_WithSignaturePairwiseConsistencyTest<DL_PrivateKey_GFP<DL_GroupParameters_DSA>, DSA2<SHA1> >;
//! \class DL_EncryptionAlgorithm_Xor /// \class DL_EncryptionAlgorithm_Xor
//! \brief P1363 based XOR Encryption Method /// \brief P1363 based XOR Encryption Method
//! \tparam MAC MessageAuthenticationCode derived class used for MAC computation /// \tparam MAC MessageAuthenticationCode derived class used for MAC computation
//! \tparam DHAES_MODE flag indicating DHAES mode /// \tparam DHAES_MODE flag indicating DHAES mode
//! \tparam LABEL_OCTETS flag indicating the label is octet count /// \tparam LABEL_OCTETS flag indicating the label is octet count
//! \details DL_EncryptionAlgorithm_Xor is based on an early P1363 draft, which itself appears to be based on an /// \details DL_EncryptionAlgorithm_Xor is based on an early P1363 draft, which itself appears to be based on an
//! early Certicom SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used it in its Integrated /// early Certicom SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used it in its Integrated
//! Ecryption Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// Ecryption Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you need this method for Crypto++ 4.2 compatibility, then use the ECIES template class with /// \details If you need this method for Crypto++ 4.2 compatibility, then use the ECIES template class with
//! <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you need this method for Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES template class with /// \details If you need this method for Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the ECIES template class with
//! <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=ture</tt> and <tt>LABEL_OCTETS=false</tt>. /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=ture</tt> and <tt>LABEL_OCTETS=false</tt>.
//! \details Bouncy Castle 1.54 and Botan 1.11 compatibility are the default template parameters. /// \details Bouncy Castle 1.54 and Botan 1.11 compatibility are the default template parameters.
//! \since Crypto++ 4.0 /// \since Crypto++ 4.0
template <class MAC, bool DHAES_MODE, bool LABEL_OCTETS=false> template <class MAC, bool DHAES_MODE, bool LABEL_OCTETS=false>
class DL_EncryptionAlgorithm_Xor : public DL_SymmetricEncryptionAlgorithm class DL_EncryptionAlgorithm_Xor : public DL_SymmetricEncryptionAlgorithm
{ {
@ -881,7 +881,7 @@ public:
} }
}; };
//! _ /// _
template <class T, bool DHAES_MODE, class KDF> template <class T, bool DHAES_MODE, class KDF>
class DL_KeyDerivationAlgorithm_P1363 : public DL_KeyDerivationAlgorithm<T> class DL_KeyDerivationAlgorithm_P1363 : public DL_KeyDerivationAlgorithm<T>
{ {
@ -910,40 +910,40 @@ public:
} }
}; };
//! \class DLIES /// \class DLIES
//! \brief Discrete Log Integrated Encryption Scheme /// \brief Discrete Log Integrated Encryption Scheme
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \tparam HASH HashTransformation derived class used for key drivation and MAC computation /// \tparam HASH HashTransformation derived class used for key drivation and MAC computation
//! \tparam DHAES_MODE flag indicating if the MAC includes addition context parameters such as the label /// \tparam DHAES_MODE flag indicating if the MAC includes addition context parameters such as the label
//! \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits /// \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
//! \details DLIES is an Integer based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation Method (KEM) /// \details DLIES is an Integer based Integrated Encryption Scheme (IES). The scheme combines a Key Encapsulation Method (KEM)
//! with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is /// with a Data Encapsulation Method (DEM) and a MAC tag. The scheme is
//! <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security. /// <A HREF="http://en.wikipedia.org/wiki/ciphertext_indistinguishability">IND-CCA2</A>, which is a strong notion of security.
//! You should prefer an Integrated Encryption Scheme over homegrown schemes. /// You should prefer an Integrated Encryption Scheme over homegrown schemes.
//! \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom /// \details The library's original implementation is based on an early P1363 draft, which itself appears to be based on an early Certicom
//! SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption /// SEC-1 draft (or an early SEC-1 draft was based on a P1363 draft). Crypto++ 4.2 used the early draft in its Integrated Ecryption
//! Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// Schemes with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the DLIES template class with /// \details If you desire an Integrated Encryption Scheme with Crypto++ 4.2 compatibility, then use the DLIES template class with
//! <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>. /// <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=false</tt> and <tt>LABEL_OCTETS=true</tt>.
//! \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the DLIES /// \details If you desire an Integrated Encryption Scheme with Bouncy Castle 1.54 and Botan 1.11 compatibility, then use the DLIES
//! template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>. /// template class with <tt>NoCofactorMultiplication</tt>, <tt>DHAES_MODE=true</tt> and <tt>LABEL_OCTETS=false</tt>.
//! \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of /// \details The default template parameters ensure compatibility with Bouncy Castle 1.54 and Botan 1.11. The combination of
//! <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security. /// <tt>IncompatibleCofactorMultiplication</tt> and <tt>DHAES_MODE=true</tt> is recommended for best efficiency and security.
//! SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the /// SHA1 is used for compatibility reasons, but it can be changed if desired. SHA-256 or another hash will likely improve the
//! security provided by the MAC. The hash is also used in the key derivation function as a PRF. /// security provided by the MAC. The hash is also used in the key derivation function as a PRF.
//! \details Below is an example of constructing a Crypto++ 4.2 compatible DLIES encryptor and decryptor. /// \details Below is an example of constructing a Crypto++ 4.2 compatible DLIES encryptor and decryptor.
//! <pre> /// <pre>
//! AutoSeededRandomPool prng; /// AutoSeededRandomPool prng;
//! DL_PrivateKey_GFP<DL_GroupParameters_GFP> key; /// DL_PrivateKey_GFP<DL_GroupParameters_GFP> key;
//! key.Initialize(prng, 2048); /// key.Initialize(prng, 2048);
//! ///
//! DLIES<SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key); /// DLIES<SHA1,NoCofactorMultiplication,true,true>::Decryptor decryptor(key);
//! DLIES<SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor); /// DLIES<SHA1,NoCofactorMultiplication,true,true>::Encryptor encryptor(decryptor);
//! </pre> /// </pre>
//! \sa ECIES, <a href="http://www.weidai.com/scan-mirror/ca.html#DLIES">Discrete Log Integrated Encryption Scheme (DLIES)</a>, /// \sa ECIES, <a href="http://www.weidai.com/scan-mirror/ca.html#DLIES">Discrete Log Integrated Encryption Scheme (DLIES)</a>,
//! Martínez, Encinas, and Ávila's <A HREF="http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf">A Survey of the Elliptic /// Martínez, Encinas, and Ávila's <A HREF="http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf">A Survey of the Elliptic
//! Curve Integrated Encryption Schemes</A> /// Curve Integrated Encryption Schemes</A>
//! \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility /// \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
template <class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS=false> template <class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS=false>
struct DLIES struct DLIES
: public DL_ES< : public DL_ES<

26
gost.h
View File

@ -1,7 +1,7 @@
// gost.h - originally written and placed in the public domain by Wei Dai // gost.h - originally written and placed in the public domain by Wei Dai
//! \file gost.h /// \file gost.h
//! \brief Classes for the GIST block cipher /// \brief Classes for the GIST block cipher
#ifndef CRYPTOPP_GOST_H #ifndef CRYPTOPP_GOST_H
#define CRYPTOPP_GOST_H #define CRYPTOPP_GOST_H
@ -11,20 +11,20 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class GOST_Info /// \class GOST_Info
//! \brief GOST block cipher information /// \brief GOST block cipher information
struct GOST_Info : public FixedBlockSize<8>, public FixedKeyLength<32> struct GOST_Info : public FixedBlockSize<8>, public FixedKeyLength<32>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "GOST";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "GOST";}
}; };
//! \class GOST /// \class GOST
//! \brief GOST block cipher /// \brief GOST block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/GOST">GOST</a> /// \sa <a href="http://www.cryptopp.com/wiki/GOST">GOST</a>
class GOST : public GOST_Info, public BlockCipherDocumentation class GOST : public GOST_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief GOST block cipher default operation /// \brief GOST block cipher default operation
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<GOST_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<GOST_Info>
{ {
public: public:
@ -40,16 +40,16 @@ class GOST : public GOST_Info, public BlockCipherDocumentation
FixedSizeSecBlock<word32, 8> m_key; FixedSizeSecBlock<word32, 8> m_key;
}; };
//! \class Enc /// \class Enc
//! \brief GOST block cipher encryption operation /// \brief GOST block cipher encryption operation
class CRYPTOPP_NO_VTABLE Enc : public Base class CRYPTOPP_NO_VTABLE Enc : public Base
{ {
public: public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
}; };
//! \class Dec /// \class Dec
//! \brief GOST block cipher decryption operation /// \brief GOST block cipher decryption operation
class CRYPTOPP_NO_VTABLE Dec : public Base class CRYPTOPP_NO_VTABLE Dec : public Base
{ {
public: public:

106
gzip.h
View File

@ -1,7 +1,7 @@
// gzip.h - originally written and placed in the public domain by Wei Dai // gzip.h - originally written and placed in the public domain by Wei Dai
//! \file gzip.h /// \file gzip.h
//! \brief GZIP compression and decompression (RFC 1952) /// \brief GZIP compression and decompression (RFC 1952)
#ifndef CRYPTOPP_GZIP_H #ifndef CRYPTOPP_GZIP_H
#define CRYPTOPP_GZIP_H #define CRYPTOPP_GZIP_H
@ -13,47 +13,47 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Gzip /// \class Gzip
//! \brief GZIP Compression (RFC 1952) /// \brief GZIP Compression (RFC 1952)
class Gzip : public Deflator class Gzip : public Deflator
{ {
public: public:
//! \brief Construct a Gzip compressor /// \brief Construct a Gzip compressor
//! \param attachment an attached transformation /// \param attachment an attached transformation
//! \param deflateLevel the deflate level /// \param deflateLevel the deflate level
//! \param log2WindowSize the window size /// \param log2WindowSize the window size
//! \param detectUncompressible flag to detect if data is compressible /// \param detectUncompressible flag to detect if data is compressible
//! \details detectUncompressible makes it faster to process uncompressible files, but /// \details detectUncompressible makes it faster to process uncompressible files, but
//! if a file has both compressible and uncompressible parts, it may fail to compress /// if a file has both compressible and uncompressible parts, it may fail to compress
//! some of the compressible parts. /// some of the compressible parts.
Gzip(BufferedTransformation *attachment=NULLPTR, unsigned int deflateLevel=DEFAULT_DEFLATE_LEVEL, unsigned int log2WindowSize=DEFAULT_LOG2_WINDOW_SIZE, bool detectUncompressible=true) Gzip(BufferedTransformation *attachment=NULLPTR, unsigned int deflateLevel=DEFAULT_DEFLATE_LEVEL, unsigned int log2WindowSize=DEFAULT_LOG2_WINDOW_SIZE, bool detectUncompressible=true)
: Deflator(attachment, deflateLevel, log2WindowSize, detectUncompressible), m_totalLen(0), m_filetime(0) { } : Deflator(attachment, deflateLevel, log2WindowSize, detectUncompressible), m_totalLen(0), m_filetime(0) { }
//! \brief Construct a Gzip compressor /// \brief Construct a Gzip compressor
//! \param parameters a set of NameValuePairs to initialize this object /// \param parameters a set of NameValuePairs to initialize this object
//! \param attachment an attached transformation /// \param attachment an attached transformation
//! \details Possible parameter names: Log2WindowSize, DeflateLevel, DetectUncompressible /// \details Possible parameter names: Log2WindowSize, DeflateLevel, DetectUncompressible
Gzip(const NameValuePairs &parameters, BufferedTransformation *attachment=NULLPTR) Gzip(const NameValuePairs &parameters, BufferedTransformation *attachment=NULLPTR)
: Deflator(parameters, attachment), m_totalLen(0), m_filetime(0) : Deflator(parameters, attachment), m_totalLen(0), m_filetime(0)
{ {
IsolatedInitialize(parameters); IsolatedInitialize(parameters);
} }
//! \param filetime the filetime to set in the header. The application is responsible for setting it. /// \param filetime the filetime to set in the header. The application is responsible for setting it.
void SetFiletime(word32 filetime) { m_filetime = filetime; } void SetFiletime(word32 filetime) { m_filetime = filetime; }
//! \param filename the original filename to set in the header. The application is responsible for setting it. /// \param filename the original filename to set in the header. The application is responsible for setting it.
//! RFC 1952 requires a ISO/IEC 8859-1 encoding. /// RFC 1952 requires a ISO/IEC 8859-1 encoding.
//! \param throwOnEncodingError if throwOnEncodingError is true, then the filename is checked to ensure it is /// \param throwOnEncodingError if throwOnEncodingError is true, then the filename is checked to ensure it is
//! ISO/IEC 8859-1 encoded. If the filename does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat /// ISO/IEC 8859-1 encoded. If the filename does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat
//! is thrown. If throwOnEncodingError is false then the filename is not checked. /// is thrown. If throwOnEncodingError is false then the filename is not checked.
void SetFilename(const std::string& filename, bool throwOnEncodingError = false); void SetFilename(const std::string& filename, bool throwOnEncodingError = false);
//! \param comment the comment to set in the header. The application is responsible for setting it. /// \param comment the comment to set in the header. The application is responsible for setting it.
//! RFC 1952 requires a ISO/IEC 8859-1 encoding. /// RFC 1952 requires a ISO/IEC 8859-1 encoding.
//! \param throwOnEncodingError if throwOnEncodingError is true, then the comment is checked to ensure it is /// \param throwOnEncodingError if throwOnEncodingError is true, then the comment is checked to ensure it is
//! ISO/IEC 8859-1 encoded. If the comment does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat /// ISO/IEC 8859-1 encoded. If the comment does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat
//! is thrown. If throwOnEncodingError is false then the comment is not checked. /// is thrown. If throwOnEncodingError is false then the comment is not checked.
void SetComment(const std::string& comment, bool throwOnEncodingError = false); void SetComment(const std::string& comment, bool throwOnEncodingError = false);
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
@ -77,54 +77,54 @@ protected:
std::string m_comment; std::string m_comment;
}; };
//! \class Gunzip /// \class Gunzip
//! \brief GZIP Decompression (RFC 1952) /// \brief GZIP Decompression (RFC 1952)
class Gunzip : public Inflator class Gunzip : public Inflator
{ {
public: public:
typedef Inflator::Err Err; typedef Inflator::Err Err;
//! \class HeaderErr /// \class HeaderErr
//! \brief Exception thrown when a header decoding error occurs /// \brief Exception thrown when a header decoding error occurs
class HeaderErr : public Err {public: HeaderErr() : Err(INVALID_DATA_FORMAT, "Gunzip: header decoding error") {}}; class HeaderErr : public Err {public: HeaderErr() : Err(INVALID_DATA_FORMAT, "Gunzip: header decoding error") {}};
//! \class TailErr /// \class TailErr
//! \brief Exception thrown when the tail is too short /// \brief Exception thrown when the tail is too short
class TailErr : public Err {public: TailErr() : Err(INVALID_DATA_FORMAT, "Gunzip: tail too short") {}}; class TailErr : public Err {public: TailErr() : Err(INVALID_DATA_FORMAT, "Gunzip: tail too short") {}};
//! \class CrcErr /// \class CrcErr
//! \brief Exception thrown when a CRC error occurs /// \brief Exception thrown when a CRC error occurs
class CrcErr : public Err {public: CrcErr() : Err(DATA_INTEGRITY_CHECK_FAILED, "Gunzip: CRC check error") {}}; class CrcErr : public Err {public: CrcErr() : Err(DATA_INTEGRITY_CHECK_FAILED, "Gunzip: CRC check error") {}};
//! \class LengthErr /// \class LengthErr
//! \brief Exception thrown when a length error occurs /// \brief Exception thrown when a length error occurs
class LengthErr : public Err {public: LengthErr() : Err(DATA_INTEGRITY_CHECK_FAILED, "Gunzip: length check error") {}}; class LengthErr : public Err {public: LengthErr() : Err(DATA_INTEGRITY_CHECK_FAILED, "Gunzip: length check error") {}};
//! \brief Construct a Gunzip decompressor /// \brief Construct a Gunzip decompressor
//! \param attachment an attached transformation /// \param attachment an attached transformation
//! \param repeat decompress multiple compressed streams in series /// \param repeat decompress multiple compressed streams in series
//! \param autoSignalPropagation 0 to turn off MessageEnd signal /// \param autoSignalPropagation 0 to turn off MessageEnd signal
Gunzip(BufferedTransformation *attachment = NULLPTR, bool repeat = false, int autoSignalPropagation = -1); Gunzip(BufferedTransformation *attachment = NULLPTR, bool repeat = false, int autoSignalPropagation = -1);
//! \return the filetime of the stream as set in the header. The application is responsible for setting it on the decompressed file. /// \return the filetime of the stream as set in the header. The application is responsible for setting it on the decompressed file.
word32 GetFiletime() const { return m_filetime; } word32 GetFiletime() const { return m_filetime; }
//! \return the filename of the stream as set in the header. The application is responsible for setting it on the decompressed file. /// \return the filename of the stream as set in the header. The application is responsible for setting it on the decompressed file.
//! \param throwOnEncodingError if throwOnEncodingError is true, then the filename is checked to ensure it is /// \param throwOnEncodingError if throwOnEncodingError is true, then the filename is checked to ensure it is
//! ISO/IEC 8859-1 encoded. If the filename does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat is thrown. /// ISO/IEC 8859-1 encoded. If the filename does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat is thrown.
//! If throwOnEncodingError is false then the filename is not checked. /// If throwOnEncodingError is false then the filename is not checked.
const std::string& GetFilename(bool throwOnEncodingError = false) const; const std::string& GetFilename(bool throwOnEncodingError = false) const;
//! \return the comment of the stream as set in the header. /// \return the comment of the stream as set in the header.
//! \param throwOnEncodingError if throwOnEncodingError is true, then the comment is checked to ensure it is /// \param throwOnEncodingError if throwOnEncodingError is true, then the comment is checked to ensure it is
//! ISO/IEC 8859-1 encoded. If the comment does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat is thrown. /// ISO/IEC 8859-1 encoded. If the comment does not adhere to ISO/IEC 8859-1, then a InvalidDataFormat is thrown.
//! If throwOnEncodingError is false then the comment is not checked. /// If throwOnEncodingError is false then the comment is not checked.
const std::string& GetComment(bool throwOnEncodingError = false) const; const std::string& GetComment(bool throwOnEncodingError = false) const;
protected: protected:
enum { enum {
//! \brief First header magic value /// \brief First header magic value
MAGIC1=0x1f, MAGIC1=0x1f,
//! \brief Second header magic value /// \brief Second header magic value
MAGIC2=0x8b, MAGIC2=0x8b,
//! \brief Deflated flag /// \brief Deflated flag
DEFLATED=8 DEFLATED=8
}; };

28
hex.h
View File

@ -1,7 +1,7 @@
// hex.h - originally written and placed in the public domain by Wei Dai // hex.h - originally written and placed in the public domain by Wei Dai
//! \file hex.h /// \file hex.h
//! \brief Classes for HexEncoder and HexDecoder /// \brief Classes for HexEncoder and HexDecoder
#ifndef CRYPTOPP_HEX_H #ifndef CRYPTOPP_HEX_H
#define CRYPTOPP_HEX_H #define CRYPTOPP_HEX_H
@ -11,17 +11,17 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class HexEncoder /// \class HexEncoder
//! \brief Converts given data to base 16 /// \brief Converts given data to base 16
class CRYPTOPP_DLL HexEncoder : public SimpleProxyFilter class CRYPTOPP_DLL HexEncoder : public SimpleProxyFilter
{ {
public: public:
//! \brief Construct a HexEncoder /// \brief Construct a HexEncoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
//! \param uppercase a flag indicating uppercase output /// \param uppercase a flag indicating uppercase output
//! \param groupSize the size of the output grouping /// \param groupSize the size of the output grouping
//! \param separator the separator to use between groups /// \param separator the separator to use between groups
//! \param terminator the terminator append after processing /// \param terminator the terminator append after processing
HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "") HexEncoder(BufferedTransformation *attachment = NULLPTR, bool uppercase = true, int groupSize = 0, const std::string &separator = ":", const std::string &terminator = "")
: SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment) : SimpleProxyFilter(new BaseN_Encoder(new Grouper), attachment)
{ {
@ -31,13 +31,13 @@ public:
void IsolatedInitialize(const NameValuePairs &parameters); void IsolatedInitialize(const NameValuePairs &parameters);
}; };
//! \class HexDecoder /// \class HexDecoder
//! \brief Decode base 16 data back to bytes /// \brief Decode base 16 data back to bytes
class CRYPTOPP_DLL HexDecoder : public BaseN_Decoder class CRYPTOPP_DLL HexDecoder : public BaseN_Decoder
{ {
public: public:
//! \brief Construct a HexDecoder /// \brief Construct a HexDecoder
//! \param attachment a BufferedTrasformation to attach to this object /// \param attachment a BufferedTrasformation to attach to this object
HexDecoder(BufferedTransformation *attachment = NULLPTR) HexDecoder(BufferedTransformation *attachment = NULLPTR)
: BaseN_Decoder(GetDefaultDecodingLookupArray(), 4, attachment) {} : BaseN_Decoder(GetDefaultDecodingLookupArray(), 4, attachment) {}

22
hkdf.h
View File

@ -1,8 +1,8 @@
// hkdf.h - written and placed in public domain by Jeffrey Walton. // hkdf.h - written and placed in public domain by Jeffrey Walton.
//! \file hkdf.h /// \file hkdf.h
//! \brief Classes for HKDF from RFC 5869 /// \brief Classes for HKDF from RFC 5869
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
#ifndef CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H #ifndef CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H
#define CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H #define CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H
@ -14,24 +14,24 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! abstract base class for key derivation function /// abstract base class for key derivation function
class KeyDerivationFunction class KeyDerivationFunction
{ {
public: public:
//! maximum number of bytes which can be produced under a secuirty context /// maximum number of bytes which can be produced under a secuirty context
virtual size_t MaxDerivedKeyLength() const =0; virtual size_t MaxDerivedKeyLength() const =0;
virtual bool Usesinfo() const =0; virtual bool Usesinfo() const =0;
//! derive a key from secret /// derive a key from secret
virtual unsigned int DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, const byte* info=NULLPTR, size_t infoLen=0) const =0; virtual unsigned int DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, const byte* info=NULLPTR, size_t infoLen=0) const =0;
virtual ~KeyDerivationFunction() {} virtual ~KeyDerivationFunction() {}
}; };
//! \brief Extract-and-Expand Key Derivation Function (HKDF) /// \brief Extract-and-Expand Key Derivation Function (HKDF)
//! \tparam T HashTransformation class /// \tparam T HashTransformation class
//! \sa <A HREF="http://eprint.iacr.org/2010/264">Cryptographic Extraction and Key Derivation: The HKDF Scheme</A> /// \sa <A HREF="http://eprint.iacr.org/2010/264">Cryptographic Extraction and Key Derivation: The HKDF Scheme</A>
//! and <A HREF="http://tools.ietf.org/html/rfc5869">HMAC-based Extract-and-Expand Key Derivation Function (HKDF)</A> /// and <A HREF="http://tools.ietf.org/html/rfc5869">HMAC-based Extract-and-Expand Key Derivation Function (HKDF)</A>
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
template <class T> template <class T>
class HKDF : public KeyDerivationFunction class HKDF : public KeyDerivationFunction
{ {

32
hmac.h
View File

@ -1,7 +1,7 @@
// hmac.h - originally written and placed in the public domain by Wei Dai // hmac.h - originally written and placed in the public domain by Wei Dai
//! \file hmac.h /// \file hmac.h
//! \brief Classes for HMAC message authentication codes /// \brief Classes for HMAC message authentication codes
#ifndef CRYPTOPP_HMAC_H #ifndef CRYPTOPP_HMAC_H
#define CRYPTOPP_HMAC_H #define CRYPTOPP_HMAC_H
@ -11,13 +11,13 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class HMAC_Base /// \class HMAC_Base
//! \brief HMAC information /// \brief HMAC information
//! \details HMAC_Base derives from VariableKeyLength and MessageAuthenticationCode /// \details HMAC_Base derives from VariableKeyLength and MessageAuthenticationCode
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, INT_MAX>, public MessageAuthenticationCode class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HMAC_Base : public VariableKeyLength<16, 0, INT_MAX>, public MessageAuthenticationCode
{ {
public: public:
//! \brief Construct a HMAC_Base /// \brief Construct a HMAC_Base
HMAC_Base() : m_innerHashKeyed(false) {} HMAC_Base() : m_innerHashKeyed(false) {}
void UncheckedSetKey(const byte *userKey, unsigned int keylength, const NameValuePairs &params); void UncheckedSetKey(const byte *userKey, unsigned int keylength, const NameValuePairs &params);
@ -40,12 +40,12 @@ private:
bool m_innerHashKeyed; bool m_innerHashKeyed;
}; };
//! \class HMAC /// \class HMAC
//! \brief HMAC /// \brief HMAC
//! \tparam T HashTransformation derived class /// \tparam T HashTransformation derived class
//! \details HMAC derives from MessageAuthenticationCodeImpl. It calculates the HMAC using /// \details HMAC derives from MessageAuthenticationCodeImpl. It calculates the HMAC using
//! <tt>HMAC(K, text) = H(K XOR opad, H(K XOR ipad, text))</tt>. /// <tt>HMAC(K, text) = H(K XOR opad, H(K XOR ipad, text))</tt>.
//! \sa <a href="http://www.weidai.com/scan-mirror/mac.html#HMAC">HMAC</a> /// \sa <a href="http://www.weidai.com/scan-mirror/mac.html#HMAC">HMAC</a>
template <class T> template <class T>
class HMAC : public MessageAuthenticationCodeImpl<HMAC_Base, HMAC<T> > class HMAC : public MessageAuthenticationCodeImpl<HMAC_Base, HMAC<T> >
{ {
@ -53,11 +53,11 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE=T::DIGESTSIZE) CRYPTOPP_CONSTANT(DIGESTSIZE=T::DIGESTSIZE)
CRYPTOPP_CONSTANT(BLOCKSIZE=T::BLOCKSIZE) CRYPTOPP_CONSTANT(BLOCKSIZE=T::BLOCKSIZE)
//! \brief Construct a HMAC /// \brief Construct a HMAC
HMAC() {} HMAC() {}
//! \brief Construct a HMAC /// \brief Construct a HMAC
//! \param key the HMAC key /// \param key the HMAC key
//! \param length the size of the HMAC key /// \param length the size of the HMAC key
HMAC(const byte *key, size_t length=HMAC_Base::DEFAULT_KEYLENGTH) HMAC(const byte *key, size_t length=HMAC_Base::DEFAULT_KEYLENGTH)
{this->SetKey(key, length);} {this->SetKey(key, length);}

42
hmqv.h
View File

@ -4,9 +4,9 @@
#ifndef CRYPTOPP_HMQV_H #ifndef CRYPTOPP_HMQV_H
#define CRYPTOPP_HMQV_H #define CRYPTOPP_HMQV_H
//! \file hmqv.h /// \file hmqv.h
//! \brief Classes for Hashed Menezes-Qu-Vanstone key agreement in GF(p) /// \brief Classes for Hashed Menezes-Qu-Vanstone key agreement in GF(p)
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
#include "gfpcrypt.h" #include "gfpcrypt.h"
#include "algebra.h" #include "algebra.h"
@ -14,11 +14,11 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Hashed Menezes-Qu-Vanstone in GF(p) /// \brief Hashed Menezes-Qu-Vanstone in GF(p)
//! \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance /// \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance
//! Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided. /// Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided.
//! \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain /// \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption, class HASH = SHA512> template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption, class HASH = SHA512>
class HMQV_Domain: public AuthenticatedKeyAgreementDomain class HMQV_Domain: public AuthenticatedKeyAgreementDomain
{ {
@ -65,14 +65,14 @@ public:
CryptoParameters & AccessCryptoParameters(){return AccessAbstractGroupParameters();} CryptoParameters & AccessCryptoParameters(){return AccessAbstractGroupParameters();}
//! return length of agreed value produced /// return length of agreed value produced
unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);} unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);}
//! return length of static private keys in this domain /// return length of static private keys in this domain
unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();} unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();}
//! return length of static public keys in this domain /// return length of static public keys in this domain
unsigned int StaticPublicKeyLength() const{return GetAbstractGroupParameters().GetEncodedElementSize(true);} unsigned int StaticPublicKeyLength() const{return GetAbstractGroupParameters().GetEncodedElementSize(true);}
//! generate static private key /// generate static private key
/*! \pre size of privateKey == PrivateStaticKeyLength() */ /*! \pre size of privateKey == PrivateStaticKeyLength() */
void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
{ {
@ -80,7 +80,7 @@ public:
x.Encode(privateKey, StaticPrivateKeyLength()); x.Encode(privateKey, StaticPrivateKeyLength());
} }
//! generate static public key /// generate static public key
/*! \pre size of publicKey == PublicStaticKeyLength() */ /*! \pre size of publicKey == PublicStaticKeyLength() */
void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
@ -94,7 +94,7 @@ public:
unsigned int EphemeralPrivateKeyLength() const {return StaticPrivateKeyLength() + StaticPublicKeyLength();} unsigned int EphemeralPrivateKeyLength() const {return StaticPrivateKeyLength() + StaticPublicKeyLength();}
unsigned int EphemeralPublicKeyLength() const{return StaticPublicKeyLength();} unsigned int EphemeralPublicKeyLength() const{return StaticPublicKeyLength();}
//! return length of ephemeral private keys in this domain /// return length of ephemeral private keys in this domain
void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
{ {
const DL_GroupParameters<Element> &params = GetAbstractGroupParameters(); const DL_GroupParameters<Element> &params = GetAbstractGroupParameters();
@ -104,14 +104,14 @@ public:
params.EncodeElement(true, y, privateKey+StaticPrivateKeyLength()); params.EncodeElement(true, y, privateKey+StaticPrivateKeyLength());
} }
//! return length of ephemeral public keys in this domain /// return length of ephemeral public keys in this domain
void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(rng);
memcpy(publicKey, privateKey+StaticPrivateKeyLength(), EphemeralPublicKeyLength()); memcpy(publicKey, privateKey+StaticPrivateKeyLength(), EphemeralPublicKeyLength());
} }
//! derive agreed value from your private keys and couterparty's public keys, return false in case of failure /// derive agreed value from your private keys and couterparty's public keys, return false in case of failure
/*! \note The ephemeral public key will always be validated. /*! \note The ephemeral public key will always be validated.
If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time. If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time.
\pre size of agreedValue == AgreedValueLength() \pre size of agreedValue == AgreedValueLength()
@ -298,11 +298,11 @@ private:
KeyAgreementRole m_role; KeyAgreementRole m_role;
}; };
//! \brief Hashed Menezes-Qu-Vanstone in GF(p) /// \brief Hashed Menezes-Qu-Vanstone in GF(p)
//! \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance /// \details This implementation follows Hugo Krawczyk's <a href="http://eprint.iacr.org/2005/176">HMQV: A High-Performance
//! Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided. /// Secure Diffie-Hellman Protocol</a>. Note: this implements HMQV only. HMQV-C with Key Confirmation is not provided.
//! \sa HMQV, MQV_Domain, FHMQV_Domain, AuthenticatedKeyAgreementDomain /// \sa HMQV, MQV_Domain, FHMQV_Domain, AuthenticatedKeyAgreementDomain
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef HMQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> HMQV; typedef HMQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> HMQV;
NAMESPACE_END NAMESPACE_END

View File

@ -15,8 +15,8 @@ NAMESPACE_BEGIN(CryptoPP)
typedef clock_t TimerWord; typedef clock_t TimerWord;
#endif #endif
//! \class TimerBase /// \class TimerBase
//! \brief Base class for timers /// \brief Base class for timers
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TimerBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE TimerBase
{ {
public: public:
@ -40,11 +40,11 @@ private:
TimerWord m_start, m_last; TimerWord m_start, m_last;
}; };
//! \class ThreadUserTimer /// \class ThreadUserTimer
//! \brief Measure CPU time spent executing instructions of this thread (if supported by OS) /// \brief Measure CPU time spent executing instructions of this thread (if supported by OS)
//! \note ThreadUserTimer only works correctly on Windows NT or later desktops and servers. /// \note ThreadUserTimer only works correctly on Windows NT or later desktops and servers.
//! On Unix-based it reports process time. On Windows Phone and Windows Store it reports wall /// On Unix-based it reports process time. On Windows Phone and Windows Store it reports wall
//! clock time with performance counter precision. On all others it reports wall clock time. /// clock time with performance counter precision. On all others it reports wall clock time.
class ThreadUserTimer : public TimerBase class ThreadUserTimer : public TimerBase
{ {
public: public:
@ -53,7 +53,7 @@ public:
TimerWord TicksPerSecond(); TimerWord TicksPerSecond();
}; };
//! high resolution timer /// high resolution timer
class CRYPTOPP_DLL Timer : public TimerBase class CRYPTOPP_DLL Timer : public TimerBase
{ {
public: public:

58
ida.h
View File

@ -1,7 +1,7 @@
// ida.h - originally written and placed in the public domain by Wei Dai // ida.h - originally written and placed in the public domain by Wei Dai
//! \file ida.h /// \file ida.h
//! \brief Classes for Rabin's Information Dispersal and Shamir's Secret Sharing algorithms /// \brief Classes for Rabin's Information Dispersal and Shamir's Secret Sharing algorithms
#ifndef CRYPTOPP_IDA_H #ifndef CRYPTOPP_IDA_H
#define CRYPTOPP_IDA_H #define CRYPTOPP_IDA_H
@ -16,9 +16,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class RawIDA /// \class RawIDA
//! \brief Secret sharing and information dispersal base class /// \brief Secret sharing and information dispersal base class
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class RawIDA : public AutoSignaling<Unflushable<Multichannel<Filter> > > class RawIDA : public AutoSignaling<Unflushable<Multichannel<Filter> > >
{ {
public: public:
@ -63,15 +63,15 @@ protected:
SecBlock<word32> m_u, m_w, m_y; SecBlock<word32> m_u, m_w, m_y;
}; };
//! \class SecretSharing /// \class SecretSharing
//! \brief Shamir's Secret Sharing Algorithm /// \brief Shamir's Secret Sharing Algorithm
//! \details SecretSharing is a variant of Shamir's secret sharing algorithm /// \details SecretSharing is a variant of Shamir's secret sharing algorithm
//! \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery /// \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class SecretSharing : public CustomFlushPropagation<Filter> class SecretSharing : public CustomFlushPropagation<Filter>
{ {
public: public:
//! \brief Construct a SecretSharing /// \brief Construct a SecretSharing
SecretSharing(RandomNumberGenerator &rng, int threshold, int nShares, BufferedTransformation *attachment=NULLPTR, bool addPadding=true) SecretSharing(RandomNumberGenerator &rng, int threshold, int nShares, BufferedTransformation *attachment=NULLPTR, bool addPadding=true)
: m_rng(rng), m_ida(new OutputProxy(*this, true)) : m_rng(rng), m_ida(new OutputProxy(*this, true))
{ {
@ -89,15 +89,15 @@ protected:
bool m_pad; bool m_pad;
}; };
//! \class SecretRecovery /// \class SecretRecovery
//! \brief Shamir's Secret Sharing Algorithm /// \brief Shamir's Secret Sharing Algorithm
//! \details SecretSharing is a variant of Shamir's secret sharing algorithm /// \details SecretSharing is a variant of Shamir's secret sharing algorithm
//! \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery /// \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class SecretRecovery : public RawIDA class SecretRecovery : public RawIDA
{ {
public: public:
//! \brief Construct a SecretRecovery /// \brief Construct a SecretRecovery
SecretRecovery(int threshold, BufferedTransformation *attachment=NULLPTR, bool removePadding=true) SecretRecovery(int threshold, BufferedTransformation *attachment=NULLPTR, bool removePadding=true)
: RawIDA(attachment) : RawIDA(attachment)
{IsolatedInitialize(MakeParameters("RecoveryThreshold", threshold)("RemovePadding", removePadding));} {IsolatedInitialize(MakeParameters("RecoveryThreshold", threshold)("RemovePadding", removePadding));}
@ -113,15 +113,15 @@ protected:
/// a variant of Rabin's Information Dispersal Algorithm /// a variant of Rabin's Information Dispersal Algorithm
//! \class InformationDispersal /// \class InformationDispersal
//! \brief Rabin's Information Dispersal Algorithm /// \brief Rabin's Information Dispersal Algorithm
//! \details InformationDispersal is a variant of Rabin's information dispersal algorithm /// \details InformationDispersal is a variant of Rabin's information dispersal algorithm
//! \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery /// \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class InformationDispersal : public CustomFlushPropagation<Filter> class InformationDispersal : public CustomFlushPropagation<Filter>
{ {
public: public:
//! \brief Construct a InformationDispersal /// \brief Construct a InformationDispersal
InformationDispersal(int threshold, int nShares, BufferedTransformation *attachment=NULLPTR, bool addPadding=true) InformationDispersal(int threshold, int nShares, BufferedTransformation *attachment=NULLPTR, bool addPadding=true)
: m_ida(new OutputProxy(*this, true)), m_pad(false), m_nextChannel(0) : m_ida(new OutputProxy(*this, true)), m_pad(false), m_nextChannel(0)
{ {
@ -139,15 +139,15 @@ protected:
unsigned int m_nextChannel; unsigned int m_nextChannel;
}; };
//! \class InformationRecovery /// \class InformationRecovery
//! \brief Rabin's Information Dispersal Algorithm /// \brief Rabin's Information Dispersal Algorithm
//! \details InformationDispersal is a variant of Rabin's information dispersal algorithm /// \details InformationDispersal is a variant of Rabin's information dispersal algorithm
//! \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery /// \sa SecretRecovery, SecretRecovery, InformationDispersal, InformationRecovery
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class InformationRecovery : public RawIDA class InformationRecovery : public RawIDA
{ {
public: public:
//! \brief Construct a InformationRecovery /// \brief Construct a InformationRecovery
InformationRecovery(int threshold, BufferedTransformation *attachment=NULLPTR, bool removePadding=true) InformationRecovery(int threshold, BufferedTransformation *attachment=NULLPTR, bool removePadding=true)
: RawIDA(attachment), m_pad(false) : RawIDA(attachment), m_pad(false)
{IsolatedInitialize(MakeParameters("RecoveryThreshold", threshold)("RemovePadding", removePadding));} {IsolatedInitialize(MakeParameters("RecoveryThreshold", threshold)("RemovePadding", removePadding));}

18
idea.h
View File

@ -1,7 +1,7 @@
// idea.h - originally written and placed in the public domain by Wei Dai // idea.h - originally written and placed in the public domain by Wei Dai
//! \file idea.h /// \file idea.h
//! \brief Classes for the IDEA block cipher /// \brief Classes for the IDEA block cipher
#ifndef CRYPTOPP_IDEA_H #ifndef CRYPTOPP_IDEA_H
#define CRYPTOPP_IDEA_H #define CRYPTOPP_IDEA_H
@ -11,18 +11,18 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class IDEA_Info /// \class IDEA_Info
//! \brief IDEA block cipher information /// \brief IDEA block cipher information
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
struct IDEA_Info : public FixedBlockSize<8>, public FixedKeyLength<16>, public FixedRounds<8> struct IDEA_Info : public FixedBlockSize<8>, public FixedKeyLength<16>, public FixedRounds<8>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "IDEA";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "IDEA";}
}; };
//! \class IDEA /// \class IDEA
//! \brief IDEA block cipher /// \brief IDEA block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/IDEA">IDEA</a> /// \sa <a href="http://www.cryptopp.com/wiki/IDEA">IDEA</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class IDEA : public IDEA_Info, public BlockCipherDocumentation class IDEA : public IDEA_Info, public BlockCipherDocumentation
{ {
public: // made public for internal purposes public: // made public for internal purposes

878
integer.h

File diff suppressed because it is too large Load Diff

View File

@ -18,8 +18,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class HashInputTooLong /// \class HashInputTooLong
//! \brief Exception thrown when trying to hash more data than is allowed by a hash function /// \brief Exception thrown when trying to hash more data than is allowed by a hash function
class CRYPTOPP_DLL HashInputTooLong : public InvalidDataFormat class CRYPTOPP_DLL HashInputTooLong : public InvalidDataFormat
{ {
public: public:
@ -27,57 +27,57 @@ public:
: InvalidDataFormat("IteratedHashBase: input data exceeds maximum allowed by hash function " + alg) {} : InvalidDataFormat("IteratedHashBase: input data exceeds maximum allowed by hash function " + alg) {}
}; };
//! \class IteratedHashBase /// \class IteratedHashBase
//! \brief Iterated hash base class /// \brief Iterated hash base class
//! \tparam T Hash word type /// \tparam T Hash word type
//! \tparam BASE HashTransformation derived class /// \tparam BASE HashTransformation derived class
//! \details IteratedHashBase provides an interface for block-based iterated hashes /// \details IteratedHashBase provides an interface for block-based iterated hashes
//! \sa HashTransformation, MessageAuthenticationCode /// \sa HashTransformation, MessageAuthenticationCode
template <class T, class BASE> template <class T, class BASE>
class CRYPTOPP_NO_VTABLE IteratedHashBase : public BASE class CRYPTOPP_NO_VTABLE IteratedHashBase : public BASE
{ {
public: public:
typedef T HashWordType; typedef T HashWordType;
//! \brief Construct an IteratedHashBase /// \brief Construct an IteratedHashBase
IteratedHashBase() : m_countLo(0), m_countHi(0) {} IteratedHashBase() : m_countLo(0), m_countHi(0) {}
//! \brief Provides the input block size most efficient for this cipher. /// \brief Provides the input block size most efficient for this cipher.
//! \return The input block size that is most efficient for the cipher /// \return The input block size that is most efficient for the cipher
//! \details The base class implementation returns MandatoryBlockSize(). /// \details The base class implementation returns MandatoryBlockSize().
//! \note Optimal input length is /// \note Optimal input length is
//! <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>. /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
unsigned int OptimalBlockSize() const {return this->BlockSize();} unsigned int OptimalBlockSize() const {return this->BlockSize();}
//! \brief Provides input and output data alignment for optimal performance. /// \brief Provides input and output data alignment for optimal performance.
//! \return the input data alignment that provides optimal performance /// \return the input data alignment that provides optimal performance
//! \details OptimalDataAlignment returns the natural alignment of the hash word. /// \details OptimalDataAlignment returns the natural alignment of the hash word.
unsigned int OptimalDataAlignment() const {return GetAlignmentOf<T>();} unsigned int OptimalDataAlignment() const {return GetAlignmentOf<T>();}
//! \brief Updates a hash with additional input /// \brief Updates a hash with additional input
//! \param input the additional input as a buffer /// \param input the additional input as a buffer
//! \param length the size of the buffer, in bytes /// \param length the size of the buffer, in bytes
void Update(const byte *input, size_t length); void Update(const byte *input, size_t length);
//! \brief Requests space which can be written into by the caller /// \brief Requests space which can be written into by the caller
//! \param size the requested size of the buffer /// \param size the requested size of the buffer
//! \details The purpose of this method is to help avoid extra memory allocations. /// \details The purpose of this method is to help avoid extra memory allocations.
//! \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made, /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
//! size is the requested size of the buffer. When the call returns, size is the size of /// size is the requested size of the buffer. When the call returns, size is the size of
//! the array returned to the caller. /// the array returned to the caller.
//! \details The base class implementation sets size to 0 and returns NULL. /// \details The base class implementation sets size to 0 and returns NULL.
//! \note Some objects, like ArraySink, cannot create a space because its fixed. /// \note Some objects, like ArraySink, cannot create a space because its fixed.
byte * CreateUpdateSpace(size_t &size); byte * CreateUpdateSpace(size_t &size);
//! \brief Restart the hash /// \brief Restart the hash
//! \details Discards the current state, and restart for a new message /// \details Discards the current state, and restart for a new message
void Restart(); void Restart();
//! \brief Computes the hash of the current message /// \brief Computes the hash of the current message
//! \param digest a pointer to the buffer to receive the hash /// \param digest a pointer to the buffer to receive the hash
//! \param digestSize the size of the truncated digest, in bytes /// \param digestSize the size of the truncated digest, in bytes
//! \details TruncatedFinal() call Final() and then copies digestSize bytes to digest. /// \details TruncatedFinal() call Final() and then copies digestSize bytes to digest.
//! The hash is restarted the hash for the next message. /// The hash is restarted the hash for the next message.
void TruncatedFinal(byte *digest, size_t digestSize); void TruncatedFinal(byte *digest, size_t digestSize);
protected: protected:
@ -99,14 +99,14 @@ private:
T m_countLo, m_countHi; T m_countLo, m_countHi;
}; };
//! \class IteratedHash /// \class IteratedHash
//! \brief Iterated hash base class /// \brief Iterated hash base class
//! \tparam T_HashWordType Hash word type /// \tparam T_HashWordType Hash word type
//! \tparam T_Endianness Endianness type of hash /// \tparam T_Endianness Endianness type of hash
//! \tparam T_BlockSize Block size of the hash /// \tparam T_BlockSize Block size of the hash
//! \tparam T_Base HashTransformation derived class /// \tparam T_Base HashTransformation derived class
//! \details IteratedHash provides a default implementation for block-based iterated hashes /// \details IteratedHash provides a default implementation for block-based iterated hashes
//! \sa HashTransformation, MessageAuthenticationCode /// \sa HashTransformation, MessageAuthenticationCode
template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, class T_Base = HashTransformation> template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, class T_Base = HashTransformation>
class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase<T_HashWordType, T_Base> class CRYPTOPP_NO_VTABLE IteratedHash : public IteratedHashBase<T_HashWordType, T_Base>
{ {
@ -120,22 +120,22 @@ public:
virtual ~IteratedHash() {} virtual ~IteratedHash() {}
//! \brief Provides the block size of the hash /// \brief Provides the block size of the hash
//! \return the block size of the hash, in bytes /// \return the block size of the hash, in bytes
//! \details BlockSize() returns <tt>T_BlockSize</tt>. /// \details BlockSize() returns <tt>T_BlockSize</tt>.
unsigned int BlockSize() const {return T_BlockSize;} unsigned int BlockSize() const {return T_BlockSize;}
//! \brief Provides the byte order of the hash /// \brief Provides the byte order of the hash
//! \returns the byte order of the hash as an enumeration /// \returns the byte order of the hash as an enumeration
//! \details GetByteOrder() returns <tt>T_Endianness::ToEnum()</tt>. /// \details GetByteOrder() returns <tt>T_Endianness::ToEnum()</tt>.
//! \sa ByteOrder() /// \sa ByteOrder()
ByteOrder GetByteOrder() const {return T_Endianness::ToEnum();} ByteOrder GetByteOrder() const {return T_Endianness::ToEnum();}
//! \brief Adjusts the byte ordering of the hash /// \brief Adjusts the byte ordering of the hash
//! \param out the output buffer /// \param out the output buffer
//! \param in the input buffer /// \param in the input buffer
//! \param byteCount the size of the buffers, in bytes /// \param byteCount the size of the buffers, in bytes
//! \details CorrectEndianess() calls ConditionalByteReverse() using <tt>T_Endianness</tt>. /// \details CorrectEndianess() calls ConditionalByteReverse() using <tt>T_Endianness</tt>.
inline void CorrectEndianess(HashWordType *out, const HashWordType *in, size_t byteCount) inline void CorrectEndianess(HashWordType *out, const HashWordType *in, size_t byteCount)
{ {
ConditionalByteReverse(T_Endianness::ToEnum(), out, in, byteCount); ConditionalByteReverse(T_Endianness::ToEnum(), out, in, byteCount);
@ -146,16 +146,16 @@ protected:
FixedSizeSecBlock<T_HashWordType, T_BlockSize/sizeof(T_HashWordType)> m_data; FixedSizeSecBlock<T_HashWordType, T_BlockSize/sizeof(T_HashWordType)> m_data;
}; };
//! \class IteratedHashWithStaticTransform /// \class IteratedHashWithStaticTransform
//! \brief Iterated hash with a static transformation function /// \brief Iterated hash with a static transformation function
//! \tparam T_HashWordType Hash word type /// \tparam T_HashWordType Hash word type
//! \tparam T_Endianness Endianness type of hash /// \tparam T_Endianness Endianness type of hash
//! \tparam T_BlockSize Block size of the hash /// \tparam T_BlockSize Block size of the hash
//! \tparam T_StateSize Internal state size of the hash /// \tparam T_StateSize Internal state size of the hash
//! \tparam T_Transform HashTransformation derived class /// \tparam T_Transform HashTransformation derived class
//! \tparam T_DigestSize Digest size of the hash /// \tparam T_DigestSize Digest size of the hash
//! \tparam T_StateAligned Flag indicating if state is 16-byte aligned /// \tparam T_StateAligned Flag indicating if state is 16-byte aligned
//! \sa HashTransformation, MessageAuthenticationCode /// \sa HashTransformation, MessageAuthenticationCode
template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, unsigned int T_StateSize, class T_Transform, unsigned int T_DigestSize = 0, bool T_StateAligned = false> template <class T_HashWordType, class T_Endianness, unsigned int T_BlockSize, unsigned int T_StateSize, class T_Transform, unsigned int T_DigestSize = 0, bool T_StateAligned = false>
class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform class CRYPTOPP_NO_VTABLE IteratedHashWithStaticTransform
: public ClonableImpl<T_Transform, AlgorithmImpl<IteratedHash<T_HashWordType, T_Endianness, T_BlockSize>, T_Transform> > : public ClonableImpl<T_Transform, AlgorithmImpl<IteratedHash<T_HashWordType, T_Endianness, T_BlockSize>, T_Transform> >
@ -165,9 +165,9 @@ public:
virtual ~IteratedHashWithStaticTransform() {} virtual ~IteratedHashWithStaticTransform() {}
//! \brief Provides the digest size of the hash /// \brief Provides the digest size of the hash
//! \return the digest size of the hash, in bytes /// \return the digest size of the hash, in bytes
//! \details DigestSize() returns <tt>DIGESTSIZE</tt>. /// \details DigestSize() returns <tt>DIGESTSIZE</tt>.
unsigned int DigestSize() const {return DIGESTSIZE;}; unsigned int DigestSize() const {return DIGESTSIZE;};
protected: protected:

118
kalyna.h
View File

@ -1,15 +1,15 @@
// kalyna.h - written and placed in the public domain by Jeffrey Walton // kalyna.h - written and placed in the public domain by Jeffrey Walton
// Based on public domain code by Keru Kuro. // Based on public domain code by Keru Kuro.
//! \file kalyna.h /// \file kalyna.h
//! \brief Classes for the Kalyna block cipher /// \brief Classes for the Kalyna block cipher
//! \details The Crypto++ implementation relied upon three sources. First was Oliynykov, Gorbenko, Kazymyrov, /// \details The Crypto++ implementation relied upon three sources. First was Oliynykov, Gorbenko, Kazymyrov,
//! Ruzhentsev, Kuznetsov, Gorbenko, Dyrda, Dolgov, Pushkaryov, Mordvinov and Kaidalov's "A New Encryption /// Ruzhentsev, Kuznetsov, Gorbenko, Dyrda, Dolgov, Pushkaryov, Mordvinov and Kaidalov's "A New Encryption
//! Standard of Ukraine: The Kalyna Block Cipher" (http://eprint.iacr.org/2015/650.pdf). Second was Roman /// Standard of Ukraine: The Kalyna Block Cipher" (http://eprint.iacr.org/2015/650.pdf). Second was Roman
//! Oliynykov and Oleksandr Kazymyrov's GitHub with the reference implementation /// Oliynykov and Oleksandr Kazymyrov's GitHub with the reference implementation
//! (http://github.com/Roman-Oliynykov/Kalyna-reference). The third resource was Keru Kuro's implementation /// (http://github.com/Roman-Oliynykov/Kalyna-reference). The third resource was Keru Kuro's implementation
//! of Kalyna in CppCrypto (http://sourceforge.net/projects/cppcrypto/). Kuro has an outstanding /// of Kalyna in CppCrypto (http://sourceforge.net/projects/cppcrypto/). Kuro has an outstanding
//! implementation that performed better than the reference implementation and our initial attempts. /// implementation that performed better than the reference implementation and our initial attempts.
#ifndef CRYPTOPP_KALYNA_H #ifndef CRYPTOPP_KALYNA_H
#define CRYPTOPP_KALYNA_H #define CRYPTOPP_KALYNA_H
@ -20,63 +20,63 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Kalyna_Info /// \class Kalyna_Info
//! \brief Kalyna block cipher information /// \brief Kalyna block cipher information
//! \details Kalyna key sizes and block sizes do not fit well into the library. Rather /// \details Kalyna key sizes and block sizes do not fit well into the library. Rather
//! than using VariableKeyLength (which is wrong) or using a GeometricKeyLength /// than using VariableKeyLength (which is wrong) or using a GeometricKeyLength
//! (a new class), we just unroll it here. Note that the step size, Q, is still /// (a new class), we just unroll it here. Note that the step size, Q, is still
//! wrong for this implementation. /// wrong for this implementation.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
struct Kalyna_Info : public VariableBlockSize<16, 16, 64> struct Kalyna_Info : public VariableBlockSize<16, 16, 64>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Kalyna";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "Kalyna";}
//! \brief The minimum key length used by the algorithm provided as a constant /// \brief The minimum key length used by the algorithm provided as a constant
//! \details MIN_KEYLENGTH is provided in bytes, not bits /// \details MIN_KEYLENGTH is provided in bytes, not bits
CRYPTOPP_CONSTANT(MIN_KEYLENGTH=16) CRYPTOPP_CONSTANT(MIN_KEYLENGTH=16)
//! \brief The maximum key length used by the algorithm provided as a constant /// \brief The maximum key length used by the algorithm provided as a constant
//! \details MIN_KEYLENGTH is provided in bytes, not bits /// \details MIN_KEYLENGTH is provided in bytes, not bits
CRYPTOPP_CONSTANT(MAX_KEYLENGTH=64) CRYPTOPP_CONSTANT(MAX_KEYLENGTH=64)
//! \brief The default key length used by the algorithm provided as a constant /// \brief The default key length used by the algorithm provided as a constant
//! \details MIN_KEYLENGTH is provided in bytes, not bits /// \details MIN_KEYLENGTH is provided in bytes, not bits
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH=16) CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH=16)
//! \brief The default IV requirements for the algorithm provided as a constant /// \brief The default IV requirements for the algorithm provided as a constant
//! \details The default value is NOT_RESYNCHRONIZABLE. See IV_Requirement /// \details The default value is NOT_RESYNCHRONIZABLE. See IV_Requirement
//! in cryptlib.h for allowed values. /// in cryptlib.h for allowed values.
CRYPTOPP_CONSTANT(IV_REQUIREMENT=SimpleKeyingInterface::UNIQUE_IV) CRYPTOPP_CONSTANT(IV_REQUIREMENT=SimpleKeyingInterface::UNIQUE_IV)
//! \brief The default initialization vector length for the algorithm provided as a constant /// \brief The default initialization vector length for the algorithm provided as a constant
//! \details IV_LENGTH is provided in bytes, not bits. Kalyna has two different block sizes for /// \details IV_LENGTH is provided in bytes, not bits. Kalyna has two different block sizes for
//! each key length. This function returns the default block size for the defult key length. /// each key length. This function returns the default block size for the defult key length.
CRYPTOPP_CONSTANT(IV_LENGTH=16) CRYPTOPP_CONSTANT(IV_LENGTH=16)
//! \brief Provides a valid key length for the algorithm provided by a static function. /// \brief Provides a valid key length for the algorithm provided by a static function.
//! \param keylength the size of the key, in bytes /// \param keylength the size of the key, in bytes
//! \details The key length depends on the block size. For each block size, 128, 256 and 512, /// \details The key length depends on the block size. For each block size, 128, 256 and 512,
//! the key length can be either the block size or twice the block size. That means the /// the key length can be either the block size or twice the block size. That means the
//! valid key lengths are 126, 256, 512 and 1024. Additionally, it means a key length of, /// valid key lengths are 126, 256, 512 and 1024. Additionally, it means a key length of,
//! say, 32 could be used with either 128-block size or 256-block size. /// say, 32 could be used with either 128-block size or 256-block size.
CRYPTOPP_STATIC_CONSTEXPR size_t CRYPTOPP_API StaticGetValidKeyLength(size_t keylength) CRYPTOPP_STATIC_CONSTEXPR size_t CRYPTOPP_API StaticGetValidKeyLength(size_t keylength)
{ {
return (keylength >= 64) ? 64 : return (keylength >= 64) ? 64 :
(keylength >= 32) ? 32 : 16; (keylength >= 32) ? 32 : 16;
} }
//! \brief Validates the blocksize for Kalyna. /// \brief Validates the blocksize for Kalyna.
//! \param blocksize the candidate blocksize /// \param blocksize the candidate blocksize
//! \param alg an Algorithm object used if the blocksize is invalid /// \param alg an Algorithm object used if the blocksize is invalid
//! \throws InvalidBlockSize if the blocksize is invalid /// \throws InvalidBlockSize if the blocksize is invalid
//! \details ThrowIfInvalidBlockSize() validates the blocksize and throws if invalid. /// \details ThrowIfInvalidBlockSize() validates the blocksize and throws if invalid.
inline void ThrowIfInvalidBlockSize(int blocksize, const Algorithm *alg) inline void ThrowIfInvalidBlockSize(int blocksize, const Algorithm *alg)
{ {
if ( blocksize != 16 && blocksize != 32 && blocksize != 64) if ( blocksize != 16 && blocksize != 32 && blocksize != 64)
throw InvalidBlockSize(alg ? alg->AlgorithmName() : std::string("VariableBlockSize"), blocksize); throw InvalidBlockSize(alg ? alg->AlgorithmName() : std::string("VariableBlockSize"), blocksize);
} }
//! \brief Validates the blocksize for Kalyna. /// \brief Validates the blocksize for Kalyna.
//! \param keylength the key length of the cipher /// \param keylength the key length of the cipher
//! \param blocksize the candidate blocksize /// \param blocksize the candidate blocksize
//! \param alg an Algorithm object used if the blocksize is invalid /// \param alg an Algorithm object used if the blocksize is invalid
//! \throws InvalidBlockSize if the blocksize is invalid /// \throws InvalidBlockSize if the blocksize is invalid
//! \details ThrowIfInvalidBlockSize() validates the blocksize under a key and throws if invalid. /// \details ThrowIfInvalidBlockSize() validates the blocksize under a key and throws if invalid.
inline void ThrowIfInvalidBlockSize(int keylength, int blocksize, const Algorithm *alg) inline void ThrowIfInvalidBlockSize(int keylength, int blocksize, const Algorithm *alg)
{ {
if ( ((keylength == 16) && (blocksize != 16)) || if ( ((keylength == 16) && (blocksize != 16)) ||
@ -88,26 +88,26 @@ struct Kalyna_Info : public VariableBlockSize<16, 16, 64>
} }
}; };
//! \class Kalyna /// \class Kalyna
//! \brief Kalyna block cipher /// \brief Kalyna block cipher
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class Kalyna : public Kalyna_Info, public BlockCipherDocumentation class Kalyna : public Kalyna_Info, public BlockCipherDocumentation
{ {
public: public:
class CRYPTOPP_NO_VTABLE Base : public VariableBlockCipherImpl<Kalyna_Info> class CRYPTOPP_NO_VTABLE Base : public VariableBlockCipherImpl<Kalyna_Info>
{ {
public: public:
//! \brief Provides the name of this algorithm /// \brief Provides the name of this algorithm
//! \return the standard algorithm name /// \return the standard algorithm name
//! \details If the object is unkeyed, then the generic name "Kalyna" is returned /// \details If the object is unkeyed, then the generic name "Kalyna" is returned
//! to the caller. If the algorithm is keyed, then a two or three part name is /// to the caller. If the algorithm is keyed, then a two or three part name is
//! returned to the caller. The name follows DSTU 7624:2014, where block size is /// returned to the caller. The name follows DSTU 7624:2014, where block size is
//! provided first and then key length. The library uses a dash to identify block size /// provided first and then key length. The library uses a dash to identify block size
//! and parenthesis to identify key length. For example, Kalyna-128(256) is Kalyna /// and parenthesis to identify key length. For example, Kalyna-128(256) is Kalyna
//! with a 128-bit block size and a 256-bit key length. If a mode is associated /// with a 128-bit block size and a 256-bit key length. If a mode is associated
//! with the object, then it follows as expected. For example, Kalyna-128(256)/ECB. /// with the object, then it follows as expected. For example, Kalyna-128(256)/ECB.
//! DSTU is a little more complex with more parameters, dashes, underscores, but the /// DSTU is a little more complex with more parameters, dashes, underscores, but the
//! library does not use the delimiters or full convention. /// library does not use the delimiters or full convention.
std::string AlgorithmName() const { std::string AlgorithmName() const {
return m_blocksize ? "Kalyna-" + IntToString(m_blocksize*8) + "(" + IntToString(m_kl*8) + ")" : StaticAlgorithmName(); return m_blocksize ? "Kalyna-" + IntToString(m_blocksize*8) + "(" + IntToString(m_kl*8) + ")" : StaticAlgorithmName();
} }

View File

@ -1,13 +1,13 @@
// keccak.h - originally written and placed in the public domain by Wei Dai // keccak.h - originally written and placed in the public domain by Wei Dai
//! \file keccak.h /// \file keccak.h
//! \brief Classes for Keccak message digests /// \brief Classes for Keccak message digests
//! \details The Crypto++ Keccak implementation uses F1600 with XOF d=0x01. /// \details The Crypto++ Keccak implementation uses F1600 with XOF d=0x01.
//! FIPS 202 conformance (XOF d=0x06) is available in SHA3 classes. /// FIPS 202 conformance (XOF d=0x06) is available in SHA3 classes.
//! \details Keccak will likely change in the future to accommodate extensibility of the /// \details Keccak will likely change in the future to accommodate extensibility of the
//! round function and the XOF functions. /// round function and the XOF functions.
//! \sa <a href="http://en.wikipedia.org/wiki/Keccak">Keccak</a> /// \sa <a href="http://en.wikipedia.org/wiki/Keccak">Keccak</a>
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
#ifndef CRYPTOPP_KECCAK_H #ifndef CRYPTOPP_KECCAK_H
#define CRYPTOPP_KECCAK_H #define CRYPTOPP_KECCAK_H
@ -17,36 +17,36 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Keccak /// \class Keccak
//! \brief Keccak message digest base class /// \brief Keccak message digest base class
//! \details The Crypto++ Keccak implementation uses F1600 with XOF d=0x01. /// \details The Crypto++ Keccak implementation uses F1600 with XOF d=0x01.
//! FIPS 202 conformance (XOF d=0x06) is available in SHA3 classes. /// FIPS 202 conformance (XOF d=0x06) is available in SHA3 classes.
//! \details Keccak is the base class for Keccak_224, Keccak_256, Keccak_384 and Keccak_512. /// \details Keccak is the base class for Keccak_224, Keccak_256, Keccak_384 and Keccak_512.
//! Library users should instantiate a derived class, and only use Keccak /// Library users should instantiate a derived class, and only use Keccak
//! as a base class reference or pointer. /// as a base class reference or pointer.
//! \details Keccak will likely change in the future to accommodate extensibility of the /// \details Keccak will likely change in the future to accommodate extensibility of the
//! round function and the XOF functions. /// round function and the XOF functions.
//! \details Perform the following to specify a different digest size. The class will use F1600, /// \details Perform the following to specify a different digest size. The class will use F1600,
//! XOF d=0x01, and a new vaue for <tt>r()</tt> (which will be <tt>200-2*24 = 152</tt>). /// XOF d=0x01, and a new vaue for <tt>r()</tt> (which will be <tt>200-2*24 = 152</tt>).
//! <pre> Keccack_192 : public Keccack /// <pre> Keccack_192 : public Keccack
//! { /// {
//! public: /// public:
//! CRYPTOPP_CONSTANT(DIGESTSIZE = 24) /// CRYPTOPP_CONSTANT(DIGESTSIZE = 24)
//! Keccack_192() : Keccack(DIGESTSIZE) {} /// Keccack_192() : Keccack(DIGESTSIZE) {}
//! }; /// };
//! </pre> /// </pre>
//! ///
//! \sa SHA3, Keccak_224, Keccak_256, Keccak_384 and Keccak_512. /// \sa SHA3, Keccak_224, Keccak_256, Keccak_384 and Keccak_512.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
class Keccak : public HashTransformation class Keccak : public HashTransformation
{ {
public: public:
//! \brief Construct a Keccak /// \brief Construct a Keccak
//! \param digestSize the digest size, in bytes /// \param digestSize the digest size, in bytes
//! \details Keccak is the base class for Keccak_224, Keccak_256, Keccak_384 and Keccak_512. /// \details Keccak is the base class for Keccak_224, Keccak_256, Keccak_384 and Keccak_512.
//! Library users should instantiate a derived class, and only use Keccak /// Library users should instantiate a derived class, and only use Keccak
//! as a base class reference or pointer. /// as a base class reference or pointer.
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
Keccak(unsigned int digestSize) : m_digestSize(digestSize) {Restart();} Keccak(unsigned int digestSize) : m_digestSize(digestSize) {Restart();}
unsigned int DigestSize() const {return m_digestSize;} unsigned int DigestSize() const {return m_digestSize;}
std::string AlgorithmName() const {return "Keccak-" + IntToString(m_digestSize*8);} std::string AlgorithmName() const {return "Keccak-" + IntToString(m_digestSize*8);}
@ -66,10 +66,10 @@ protected:
unsigned int m_digestSize, m_counter; unsigned int m_digestSize, m_counter;
}; };
//! \class Keccak_224 /// \class Keccak_224
//! \tparam T_DigestSize controls the digest size as a template parameter instead of a per-class constant /// \tparam T_DigestSize controls the digest size as a template parameter instead of a per-class constant
//! \brief Keccak-X message digest, template for more fine-grained typedefs /// \brief Keccak-X message digest, template for more fine-grained typedefs
//! \since Crypto++ 6.0.0 /// \since Crypto++ 6.0.0
template<unsigned int T_DigestSize> template<unsigned int T_DigestSize>
class Keccak_Final : public Keccak class Keccak_Final : public Keccak
{ {
@ -77,7 +77,7 @@ public:
CRYPTOPP_CONSTANT(DIGESTSIZE = T_DigestSize) CRYPTOPP_CONSTANT(DIGESTSIZE = T_DigestSize)
CRYPTOPP_CONSTANT(BLOCKSIZE = 200 - 2 * DIGESTSIZE) CRYPTOPP_CONSTANT(BLOCKSIZE = 200 - 2 * DIGESTSIZE)
//! \brief Construct a Keccak-X message digest /// \brief Construct a Keccak-X message digest
Keccak_Final() : Keccak(DIGESTSIZE) {} Keccak_Final() : Keccak(DIGESTSIZE) {}
static std::string StaticAlgorithmName() { return "Keccak-" + IntToString(DIGESTSIZE * 8); } static std::string StaticAlgorithmName() { return "Keccak-" + IntToString(DIGESTSIZE * 8); }
unsigned int BlockSize() const { return BLOCKSIZE; } unsigned int BlockSize() const { return BLOCKSIZE; }
@ -86,20 +86,20 @@ private:
CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE > (int)T_DigestSize); // this is a general expectation by HMAC CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE > (int)T_DigestSize); // this is a general expectation by HMAC
}; };
//! \brief Keccak-224 message digest /// \brief Keccak-224 message digest
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef Keccak_Final<28> Keccak_224; typedef Keccak_Final<28> Keccak_224;
//! \brief Keccak-256 message digest /// \brief Keccak-256 message digest
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef Keccak_Final<32> Keccak_256; typedef Keccak_Final<32> Keccak_256;
//! \brief Keccak-384 message digest /// \brief Keccak-384 message digest
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef Keccak_Final<48> Keccak_384; typedef Keccak_Final<48> Keccak_384;
//! \brief Keccak-512 message digest /// \brief Keccak-512 message digest
//! \since Crypto++ 5.6.4 /// \since Crypto++ 5.6.4
typedef Keccak_Final<64> Keccak_512; typedef Keccak_Final<64> Keccak_512;
NAMESPACE_END NAMESPACE_END

View File

@ -1,7 +1,7 @@
// lubyrack.h - originally written and placed in the public domain by Wei Dai // lubyrack.h - originally written and placed in the public domain by Wei Dai
//! \file lubyrack.h /// \file lubyrack.h
//! \brief Classes for the Luby-Rackoff block cipher /// \brief Classes for the Luby-Rackoff block cipher
#ifndef CRYPTOPP_LUBYRACK_H #ifndef CRYPTOPP_LUBYRACK_H
#define CRYPTOPP_LUBYRACK_H #define CRYPTOPP_LUBYRACK_H
@ -11,16 +11,16 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class LR_Info /// \class LR_Info
//! \brief Luby-Rackoff block cipher information /// \brief Luby-Rackoff block cipher information
template <class T> template <class T>
struct LR_Info : public VariableKeyLength<16, 0, 2*(INT_MAX/2), 2>, public FixedBlockSize<2*T::DIGESTSIZE> struct LR_Info : public VariableKeyLength<16, 0, 2*(INT_MAX/2), 2>, public FixedBlockSize<2*T::DIGESTSIZE>
{ {
static std::string StaticAlgorithmName() {return std::string("LR/")+T::StaticAlgorithmName();} static std::string StaticAlgorithmName() {return std::string("LR/")+T::StaticAlgorithmName();}
}; };
//! \class LR /// \class LR
//! \brief Luby-Rackoff block cipher /// \brief Luby-Rackoff block cipher
template <class T> template <class T>
class LR : public LR_Info<T>, public BlockCipherDocumentation class LR : public LR_Info<T>, public BlockCipherDocumentation
{ {

130
luc.h
View File

@ -1,10 +1,10 @@
// luc.h - originally written and placed in the public domain by Wei Dai // luc.h - originally written and placed in the public domain by Wei Dai
//! \file luc.h /// \file luc.h
//! \brief Classes for the LUC cryptosystem /// \brief Classes for the LUC cryptosystem
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
#ifndef CRYPTOPP_LUC_H #ifndef CRYPTOPP_LUC_H
#define CRYPTOPP_LUC_H #define CRYPTOPP_LUC_H
@ -29,10 +29,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief The LUC function. /// \brief The LUC function.
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
class LUCFunction : public TrapdoorFunction, public PublicKey class LUCFunction : public TrapdoorFunction, public PublicKey
{ {
typedef LUCFunction ThisClass; typedef LUCFunction ThisClass;
@ -40,9 +40,9 @@ class LUCFunction : public TrapdoorFunction, public PublicKey
public: public:
virtual ~LUCFunction() {} virtual ~LUCFunction() {}
//! \brief Initialize a LUC public key with {n,e} /// \brief Initialize a LUC public key with {n,e}
//! \param n the modulus /// \param n the modulus
//! \param e the public exponent /// \param e the public exponent
void Initialize(const Integer &n, const Integer &e) void Initialize(const Integer &n, const Integer &e)
{m_n = n; m_e = e;} {m_n = n; m_e = e;}
@ -68,10 +68,10 @@ protected:
Integer m_n, m_e; Integer m_n, m_e;
}; };
//! \brief The LUC inverse function. /// \brief The LUC inverse function.
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
class InvertibleLUCFunction : public LUCFunction, public TrapdoorFunctionInverse, public PrivateKey class InvertibleLUCFunction : public LUCFunction, public TrapdoorFunctionInverse, public PrivateKey
{ {
typedef InvertibleLUCFunction ThisClass; typedef InvertibleLUCFunction ThisClass;
@ -79,23 +79,23 @@ class InvertibleLUCFunction : public LUCFunction, public TrapdoorFunctionInverse
public: public:
virtual ~InvertibleLUCFunction() {} virtual ~InvertibleLUCFunction() {}
//! \brief Create a LUC private key /// \brief Create a LUC private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param modulusBits the size of the modulus, in bits /// \param modulusBits the size of the modulus, in bits
//! \param eStart the desired starting public exponent /// \param eStart the desired starting public exponent
//! \details Initialize() creates a new keypair using a starting public exponent of 17. /// \details Initialize() creates a new keypair using a starting public exponent of 17.
//! \details This function overload of Initialize() creates a new keypair because it /// \details This function overload of Initialize() creates a new keypair because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits, const Integer &eStart=17); void Initialize(RandomNumberGenerator &rng, unsigned int modulusBits, const Integer &eStart=17);
//! \brief Initialize a LUC private key with {n,e,p,q,dp,dq,u} /// \brief Initialize a LUC private key with {n,e,p,q,dp,dq,u}
//! \param n modulus /// \param n modulus
//! \param e public exponent /// \param e public exponent
//! \param p first prime factor /// \param p first prime factor
//! \param q second prime factor /// \param q second prime factor
//! \param u q<sup>-1</sup> mod p /// \param u q<sup>-1</sup> mod p
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const Integer &n, const Integer &e, const Integer &p, const Integer &q, const Integer &u) void Initialize(const Integer &n, const Integer &e, const Integer &p, const Integer &q, const Integer &u)
{m_n = n; m_e = e; m_p = p; m_q = q; m_u = u;} {m_n = n; m_e = e; m_p = p; m_q = q; m_u = u;}
@ -130,22 +130,22 @@ struct LUC
typedef InvertibleLUCFunction PrivateKey; typedef InvertibleLUCFunction PrivateKey;
}; };
//! \brief LUC cryptosystem /// \brief LUC cryptosystem
//! \tparam STANDARD signature standard /// \tparam STANDARD signature standard
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
template <class STANDARD> template <class STANDARD>
struct LUCES : public TF_ES<LUC, STANDARD> struct LUCES : public TF_ES<LUC, STANDARD>
{ {
}; };
//! \brief LUC signature scheme with appendix /// \brief LUC signature scheme with appendix
//! \tparam STANDARD signature standard /// \tparam STANDARD signature standard
//! \tparam H hash transformation /// \tparam H hash transformation
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
template <class STANDARD, class H> template <class STANDARD, class H>
struct LUCSS : public TF_SS<LUC, STANDARD, H> struct LUCSS : public TF_SS<LUC, STANDARD, H>
{ {
@ -178,7 +178,7 @@ private:
Integer m_p; Integer m_p;
}; };
//! _ /// _
class DL_BasePrecomputation_LUC : public DL_FixedBasePrecomputation<Integer> class DL_BasePrecomputation_LUC : public DL_FixedBasePrecomputation<Integer>
{ {
public: public:
@ -208,8 +208,8 @@ private:
Integer m_g; Integer m_g;
}; };
//! \class DL_GroupParameters_LUC /// \class DL_GroupParameters_LUC
//! \brief LUC GroupParameters specialization /// \brief LUC GroupParameters specialization
class DL_GroupParameters_LUC : public DL_GroupParameters_IntegerBasedImpl<DL_GroupPrecomputation_LUC, DL_BasePrecomputation_LUC> class DL_GroupParameters_LUC : public DL_GroupParameters_IntegerBasedImpl<DL_GroupPrecomputation_LUC, DL_BasePrecomputation_LUC>
{ {
public: public:
@ -239,8 +239,8 @@ private:
int GetFieldType() const {return 2;} int GetFieldType() const {return 2;}
}; };
//! \class DL_GroupParameters_LUC_DefaultSafePrime /// \class DL_GroupParameters_LUC_DefaultSafePrime
//! \brief GF(p) group parameters that default to safe primes /// \brief GF(p) group parameters that default to safe primes
class DL_GroupParameters_LUC_DefaultSafePrime : public DL_GroupParameters_LUC class DL_GroupParameters_LUC_DefaultSafePrime : public DL_GroupParameters_LUC
{ {
public: public:
@ -250,8 +250,8 @@ protected:
unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;} unsigned int GetDefaultSubgroupOrderSize(unsigned int modulusSize) const {return modulusSize-1;}
}; };
//! \class DL_Algorithm_LUC_HMP /// \class DL_Algorithm_LUC_HMP
//! \brief LUC HMP signature algorithm /// \brief LUC HMP signature algorithm
class DL_Algorithm_LUC_HMP : public DL_ElgamalLikeSignatureAlgorithm<Integer> class DL_Algorithm_LUC_HMP : public DL_ElgamalLikeSignatureAlgorithm<Integer>
{ {
public: public:
@ -266,7 +266,7 @@ public:
{return params.GetGroupOrder().ByteCount();} {return params.GetGroupOrder().ByteCount();}
}; };
//! \brief LUC signature keys /// \brief LUC signature keys
struct DL_SignatureKeys_LUC struct DL_SignatureKeys_LUC
{ {
typedef DL_GroupParameters_LUC GroupParameters; typedef DL_GroupParameters_LUC GroupParameters;
@ -274,17 +274,17 @@ struct DL_SignatureKeys_LUC
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey; typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
}; };
//! \brief LUC-HMP, based on "Digital signature schemes based on Lucas functions" by Patrick Horster, Markus Michels, Holger Petersen /// \brief LUC-HMP, based on "Digital signature schemes based on Lucas functions" by Patrick Horster, Markus Michels, Holger Petersen
//! \tparam H hash transformation /// \tparam H hash transformation
//! \details This class is here for historical and pedagogical interest. It has no practical advantages over other /// \details This class is here for historical and pedagogical interest. It has no practical advantages over other
//! trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes /// trapdoor functions and probably shouldn't be used in production software. The discrete log based LUC schemes
//! defined later in this .h file may be of more practical interest. /// defined later in this .h file may be of more practical interest.
template <class H> template <class H>
struct LUC_HMP : public DL_SS<DL_SignatureKeys_LUC, DL_Algorithm_LUC_HMP, DL_SignatureMessageEncodingMethod_DSA, H> struct LUC_HMP : public DL_SS<DL_SignatureKeys_LUC, DL_Algorithm_LUC_HMP, DL_SignatureMessageEncodingMethod_DSA, H>
{ {
}; };
//! \brief LUC encryption keys /// \brief LUC encryption keys
struct DL_CryptoKeys_LUC struct DL_CryptoKeys_LUC
{ {
typedef DL_GroupParameters_LUC_DefaultSafePrime GroupParameters; typedef DL_GroupParameters_LUC_DefaultSafePrime GroupParameters;
@ -292,14 +292,14 @@ struct DL_CryptoKeys_LUC
typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey; typedef DL_PrivateKey_GFP<GroupParameters> PrivateKey;
}; };
//! \class LUC-IES /// \class LUC-IES
//! \brief LUC Integrated Encryption Scheme /// \brief LUC Integrated Encryption Scheme
//! \tparam COFACTOR_OPTION cofactor multiplication option /// \tparam COFACTOR_OPTION cofactor multiplication option
//! \tparam HASH HashTransformation derived class used for key drivation and MAC computation /// \tparam HASH HashTransformation derived class used for key drivation and MAC computation
//! \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as <em>u·V</em>, <em>v·U</em> and label /// \tparam DHAES_MODE flag indicating if the MAC includes additional context parameters such as <em>u·V</em>, <em>v·U</em> and label
//! \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits /// \tparam LABEL_OCTETS flag indicating if the label size is specified in octets or bits
//! \sa CofactorMultiplicationOption /// \sa CofactorMultiplicationOption
//! \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility /// \since Crypto++ 4.0, Crypto++ 5.7 for Bouncy Castle and Botan compatibility
template <class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false> template <class HASH = SHA1, class COFACTOR_OPTION = NoCofactorMultiplication, bool DHAES_MODE = true, bool LABEL_OCTETS = false>
struct LUC_IES struct LUC_IES
: public DL_ES< : public DL_ES<
@ -314,7 +314,7 @@ struct LUC_IES
// ******************************************************** // ********************************************************
//! LUC-DH /// LUC-DH
typedef DH_Domain<DL_GroupParameters_LUC_DefaultSafePrime> LUC_DH; typedef DH_Domain<DL_GroupParameters_LUC_DefaultSafePrime> LUC_DH;
NAMESPACE_END NAMESPACE_END

14
mars.h
View File

@ -1,7 +1,7 @@
// mars.h - originally written and placed in the public domain by Wei Dai // mars.h - originally written and placed in the public domain by Wei Dai
//! \file mars.h /// \file mars.h
//! \brief Classes for the MARS block cipher (IBM AES submission) /// \brief Classes for the MARS block cipher (IBM AES submission)
#ifndef CRYPTOPP_MARS_H #ifndef CRYPTOPP_MARS_H
#define CRYPTOPP_MARS_H #define CRYPTOPP_MARS_H
@ -11,16 +11,16 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class MARS_Info /// \class MARS_Info
//! \brief MARS block cipher information /// \brief MARS block cipher information
struct MARS_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 56, 8> struct MARS_Info : public FixedBlockSize<16>, public VariableKeyLength<16, 16, 56, 8>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "MARS";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "MARS";}
}; };
//! \class MARS /// \class MARS
//! \brief MARS block cipher /// \brief MARS block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/MARS">MARS</a> /// \sa <a href="http://www.cryptopp.com/wiki/MARS">MARS</a>
class MARS : public MARS_Info, public BlockCipherDocumentation class MARS : public MARS_Info, public BlockCipherDocumentation
{ {
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<MARS_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<MARS_Info>

2
md4.h
View File

@ -7,7 +7,7 @@ NAMESPACE_BEGIN(CryptoPP)
namespace Weak1 { namespace Weak1 {
//! <a href="http://www.weidai.com/scan-mirror/md.html#MD4">MD4</a> /// <a href="http://www.weidai.com/scan-mirror/md.html#MD4">MD4</a>
/*! \warning MD4 is considered insecure, and should not be used /*! \warning MD4 is considered insecure, and should not be used
unless you absolutely need it for compatibility. */ unless you absolutely need it for compatibility. */
class MD4 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD4> class MD4 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD4>

8
md5.h
View File

@ -7,10 +7,10 @@ NAMESPACE_BEGIN(CryptoPP)
namespace Weak1 { namespace Weak1 {
//! \class MD5 /// \class MD5
//! \brief MD5 message digest /// \brief MD5 message digest
//! \sa <a href="http://www.cryptolounge.org/wiki/MD5">MD5</a> /// \sa <a href="http://www.cryptolounge.org/wiki/MD5">MD5</a>
//! \since Crypto++ 1.0 /// \since Crypto++ 1.0
class MD5 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD5> class MD5 : public IteratedHashWithStaticTransform<word32, LittleEndian, 64, 16, MD5>
{ {
public: public:

22
mdc.h
View File

@ -3,8 +3,8 @@
#ifndef CRYPTOPP_MDC_H #ifndef CRYPTOPP_MDC_H
#define CRYPTOPP_MDC_H #define CRYPTOPP_MDC_H
//! \file mdc.h /// \file mdc.h
//! \brief Classes for the MDC message digest /// \brief Classes for the MDC message digest
#include "seckey.h" #include "seckey.h"
#include "secblock.h" #include "secblock.h"
@ -12,24 +12,24 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class MDC_Info /// \class MDC_Info
//! \tparam B BlockCipher derived class /// \tparam B BlockCipher derived class
//! \brief MDC_Info cipher information /// \brief MDC_Info cipher information
template <class B> template <class B>
struct MDC_Info : public FixedBlockSize<B::DIGESTSIZE>, public FixedKeyLength<B::BLOCKSIZE> struct MDC_Info : public FixedBlockSize<B::DIGESTSIZE>, public FixedKeyLength<B::BLOCKSIZE>
{ {
static std::string StaticAlgorithmName() {return std::string("MDC/")+B::StaticAlgorithmName();} static std::string StaticAlgorithmName() {return std::string("MDC/")+B::StaticAlgorithmName();}
}; };
//! \brief MDC cipher /// \brief MDC cipher
//! \tparam H HashTransformation derived class /// \tparam H HashTransformation derived class
//! \details MDC() is a construction by Peter Gutmann to turn an iterated hash function into a PRF /// \details MDC() is a construction by Peter Gutmann to turn an iterated hash function into a PRF
//! \sa <a href="http://www.cryptopp.com/wiki/MDC">MDC</a> /// \sa <a href="http://www.cryptopp.com/wiki/MDC">MDC</a>
template <class H> template <class H>
class MDC : public MDC_Info<H> class MDC : public MDC_Info<H>
{ {
//! \class Enc /// \class Enc
//! \brief MDC cipher encryption operation /// \brief MDC cipher encryption operation
class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl<MDC_Info<H> > class CRYPTOPP_NO_VTABLE Enc : public BlockCipherImpl<MDC_Info<H> >
{ {
typedef typename H::HashWordType HashWordType; typedef typename H::HashWordType HashWordType;

View File

@ -1,10 +1,10 @@
// mersenne.h - written and placed in public domain by Jeffrey Walton. // mersenne.h - written and placed in public domain by Jeffrey Walton.
//! \file mersenne.h /// \file mersenne.h
//! \brief Class file for Mersenne Twister /// \brief Class file for Mersenne Twister
//! \warning MersenneTwister is suitable for Monte-Carlo simulations, where uniformaly distrubuted /// \warning MersenneTwister is suitable for Monte-Carlo simulations, where uniformaly distrubuted
//! numbers are required quickly. It should not be used for cryptographic purposes. /// numbers are required quickly. It should not be used for cryptographic purposes.
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
#ifndef CRYPTOPP_MERSENNE_TWISTER_H #ifndef CRYPTOPP_MERSENNE_TWISTER_H
#define CRYPTOPP_MERSENNE_TWISTER_H #define CRYPTOPP_MERSENNE_TWISTER_H
@ -14,18 +14,18 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class MersenneTwister /// \class MersenneTwister
//! \brief Mersenne Twister class for Monte-Carlo simulations /// \brief Mersenne Twister class for Monte-Carlo simulations
//! \tparam K Magic constant /// \tparam K Magic constant
//! \tparam M Period parameter /// \tparam M Period parameter
//! \tparam N Size of the state vector /// \tparam N Size of the state vector
//! \tparam F Multiplier constant /// \tparam F Multiplier constant
//! \tparam S Initial seed /// \tparam S Initial seed
//! \details Provides the MersenneTwister implementation. The class is a header-only implementation. /// \details Provides the MersenneTwister implementation. The class is a header-only implementation.
//! \warning MersenneTwister is suitable for simulations, where uniformaly distrubuted numbers are /// \warning MersenneTwister is suitable for simulations, where uniformaly distrubuted numbers are
//! required quickly. It should not be used for cryptographic purposes. /// required quickly. It should not be used for cryptographic purposes.
//! \sa MT19937, MT19937ar /// \sa MT19937, MT19937ar
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
template <unsigned int K, unsigned int M, unsigned int N, unsigned int F, word32 S> template <unsigned int K, unsigned int M, unsigned int N, unsigned int F, word32 S>
class MersenneTwister : public RandomNumberGenerator class MersenneTwister : public RandomNumberGenerator
{ {
@ -34,10 +34,10 @@ public:
~MersenneTwister() {} ~MersenneTwister() {}
//! \brief Construct a Mersenne Twister /// \brief Construct a Mersenne Twister
//! \param seed 32-bit seed /// \param seed 32-bit seed
//! \details Defaults to template parameter S due to changing algorithm /// \details Defaults to template parameter S due to changing algorithm
//! parameters over time /// parameters over time
MersenneTwister(word32 seed = S) : m_seed(seed), m_idx(N) MersenneTwister(word32 seed = S) : m_seed(seed), m_idx(N)
{ {
Reset(seed); Reset(seed);
@ -45,11 +45,11 @@ public:
bool CanIncorporateEntropy() const {return true;} bool CanIncorporateEntropy() const {return true;}
//! \brief Update RNG state with additional unpredictable values /// \brief Update RNG state with additional unpredictable values
//! \param input the entropy to add to the generator /// \param input the entropy to add to the generator
//! \param length the size of the input buffer /// \param length the size of the input buffer
//! \details MersenneTwister uses the first 32-bits of <tt>input</tt> to reseed the /// \details MersenneTwister uses the first 32-bits of <tt>input</tt> to reseed the
//! generator. If fewer bytes are provided, then the seed is padded with 0's. /// generator. If fewer bytes are provided, then the seed is padded with 0's.
void IncorporateEntropy(const byte *input, size_t length) void IncorporateEntropy(const byte *input, size_t length)
{ {
word32 temp = 0; word32 temp = 0;
@ -60,13 +60,13 @@ public:
SecureWipeArray(&temp, 1); SecureWipeArray(&temp, 1);
} }
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param output byte buffer /// \param output byte buffer
//! \param size length of the buffer, in bytes /// \param size length of the buffer, in bytes
//! \details Bytes are written to output in big endian order. If output length /// \details Bytes are written to output in big endian order. If output length
//! is not a multiple of word32, then unused bytes are not accumulated for subsequent /// is not a multiple of word32, then unused bytes are not accumulated for subsequent
//! calls to GenerateBlock. Rather, the unused tail bytes are discarded, and the /// calls to GenerateBlock. Rather, the unused tail bytes are discarded, and the
//! stream is continued at the next word32 boundary from the state array. /// stream is continued at the next word32 boundary from the state array.
void GenerateBlock(byte *output, size_t size) void GenerateBlock(byte *output, size_t size)
{ {
// Handle word32 size blocks // Handle word32 size blocks
@ -100,10 +100,10 @@ public:
SecureWipeArray(&temp, 1); SecureWipeArray(&temp, 1);
} }
//! \brief Generate a random 32-bit word in the range min to max, inclusive /// \brief Generate a random 32-bit word in the range min to max, inclusive
//! \returns random 32-bit word in the range min to max, inclusive /// \returns random 32-bit word in the range min to max, inclusive
//! \details If the 32-bit candidate is not within the range, then it is discarded /// \details If the 32-bit candidate is not within the range, then it is discarded
//! and a new candidate is used. /// and a new candidate is used.
word32 GenerateWord32(word32 min=0, word32 max=0xffffffffL) word32 GenerateWord32(word32 min=0, word32 max=0xffffffffL)
{ {
const word32 range = max-min; const word32 range = max-min;
@ -120,12 +120,12 @@ public:
return value+min; return value+min;
} }
//! \brief Generate and discard n bytes /// \brief Generate and discard n bytes
//! \param n the number of bytes to discard, rounded up to a <tt>word32</tt> size /// \param n the number of bytes to discard, rounded up to a <tt>word32</tt> size
//! \details If n is not a multiple of <tt>word32</tt>, then unused bytes are /// \details If n is not a multiple of <tt>word32</tt>, then unused bytes are
//! not accumulated for subsequent calls to GenerateBlock. Rather, the unused /// not accumulated for subsequent calls to GenerateBlock. Rather, the unused
//! tail bytes are discarded, and the stream is continued at the next /// tail bytes are discarded, and the stream is continued at the next
//! <tt>word32</tt> boundary from the state array. /// <tt>word32</tt> boundary from the state array.
void DiscardBytes(size_t n) void DiscardBytes(size_t n)
{ {
for(size_t i=0; i < RoundUpToMultipleOf(n, 4U); i++) for(size_t i=0; i < RoundUpToMultipleOf(n, 4U); i++)
@ -144,10 +144,10 @@ protected:
m_state[i] = word32(F * (m_state[i-1] ^ (m_state[i-1] >> 30)) + i); m_state[i] = word32(F * (m_state[i-1] ^ (m_state[i-1] >> 30)) + i);
} }
//! \brief Returns the next 32-bit word from the state array /// \brief Returns the next 32-bit word from the state array
//! \returns the next 32-bit word from the state array /// \returns the next 32-bit word from the state array
//! \details fetches the next word frm the state array, performs bit operations on /// \details fetches the next word frm the state array, performs bit operations on
//! it, and then returns the value to the caller. /// it, and then returns the value to the caller.
word32 NextMersenneWord() word32 NextMersenneWord()
{ {
if (m_idx >= N) { Twist(); } if (m_idx >= N) { Twist(); }
@ -161,7 +161,7 @@ protected:
return temp ^ (temp >> 18); return temp ^ (temp >> 18);
} }
//! \brief Performs the twist operaton on the state array /// \brief Performs the twist operaton on the state array
void Twist() void Twist()
{ {
static const word32 magic[2]={0x0UL, K}; static const word32 magic[2]={0x0UL, K};
@ -192,33 +192,33 @@ protected:
private: private:
//! \brief 32-bit word state array of size N /// \brief 32-bit word state array of size N
FixedSizeSecBlock<word32, N+1> m_state; FixedSizeSecBlock<word32, N+1> m_state;
//! \brief the value used to seed the generator /// \brief the value used to seed the generator
word32 m_seed; word32 m_seed;
//! \brief the current index into the state array /// \brief the current index into the state array
word32 m_idx; word32 m_idx;
}; };
//! \class MT19937 /// \class MT19937
//! \brief Original MT19937 generator provided in the ACM paper. /// \brief Original MT19937 generator provided in the ACM paper.
//! \details MT19937 uses 4537 as default initial seed. /// \details MT19937 uses 4537 as default initial seed.
//! \sa MT19937ar, <A HREF="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf">Mersenne twister: /// \sa MT19937ar, <A HREF="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/mt.pdf">Mersenne twister:
//! a 623-dimensionally equidistributed uniform pseudo-random number generator</A> /// a 623-dimensionally equidistributed uniform pseudo-random number generator</A>
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
#if CRYPTOPP_DOXYGEN_PROCESSING #if CRYPTOPP_DOXYGEN_PROCESSING
class MT19937 : public MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x10DCD /*69069*/, 4537> {}; class MT19937 : public MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x10DCD /*69069*/, 4537> {};
#else #else
typedef MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x10DCD /*69069*/, 4537> MT19937; typedef MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x10DCD /*69069*/, 4537> MT19937;
#endif #endif
//! \class MT19937ar /// \class MT19937ar
//! \brief Updated MT19937 generator adapted to provide an array for initialization. /// \brief Updated MT19937 generator adapted to provide an array for initialization.
//! \details MT19937 uses 5489 as default initial seed. Use this generator when interoperating with C++11's /// \details MT19937 uses 5489 as default initial seed. Use this generator when interoperating with C++11's
//! mt19937 class. /// mt19937 class.
//! \sa MT19937, <A HREF="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html">Mersenne Twister /// \sa MT19937, <A HREF="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html">Mersenne Twister
//! with improved initialization</A> /// with improved initialization</A>
//! \since Crypto++ 5.6.3 /// \since Crypto++ 5.6.3
#if CRYPTOPP_DOXYGEN_PROCESSING #if CRYPTOPP_DOXYGEN_PROCESSING
class MT19937ar : public MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x6C078965 /*1812433253*/, 5489> {}; class MT19937ar : public MersenneTwister<0x9908B0DF /*2567483615*/, 397, 624, 0x6C078965 /*1812433253*/, 5489> {};
#else #else

1762
misc.h

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
// modarith.h - originally written and placed in the public domain by Wei Dai // modarith.h - originally written and placed in the public domain by Wei Dai
//! \file modarith.h /// \file modarith.h
//! \brief Class file for performing modular arithmetic. /// \brief Class file for performing modular arithmetic.
#ifndef CRYPTOPP_MODARITH_H #ifndef CRYPTOPP_MODARITH_H
#define CRYPTOPP_MODARITH_H #define CRYPTOPP_MODARITH_H
@ -25,17 +25,17 @@ CRYPTOPP_DLL_TEMPLATE_CLASS AbstractGroup<Integer>;
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<Integer>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractRing<Integer>;
CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<Integer>; CRYPTOPP_DLL_TEMPLATE_CLASS AbstractEuclideanDomain<Integer>;
//! \class ModularArithmetic /// \class ModularArithmetic
//! \brief Ring of congruence classes modulo n /// \brief Ring of congruence classes modulo n
//! \details This implementation represents each congruence class as the smallest /// \details This implementation represents each congruence class as the smallest
//! non-negative integer in that class. /// non-negative integer in that class.
//! \details <tt>const Element&</tt> returned by member functions are references /// \details <tt>const Element&</tt> returned by member functions are references
//! to internal data members. Since each object may have only /// to internal data members. Since each object may have only
//! one such data member for holding results, the following code /// one such data member for holding results, the following code
//! will produce incorrect results: /// will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
class CRYPTOPP_DLL ModularArithmetic : public AbstractRing<Integer> class CRYPTOPP_DLL ModularArithmetic : public AbstractRing<Integer>
{ {
public: public:
@ -45,201 +45,201 @@ public:
virtual ~ModularArithmetic() {} virtual ~ModularArithmetic() {}
//! \brief Construct a ModularArithmetic /// \brief Construct a ModularArithmetic
//! \param modulus congruence class modulus /// \param modulus congruence class modulus
ModularArithmetic(const Integer &modulus = Integer::One()) ModularArithmetic(const Integer &modulus = Integer::One())
: AbstractRing<Integer>(), m_modulus(modulus), m_result((word)0, modulus.reg.size()) {} : AbstractRing<Integer>(), m_modulus(modulus), m_result((word)0, modulus.reg.size()) {}
//! \brief Copy construct a ModularArithmetic /// \brief Copy construct a ModularArithmetic
//! \param ma other ModularArithmetic /// \param ma other ModularArithmetic
ModularArithmetic(const ModularArithmetic &ma) ModularArithmetic(const ModularArithmetic &ma)
: AbstractRing<Integer>(), m_modulus(ma.m_modulus), m_result((word)0, ma.m_modulus.reg.size()) {} : AbstractRing<Integer>(), m_modulus(ma.m_modulus), m_result((word)0, ma.m_modulus.reg.size()) {}
//! \brief Construct a ModularArithmetic /// \brief Construct a ModularArithmetic
//! \param bt BER encoded ModularArithmetic /// \param bt BER encoded ModularArithmetic
ModularArithmetic(BufferedTransformation &bt); // construct from BER encoded parameters ModularArithmetic(BufferedTransformation &bt); // construct from BER encoded parameters
//! \brief Clone a ModularArithmetic /// \brief Clone a ModularArithmetic
//! \returns pointer to a new ModularArithmetic /// \returns pointer to a new ModularArithmetic
//! \details Clone effectively copy constructs a new ModularArithmetic. The caller is /// \details Clone effectively copy constructs a new ModularArithmetic. The caller is
//! responsible for deleting the pointer returned from this method. /// responsible for deleting the pointer returned from this method.
virtual ModularArithmetic * Clone() const {return new ModularArithmetic(*this);} virtual ModularArithmetic * Clone() const {return new ModularArithmetic(*this);}
//! \brief Encodes in DER format /// \brief Encodes in DER format
//! \param bt BufferedTransformation object /// \param bt BufferedTransformation object
void DEREncode(BufferedTransformation &bt) const; void DEREncode(BufferedTransformation &bt) const;
//! \brief Encodes element in DER format /// \brief Encodes element in DER format
//! \param out BufferedTransformation object /// \param out BufferedTransformation object
//! \param a Element to encode /// \param a Element to encode
void DEREncodeElement(BufferedTransformation &out, const Element &a) const; void DEREncodeElement(BufferedTransformation &out, const Element &a) const;
//! \brief Decodes element in DER format /// \brief Decodes element in DER format
//! \param in BufferedTransformation object /// \param in BufferedTransformation object
//! \param a Element to decode /// \param a Element to decode
void BERDecodeElement(BufferedTransformation &in, Element &a) const; void BERDecodeElement(BufferedTransformation &in, Element &a) const;
//! \brief Retrieves the modulus /// \brief Retrieves the modulus
//! \returns the modulus /// \returns the modulus
const Integer& GetModulus() const {return m_modulus;} const Integer& GetModulus() const {return m_modulus;}
//! \brief Sets the modulus /// \brief Sets the modulus
//! \param newModulus the new modulus /// \param newModulus the new modulus
void SetModulus(const Integer &newModulus) void SetModulus(const Integer &newModulus)
{m_modulus = newModulus; m_result.reg.resize(m_modulus.reg.size());} {m_modulus = newModulus; m_result.reg.resize(m_modulus.reg.size());}
//! \brief Retrieves the representation /// \brief Retrieves the representation
//! \returns true if the if the modulus is in Montgomery form for multiplication, false otherwise /// \returns true if the if the modulus is in Montgomery form for multiplication, false otherwise
virtual bool IsMontgomeryRepresentation() const {return false;} virtual bool IsMontgomeryRepresentation() const {return false;}
//! \brief Reduces an element in the congruence class /// \brief Reduces an element in the congruence class
//! \param a element to convert /// \param a element to convert
//! \returns the reduced element /// \returns the reduced element
//! \details ConvertIn is useful for derived classes, like MontgomeryRepresentation, which /// \details ConvertIn is useful for derived classes, like MontgomeryRepresentation, which
//! must convert between representations. /// must convert between representations.
virtual Integer ConvertIn(const Integer &a) const virtual Integer ConvertIn(const Integer &a) const
{return a%m_modulus;} {return a%m_modulus;}
//! \brief Reduces an element in the congruence class /// \brief Reduces an element in the congruence class
//! \param a element to convert /// \param a element to convert
//! \returns the reduced element /// \returns the reduced element
//! \details ConvertOut is useful for derived classes, like MontgomeryRepresentation, which /// \details ConvertOut is useful for derived classes, like MontgomeryRepresentation, which
//! must convert between representations. /// must convert between representations.
virtual Integer ConvertOut(const Integer &a) const virtual Integer ConvertOut(const Integer &a) const
{return a;} {return a;}
//! \brief Divides an element by 2 /// \brief Divides an element by 2
//! \param a element to convert /// \param a element to convert
const Integer& Half(const Integer &a) const; const Integer& Half(const Integer &a) const;
//! \brief Compare two elements for equality /// \brief Compare two elements for equality
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns true if the elements are equal, false otherwise /// \returns true if the elements are equal, false otherwise
//! \details Equal() tests the elements for equality using <tt>a==b</tt> /// \details Equal() tests the elements for equality using <tt>a==b</tt>
bool Equal(const Integer &a, const Integer &b) const bool Equal(const Integer &a, const Integer &b) const
{return a==b;} {return a==b;}
//! \brief Provides the Identity element /// \brief Provides the Identity element
//! \returns the Identity element /// \returns the Identity element
const Integer& Identity() const const Integer& Identity() const
{return Integer::Zero();} {return Integer::Zero();}
//! \brief Adds elements in the ring /// \brief Adds elements in the ring
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns the sum of <tt>a</tt> and <tt>b</tt> /// \returns the sum of <tt>a</tt> and <tt>b</tt>
const Integer& Add(const Integer &a, const Integer &b) const; const Integer& Add(const Integer &a, const Integer &b) const;
//! \brief TODO /// \brief TODO
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns TODO /// \returns TODO
Integer& Accumulate(Integer &a, const Integer &b) const; Integer& Accumulate(Integer &a, const Integer &b) const;
//! \brief Inverts the element in the ring /// \brief Inverts the element in the ring
//! \param a first element /// \param a first element
//! \returns the inverse of the element /// \returns the inverse of the element
const Integer& Inverse(const Integer &a) const; const Integer& Inverse(const Integer &a) const;
//! \brief Subtracts elements in the ring /// \brief Subtracts elements in the ring
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function. /// \returns the difference of <tt>a</tt> and <tt>b</tt>. The element <tt>a</tt> must provide a Subtract member function.
const Integer& Subtract(const Integer &a, const Integer &b) const; const Integer& Subtract(const Integer &a, const Integer &b) const;
//! \brief TODO /// \brief TODO
//! \param a first element /// \param a first element
//! \param b second element /// \param b second element
//! \returns TODO /// \returns TODO
Integer& Reduce(Integer &a, const Integer &b) const; Integer& Reduce(Integer &a, const Integer &b) const;
//! \brief Doubles an element in the ring /// \brief Doubles an element in the ring
//! \param a the element /// \param a the element
//! \returns the element doubled /// \returns the element doubled
//! \details Double returns <tt>Add(a, a)</tt>. The element <tt>a</tt> must provide an Add member function. /// \details Double returns <tt>Add(a, a)</tt>. The element <tt>a</tt> must provide an Add member function.
const Integer& Double(const Integer &a) const const Integer& Double(const Integer &a) const
{return Add(a, a);} {return Add(a, a);}
//! \brief Retrieves the multiplicative identity /// \brief Retrieves the multiplicative identity
//! \returns the multiplicative identity /// \returns the multiplicative identity
//! \details the base class implementations returns 1. /// \details the base class implementations returns 1.
const Integer& MultiplicativeIdentity() const const Integer& MultiplicativeIdentity() const
{return Integer::One();} {return Integer::One();}
//! \brief Multiplies elements in the ring /// \brief Multiplies elements in the ring
//! \param a the multiplicand /// \param a the multiplicand
//! \param b the multiplier /// \param b the multiplier
//! \returns the product of a and b /// \returns the product of a and b
//! \details Multiply returns <tt>a*b\%n</tt>. /// \details Multiply returns <tt>a*b\%n</tt>.
const Integer& Multiply(const Integer &a, const Integer &b) const const Integer& Multiply(const Integer &a, const Integer &b) const
{return m_result1 = a*b%m_modulus;} {return m_result1 = a*b%m_modulus;}
//! \brief Square an element in the ring /// \brief Square an element in the ring
//! \param a the element /// \param a the element
//! \returns the element squared /// \returns the element squared
//! \details Square returns <tt>a*a\%n</tt>. The element <tt>a</tt> must provide a Square member function. /// \details Square returns <tt>a*a\%n</tt>. The element <tt>a</tt> must provide a Square member function.
const Integer& Square(const Integer &a) const const Integer& Square(const Integer &a) const
{return m_result1 = a.Squared()%m_modulus;} {return m_result1 = a.Squared()%m_modulus;}
//! \brief Determines whether an element is a unit in the ring /// \brief Determines whether an element is a unit in the ring
//! \param a the element /// \param a the element
//! \returns true if the element is a unit after reduction, false otherwise. /// \returns true if the element is a unit after reduction, false otherwise.
bool IsUnit(const Integer &a) const bool IsUnit(const Integer &a) const
{return Integer::Gcd(a, m_modulus).IsUnit();} {return Integer::Gcd(a, m_modulus).IsUnit();}
//! \brief Calculate the multiplicative inverse of an element in the ring /// \brief Calculate the multiplicative inverse of an element in the ring
//! \param a the element /// \param a the element
//! \details MultiplicativeInverse returns <tt>a<sup>-1</sup>\%n</tt>. The element <tt>a</tt> must /// \details MultiplicativeInverse returns <tt>a<sup>-1</sup>\%n</tt>. The element <tt>a</tt> must
//! provide a InverseMod member function. /// provide a InverseMod member function.
const Integer& MultiplicativeInverse(const Integer &a) const const Integer& MultiplicativeInverse(const Integer &a) const
{return m_result1 = a.InverseMod(m_modulus);} {return m_result1 = a.InverseMod(m_modulus);}
//! \brief Divides elements in the ring /// \brief Divides elements in the ring
//! \param a the dividend /// \param a the dividend
//! \param b the divisor /// \param b the divisor
//! \returns the quotient /// \returns the quotient
//! \details Divide returns <tt>a*b<sup>-1</sup>\%n</tt>. /// \details Divide returns <tt>a*b<sup>-1</sup>\%n</tt>.
const Integer& Divide(const Integer &a, const Integer &b) const const Integer& Divide(const Integer &a, const Integer &b) const
{return Multiply(a, MultiplicativeInverse(b));} {return Multiply(a, MultiplicativeInverse(b));}
//! \brief TODO /// \brief TODO
//! \param x first element /// \param x first element
//! \param e1 first exponent /// \param e1 first exponent
//! \param y second element /// \param y second element
//! \param e2 second exponent /// \param e2 second exponent
//! \returns TODO /// \returns TODO
Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const; Integer CascadeExponentiate(const Integer &x, const Integer &e1, const Integer &y, const Integer &e2) const;
//! \brief Exponentiates a base to multiple exponents in the ring /// \brief Exponentiates a base to multiple exponents in the ring
//! \param results an array of Elements /// \param results an array of Elements
//! \param base the base to raise to the exponents /// \param base the base to raise to the exponents
//! \param exponents an array of exponents /// \param exponents an array of exponents
//! \param exponentsCount the number of exponents in the array /// \param exponentsCount the number of exponents in the array
//! \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the /// \details SimultaneousExponentiate() raises the base to each exponent in the exponents array and stores the
//! result at the respective position in the results array. /// result at the respective position in the results array.
//! \details SimultaneousExponentiate() must be implemented in a derived class. /// \details SimultaneousExponentiate() must be implemented in a derived class.
//! \pre <tt>COUNTOF(results) == exponentsCount</tt> /// \pre <tt>COUNTOF(results) == exponentsCount</tt>
//! \pre <tt>COUNTOF(exponents) == exponentsCount</tt> /// \pre <tt>COUNTOF(exponents) == exponentsCount</tt>
void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const; void SimultaneousExponentiate(Element *results, const Element &base, const Integer *exponents, unsigned int exponentsCount) const;
//! \brief Provides the maximum bit size of an element in the ring /// \brief Provides the maximum bit size of an element in the ring
//! \returns maximum bit size of an element /// \returns maximum bit size of an element
unsigned int MaxElementBitLength() const unsigned int MaxElementBitLength() const
{return (m_modulus-1).BitCount();} {return (m_modulus-1).BitCount();}
//! \brief Provides the maximum byte size of an element in the ring /// \brief Provides the maximum byte size of an element in the ring
//! \returns maximum byte size of an element /// \returns maximum byte size of an element
unsigned int MaxElementByteLength() const unsigned int MaxElementByteLength() const
{return (m_modulus-1).ByteCount();} {return (m_modulus-1).ByteCount();}
//! \brief Provides a random element in the ring /// \brief Provides a random element in the ring
//! \param rng RandomNumberGenerator used to generate material /// \param rng RandomNumberGenerator used to generate material
//! \param ignore_for_now unused /// \param ignore_for_now unused
//! \returns a random element that is uniformly distributed /// \returns a random element that is uniformly distributed
//! \details RandomElement constructs a new element in the range <tt>[0,n-1]</tt>, inclusive. /// \details RandomElement constructs a new element in the range <tt>[0,n-1]</tt>, inclusive.
//! The element's class must provide a constructor with the signature <tt>Element(RandomNumberGenerator rng, /// The element's class must provide a constructor with the signature <tt>Element(RandomNumberGenerator rng,
//! Element min, Element max)</tt>. /// Element min, Element max)</tt>.
Element RandomElement(RandomNumberGenerator &rng , const RandomizationParameter &ignore_for_now = 0) const Element RandomElement(RandomNumberGenerator &rng , const RandomizationParameter &ignore_for_now = 0) const
// left RandomizationParameter arg as ref in case RandomizationParameter becomes a more complicated struct // left RandomizationParameter arg as ref in case RandomizationParameter becomes a more complicated struct
{ {
@ -247,10 +247,10 @@ public:
return Element(rng, Integer::Zero(), m_modulus - Integer::One()) ; return Element(rng, Integer::Zero(), m_modulus - Integer::One()) ;
} }
//! \brief Compares two ModularArithmetic for equality /// \brief Compares two ModularArithmetic for equality
//! \param rhs other ModularArithmetic /// \param rhs other ModularArithmetic
//! \returns true if this is equal to the other, false otherwise /// \returns true if this is equal to the other, false otherwise
//! \details The operator tests for equality using <tt>this.m_modulus == rhs.m_modulus</tt>. /// \details The operator tests for equality using <tt>this.m_modulus == rhs.m_modulus</tt>.
bool operator==(const ModularArithmetic &rhs) const bool operator==(const ModularArithmetic &rhs) const
{return m_modulus == rhs.m_modulus;} {return m_modulus == rhs.m_modulus;}
@ -263,30 +263,30 @@ protected:
// const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ; // const ModularArithmetic::RandomizationParameter ModularArithmetic::DefaultRandomizationParameter = 0 ;
//! \class MontgomeryRepresentation /// \class MontgomeryRepresentation
//! \brief Performs modular arithmetic in Montgomery representation for increased speed /// \brief Performs modular arithmetic in Montgomery representation for increased speed
//! \details The Montgomery representation represents each congruence class <tt>[a]</tt> as /// \details The Montgomery representation represents each congruence class <tt>[a]</tt> as
//! <tt>a*r\%n</tt>, where <tt>r</tt> is a convenient power of 2. /// <tt>a*r\%n</tt>, where <tt>r</tt> is a convenient power of 2.
//! \details <tt>const Element&</tt> returned by member functions are references to /// \details <tt>const Element&</tt> returned by member functions are references to
//! internal data members. Since each object may have only one such data member for holding /// internal data members. Since each object may have only one such data member for holding
//! results, the following code will produce incorrect results: /// results, the following code will produce incorrect results:
//! <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre> /// <pre> abcd = group.Add(group.Add(a,b), group.Add(c,d));</pre>
//! But this should be fine: /// But this should be fine:
//! <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre> /// <pre> abcd = group.Add(a, group.Add(b, group.Add(c,d));</pre>
class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic class CRYPTOPP_DLL MontgomeryRepresentation : public ModularArithmetic
{ {
public: public:
virtual ~MontgomeryRepresentation() {} virtual ~MontgomeryRepresentation() {}
//! \brief Construct a MontgomeryRepresentation /// \brief Construct a MontgomeryRepresentation
//! \param modulus congruence class modulus /// \param modulus congruence class modulus
//! \note The modulus must be odd. /// \note The modulus must be odd.
MontgomeryRepresentation(const Integer &modulus); MontgomeryRepresentation(const Integer &modulus);
//! \brief Clone a MontgomeryRepresentation /// \brief Clone a MontgomeryRepresentation
//! \returns pointer to a new MontgomeryRepresentation /// \returns pointer to a new MontgomeryRepresentation
//! \details Clone effectively copy constructs a new MontgomeryRepresentation. The caller is /// \details Clone effectively copy constructs a new MontgomeryRepresentation. The caller is
//! responsible for deleting the pointer returned from this method. /// responsible for deleting the pointer returned from this method.
virtual ModularArithmetic * Clone() const {return new MontgomeryRepresentation(*this);} virtual ModularArithmetic * Clone() const {return new MontgomeryRepresentation(*this);}
bool IsMontgomeryRepresentation() const {return true;} bool IsMontgomeryRepresentation() const {return true;}

204
modes.h
View File

@ -1,7 +1,7 @@
// modes.h - originally written and placed in the public domain by Wei Dai // modes.h - originally written and placed in the public domain by Wei Dai
//! \file modes.h /// \file modes.h
//! \brief Classes for block cipher modes of operation /// \brief Classes for block cipher modes of operation
#ifndef CRYPTOPP_MODES_H #ifndef CRYPTOPP_MODES_H
#define CRYPTOPP_MODES_H #define CRYPTOPP_MODES_H
@ -30,24 +30,24 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class CipherModeDocumentation /// \class CipherModeDocumentation
//! \brief Block cipher mode of operation information /// \brief Block cipher mode of operation information
//! \details Each class derived from this one defines two types, Encryption and Decryption, /// \details Each class derived from this one defines two types, Encryption and Decryption,
//! both of which implement the SymmetricCipher interface. /// both of which implement the SymmetricCipher interface.
//! For each mode there are two classes, one of which is a template class, /// For each mode there are two classes, one of which is a template class,
//! and the other one has a name that ends in "_ExternalCipher". /// and the other one has a name that ends in "_ExternalCipher".
//! The "external cipher" mode objects hold a reference to the underlying block cipher, /// The "external cipher" mode objects hold a reference to the underlying block cipher,
//! instead of holding an instance of it. The reference must be passed in to the constructor. /// instead of holding an instance of it. The reference must be passed in to the constructor.
//! For the "cipher holder" classes, the CIPHER template parameter should be a class /// For the "cipher holder" classes, the CIPHER template parameter should be a class
//! derived from BlockCipherDocumentation, for example DES or AES. /// derived from BlockCipherDocumentation, for example DES or AES.
//! \details See NIST SP 800-38A for definitions of these modes. See /// \details See NIST SP 800-38A for definitions of these modes. See
//! AuthenticatedSymmetricCipherDocumentation for authenticated encryption modes. /// AuthenticatedSymmetricCipherDocumentation for authenticated encryption modes.
struct CipherModeDocumentation : public SymmetricCipherDocumentation struct CipherModeDocumentation : public SymmetricCipherDocumentation
{ {
}; };
//! \class CipherModeBase /// \class CipherModeBase
//! \brief Block cipher mode of operation information /// \brief Block cipher mode of operation information
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CipherModeBase : public SymmetricCipher
{ {
public: public:
@ -95,9 +95,9 @@ protected:
AlignedSecByteBlock m_register; AlignedSecByteBlock m_register;
}; };
//! \class ModePolicyCommonTemplate /// \class ModePolicyCommonTemplate
//! \brief Block cipher mode of operation common operations /// \brief Block cipher mode of operation common operations
//! \tparam POLICY_INTERFACE common operations /// \tparam POLICY_INTERFACE common operations
template <class POLICY_INTERFACE> template <class POLICY_INTERFACE>
class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE class CRYPTOPP_NO_VTABLE ModePolicyCommonTemplate : public CipherModeBase, public POLICY_INTERFACE
{ {
@ -114,8 +114,8 @@ void ModePolicyCommonTemplate<POLICY_INTERFACE>::CipherSetKey(const NameValuePai
SetFeedbackSize(feedbackSize); SetFeedbackSize(feedbackSize);
} }
//! \class CFB_ModePolicy /// \class CFB_ModePolicy
//! \brief CFB block cipher mode of operation /// \brief CFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CFB_ModePolicy : public ModePolicyCommonTemplate<CFB_CipherAbstractPolicy>
{ {
public: public:
@ -149,8 +149,8 @@ inline void CopyOrZero(void *dest, size_t d, const void *src, size_t s)
memset(dest, 0, d); memset(dest, 0, d);
} }
//! \class OFB_ModePolicy /// \class OFB_ModePolicy
//! \brief OFB block cipher mode of operation /// \brief OFB block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE OFB_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{ {
public: public:
@ -166,8 +166,8 @@ private:
void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length); void CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length);
}; };
//! \class CTR_ModePolicy /// \class CTR_ModePolicy
//! \brief CTR block cipher mode of operation /// \brief CTR block cipher mode of operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy> class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CTR_ModePolicy : public ModePolicyCommonTemplate<AdditiveCipherAbstractPolicy>
{ {
public: public:
@ -192,8 +192,8 @@ protected:
AlignedSecByteBlock m_counterArray; AlignedSecByteBlock m_counterArray;
}; };
//! \class BlockOrientedCipherModeBase /// \class BlockOrientedCipherModeBase
//! \brief Block cipher mode of operation default implementation /// \brief Block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockOrientedCipherModeBase : public CipherModeBase
{ {
public: public:
@ -212,8 +212,8 @@ protected:
SecByteBlock m_buffer; SecByteBlock m_buffer;
}; };
//! \class ECB_OneWay /// \class ECB_OneWay
//! \brief ECB block cipher mode of operation default implementation /// \brief ECB block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ECB_OneWay : public BlockOrientedCipherModeBase
{ {
public: public:
@ -226,8 +226,8 @@ public:
void ProcessData(byte *outString, const byte *inString, size_t length); void ProcessData(byte *outString, const byte *inString, size_t length);
}; };
//! \class CBC_ModeBase /// \class CBC_ModeBase
//! \brief CBC block cipher mode of operation default implementation /// \brief CBC block cipher mode of operation default implementation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_ModeBase : public BlockOrientedCipherModeBase
{ {
public: public:
@ -238,16 +238,16 @@ public:
unsigned int MinLastBlockSize() const {return 0;} unsigned int MinLastBlockSize() const {return 0;}
}; };
//! \class CBC_Encryption /// \class CBC_Encryption
//! \brief CBC block cipher mode of operation encryption operation /// \brief CBC block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Encryption : public CBC_ModeBase
{ {
public: public:
void ProcessData(byte *outString, const byte *inString, size_t length); void ProcessData(byte *outString, const byte *inString, size_t length);
}; };
//! \class CBC_CTS_Encryption /// \class CBC_CTS_Encryption
//! \brief CBC-CTS block cipher mode of operation encryption operation /// \brief CBC-CTS block cipher mode of operation encryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Encryption : public CBC_Encryption
{ {
public: public:
@ -267,8 +267,8 @@ protected:
byte *m_stolenIV; byte *m_stolenIV;
}; };
//! \class CBC_Decryption /// \class CBC_Decryption
//! \brief CBC block cipher mode of operation decryption operation /// \brief CBC block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_Decryption : public CBC_ModeBase
{ {
public: public:
@ -281,8 +281,8 @@ protected:
AlignedSecByteBlock m_temp; AlignedSecByteBlock m_temp;
}; };
//! \class CBC_CTS_Decryption /// \class CBC_CTS_Decryption
//! \brief CBC-CTS block cipher mode of operation decryption operation /// \brief CBC-CTS block cipher mode of operation decryption operation
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CBC_CTS_Decryption : public CBC_Decryption
{ {
public: public:
@ -290,8 +290,8 @@ public:
size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength); size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
}; };
//! \class CipherModeFinalTemplate_CipherHolder /// \class CipherModeFinalTemplate_CipherHolder
//! \brief Block cipher mode of operation aggregate /// \brief Block cipher mode of operation aggregate
template <class CIPHER, class BASE> template <class CIPHER, class BASE>
class CipherModeFinalTemplate_CipherHolder : protected ObjectHolder<CIPHER>, public AlgorithmImpl<BASE, CipherModeFinalTemplate_CipherHolder<CIPHER, BASE> > class CipherModeFinalTemplate_CipherHolder : protected ObjectHolder<CIPHER>, public AlgorithmImpl<BASE, CipherModeFinalTemplate_CipherHolder<CIPHER, BASE> >
{ {
@ -321,9 +321,9 @@ public:
} }
}; };
//! \class CipherModeFinalTemplate_ExternalCipher /// \class CipherModeFinalTemplate_ExternalCipher
//! \tparam BASE CipherModeFinalTemplate_CipherHolder base class /// \tparam BASE CipherModeFinalTemplate_CipherHolder base class
//! \details Base class for external mode cipher combinations /// \details Base class for external mode cipher combinations
template <class BASE> template <class BASE>
class CipherModeFinalTemplate_ExternalCipher : public BASE class CipherModeFinalTemplate_ExternalCipher : public BASE
{ {
@ -342,10 +342,10 @@ CRYPTOPP_DLL_TEMPLATE_CLASS CFB_CipherTemplate<AbstractPolicyHolder<CFB_CipherAb
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >; CRYPTOPP_DLL_TEMPLATE_CLASS CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >; CRYPTOPP_DLL_TEMPLATE_CLASS CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> >;
//! \class CFB_Mode /// \class CFB_Mode
//! \brief CFB block cipher mode of operation /// \brief CFB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct CFB_Mode : public CipherModeDocumentation struct CFB_Mode : public CipherModeDocumentation
{ {
@ -353,21 +353,21 @@ struct CFB_Mode : public CipherModeDocumentation
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption; typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
}; };
//! \class CFB_Mode_ExternalCipher /// \class CFB_Mode_ExternalCipher
//! \brief CFB mode, external cipher. /// \brief CFB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct CFB_Mode_ExternalCipher : public CipherModeDocumentation struct CFB_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > Decryption;
}; };
//! \class CFB_FIPS_Mode /// \class CFB_FIPS_Mode
//! \brief CFB block cipher mode of operation providing FIPS validated cryptography. /// \brief CFB block cipher mode of operation providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A /// \details Requires full block plaintext according to FIPS 800-38A
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct CFB_FIPS_Mode : public CipherModeDocumentation struct CFB_FIPS_Mode : public CipherModeDocumentation
{ {
@ -375,11 +375,11 @@ struct CFB_FIPS_Mode : public CipherModeDocumentation
typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption; typedef CipherModeFinalTemplate_CipherHolder<typename CIPHER::Encryption, ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_DecryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Decryption;
}; };
//! \class CFB_FIPS_Mode_ExternalCipher /// \class CFB_FIPS_Mode_ExternalCipher
//! \brief CFB mode, external cipher, providing FIPS validated cryptography. /// \brief CFB mode, external cipher, providing FIPS validated cryptography.
//! \details Requires full block plaintext according to FIPS 800-38A /// \details Requires full block plaintext according to FIPS 800-38A
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct CFB_FIPS_Mode_ExternalCipher : public CipherModeDocumentation struct CFB_FIPS_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, CFB_RequireFullDataBlocks<CFB_EncryptionTemplate<AbstractPolicyHolder<CFB_CipherAbstractPolicy, CFB_ModePolicy> > > > > Encryption;
@ -388,10 +388,10 @@ struct CFB_FIPS_Mode_ExternalCipher : public CipherModeDocumentation
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >; CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> >;
//! \class OFB_Mode /// \class OFB_Mode
//! \brief OFB block cipher mode of operation /// \brief OFB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct OFB_Mode : public CipherModeDocumentation struct OFB_Mode : public CipherModeDocumentation
{ {
@ -399,10 +399,10 @@ struct OFB_Mode : public CipherModeDocumentation
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class OFB_Mode_ExternalCipher /// \class OFB_Mode_ExternalCipher
//! \brief OFB mode, external cipher. /// \brief OFB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct OFB_Mode_ExternalCipher : public CipherModeDocumentation struct OFB_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, OFB_ModePolicy> > > > Encryption;
@ -412,10 +412,10 @@ struct OFB_Mode_ExternalCipher : public CipherModeDocumentation
CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >; CRYPTOPP_DLL_TEMPLATE_CLASS AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> >;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > >; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > >;
//! \class CTR_Mode /// \class CTR_Mode
//! \brief CTR block cipher mode of operation /// \brief CTR block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct CTR_Mode : public CipherModeDocumentation struct CTR_Mode : public CipherModeDocumentation
{ {
@ -423,20 +423,20 @@ struct CTR_Mode : public CipherModeDocumentation
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class CTR_Mode_ExternalCipher /// \class CTR_Mode_ExternalCipher
//! \brief CTR mode, external cipher. /// \brief CTR mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct CTR_Mode_ExternalCipher : public CipherModeDocumentation struct CTR_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption; typedef CipherModeFinalTemplate_ExternalCipher<ConcretePolicyHolder<Empty, AdditiveCipherTemplate<AbstractPolicyHolder<AdditiveCipherAbstractPolicy, CTR_ModePolicy> > > > Encryption;
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class ECB_Mode /// \class ECB_Mode
//! \brief ECB block cipher mode of operation /// \brief ECB block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct ECB_Mode : public CipherModeDocumentation struct ECB_Mode : public CipherModeDocumentation
{ {
@ -446,20 +446,20 @@ struct ECB_Mode : public CipherModeDocumentation
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ECB_OneWay>; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<ECB_OneWay>;
//! \class ECB_Mode_ExternalCipher /// \class ECB_Mode_ExternalCipher
//! \brief ECB mode, external cipher. /// \brief ECB mode, external cipher.
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct ECB_Mode_ExternalCipher : public CipherModeDocumentation struct ECB_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<ECB_OneWay> Encryption; typedef CipherModeFinalTemplate_ExternalCipher<ECB_OneWay> Encryption;
typedef Encryption Decryption; typedef Encryption Decryption;
}; };
//! \class CBC_Mode /// \class CBC_Mode
//! \brief CBC block cipher mode of operation /// \brief CBC block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct CBC_Mode : public CipherModeDocumentation struct CBC_Mode : public CipherModeDocumentation
{ {
@ -470,20 +470,20 @@ struct CBC_Mode : public CipherModeDocumentation
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Encryption>; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Decryption>; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_Decryption>;
//! \class CBC_Mode_ExternalCipher /// \class CBC_Mode_ExternalCipher
//! \brief CBC mode, external cipher /// \brief CBC mode, external cipher
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct CBC_Mode_ExternalCipher : public CipherModeDocumentation struct CBC_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<CBC_Encryption> Encryption; typedef CipherModeFinalTemplate_ExternalCipher<CBC_Encryption> Encryption;
typedef CipherModeFinalTemplate_ExternalCipher<CBC_Decryption> Decryption; typedef CipherModeFinalTemplate_ExternalCipher<CBC_Decryption> Decryption;
}; };
//! \class CBC_CTS_Mode /// \class CBC_CTS_Mode
//! \brief CBC-CTS block cipher mode of operation /// \brief CBC-CTS block cipher mode of operation
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
template <class CIPHER> template <class CIPHER>
struct CBC_CTS_Mode : public CipherModeDocumentation struct CBC_CTS_Mode : public CipherModeDocumentation
{ {
@ -494,10 +494,10 @@ struct CBC_CTS_Mode : public CipherModeDocumentation
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption>; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption>;
CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption>; CRYPTOPP_DLL_TEMPLATE_CLASS CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Decryption>;
//! \class CBC_CTS_Mode_ExternalCipher /// \class CBC_CTS_Mode_ExternalCipher
//! \brief CBC mode with ciphertext stealing, external cipher /// \brief CBC mode with ciphertext stealing, external cipher
//! \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A> /// \sa <A HREF="http://www.cryptopp.com/wiki/Modes_of_Operation">Modes of Operation</A>
//! on the Crypto++ wiki. /// on the Crypto++ wiki.
struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation struct CBC_CTS_Mode_ExternalCipher : public CipherModeDocumentation
{ {
typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption> Encryption; typedef CipherModeFinalTemplate_ExternalCipher<CBC_CTS_Encryption> Encryption;

View File

@ -10,7 +10,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! Message Queue /// Message Queue
class CRYPTOPP_DLL MessageQueue : public AutoSignaling<BufferedTransformation> class CRYPTOPP_DLL MessageQueue : public AutoSignaling<BufferedTransformation>
{ {
public: public:
@ -67,7 +67,7 @@ private:
}; };
//! A filter that checks messages on two channels for equality /// A filter that checks messages on two channels for equality
class CRYPTOPP_DLL EqualityComparisonFilter : public Unflushable<Multichannel<Filter> > class CRYPTOPP_DLL EqualityComparisonFilter : public Unflushable<Multichannel<Filter> >
{ {
public: public:

144
mqv.h
View File

@ -1,7 +1,7 @@
// mqv.h - originally written and placed in the public domain by Wei Dai // mqv.h - originally written and placed in the public domain by Wei Dai
//! \file mqv.h /// \file mqv.h
//! \brief Classes for MenezesQuVanstone (MQV) key agreement /// \brief Classes for MenezesQuVanstone (MQV) key agreement
#ifndef CRYPTOPP_MQV_H #ifndef CRYPTOPP_MQV_H
#define CRYPTOPP_MQV_H #define CRYPTOPP_MQV_H
@ -15,14 +15,14 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class MQV_Domain /// \class MQV_Domain
//! \brief MQV domain for performing authenticated key agreement /// \brief MQV domain for performing authenticated key agreement
//! \tparam GROUP_PARAMETERS doamin parameters /// \tparam GROUP_PARAMETERS doamin parameters
//! \tparam COFACTOR_OPTION cofactor option /// \tparam COFACTOR_OPTION cofactor option
//! \details GROUP_PARAMETERS parameters include the curve coefcients and the base point. /// \details GROUP_PARAMETERS parameters include the curve coefcients and the base point.
//! Binary curves use a polynomial to represent its characteristic, while prime curves /// Binary curves use a polynomial to represent its characteristic, while prime curves
//! use a prime number. /// use a prime number.
//! \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain /// \sa MQV, HMQV, FHMQV, and AuthenticatedKeyAgreementDomain
template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption> template <class GROUP_PARAMETERS, class COFACTOR_OPTION = typename GROUP_PARAMETERS::DefaultCofactorOption>
class MQV_Domain : public AuthenticatedKeyAgreementDomain class MQV_Domain : public AuthenticatedKeyAgreementDomain
{ {
@ -31,104 +31,104 @@ public:
typedef typename GroupParameters::Element Element; typedef typename GroupParameters::Element Element;
typedef MQV_Domain<GROUP_PARAMETERS, COFACTOR_OPTION> Domain; typedef MQV_Domain<GROUP_PARAMETERS, COFACTOR_OPTION> Domain;
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
MQV_Domain() {} MQV_Domain() {}
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
//! \param params group parameters and options /// \param params group parameters and options
MQV_Domain(const GroupParameters &params) MQV_Domain(const GroupParameters &params)
: m_groupParameters(params) {} : m_groupParameters(params) {}
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
//! \param bt BufferedTransformation with group parameters and options /// \param bt BufferedTransformation with group parameters and options
MQV_Domain(BufferedTransformation &bt) MQV_Domain(BufferedTransformation &bt)
{m_groupParameters.BERDecode(bt);} {m_groupParameters.BERDecode(bt);}
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \details v1 and v2 are passed directly to the GROUP_PARAMETERS object. /// \details v1 and v2 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2> template <class T1, class T2>
MQV_Domain(T1 v1, T2 v2) MQV_Domain(T1 v1, T2 v2)
{m_groupParameters.Initialize(v1, v2);} {m_groupParameters.Initialize(v1, v2);}
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2 and v3 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2, class T3> template <class T1, class T2, class T3>
MQV_Domain(T1 v1, T2 v2, T3 v3) MQV_Domain(T1 v1, T2 v2, T3 v3)
{m_groupParameters.Initialize(v1, v2, v3);} {m_groupParameters.Initialize(v1, v2, v3);}
//! \brief Construct a MQV domain /// \brief Construct a MQV domain
//! \tparam T1 template parameter used as a constructor parameter /// \tparam T1 template parameter used as a constructor parameter
//! \tparam T2 template parameter used as a constructor parameter /// \tparam T2 template parameter used as a constructor parameter
//! \tparam T3 template parameter used as a constructor parameter /// \tparam T3 template parameter used as a constructor parameter
//! \tparam T4 template parameter used as a constructor parameter /// \tparam T4 template parameter used as a constructor parameter
//! \param v1 first parameter /// \param v1 first parameter
//! \param v2 second parameter /// \param v2 second parameter
//! \param v3 third parameter /// \param v3 third parameter
//! \param v4 third parameter /// \param v4 third parameter
//! \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object. /// \details v1, v2, v3 and v4 are passed directly to the GROUP_PARAMETERS object.
template <class T1, class T2, class T3, class T4> template <class T1, class T2, class T3, class T4>
MQV_Domain(T1 v1, T2 v2, T3 v3, T4 v4) MQV_Domain(T1 v1, T2 v2, T3 v3, T4 v4)
{m_groupParameters.Initialize(v1, v2, v3, v4);} {m_groupParameters.Initialize(v1, v2, v3, v4);}
//! \brief Retrieves the group parameters for this domain /// \brief Retrieves the group parameters for this domain
//! \return the group parameters for this domain as a const reference /// \return the group parameters for this domain as a const reference
const GroupParameters & GetGroupParameters() const {return m_groupParameters;} const GroupParameters & GetGroupParameters() const {return m_groupParameters;}
//! \brief Retrieves the group parameters for this domain /// \brief Retrieves the group parameters for this domain
//! \return the group parameters for this domain as a non-const reference /// \return the group parameters for this domain as a non-const reference
GroupParameters & AccessGroupParameters() {return m_groupParameters;} GroupParameters & AccessGroupParameters() {return m_groupParameters;}
//! \brief Retrieves the crypto parameters for this domain /// \brief Retrieves the crypto parameters for this domain
//! \return the crypto parameters for this domain as a non-const reference /// \return the crypto parameters for this domain as a non-const reference
CryptoParameters & AccessCryptoParameters() {return AccessAbstractGroupParameters();} CryptoParameters & AccessCryptoParameters() {return AccessAbstractGroupParameters();}
//! \brief Provides the size of the agreed value /// \brief Provides the size of the agreed value
//! \return size of agreed value produced in this domain /// \return size of agreed value produced in this domain
//! \details The length is calculated using <tt>GetEncodedElementSize(false)</tt>, which means the /// \details The length is calculated using <tt>GetEncodedElementSize(false)</tt>, which means the
//! element is encoded in a non-reversible format. A non-reversible format means its a raw byte array, /// element is encoded in a non-reversible format. A non-reversible format means its a raw byte array,
//! and it lacks presentation format like an ASN.1 BIT_STRING or OCTET_STRING. /// and it lacks presentation format like an ASN.1 BIT_STRING or OCTET_STRING.
unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);} unsigned int AgreedValueLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(false);}
//! \brief Provides the size of the static private key /// \brief Provides the size of the static private key
//! \return size of static private keys in this domain /// \return size of static private keys in this domain
//! \details The length is calculated using the byte count of the subgroup order. /// \details The length is calculated using the byte count of the subgroup order.
unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();} unsigned int StaticPrivateKeyLength() const {return GetAbstractGroupParameters().GetSubgroupOrder().ByteCount();}
//! \brief Provides the size of the static public key /// \brief Provides the size of the static public key
//! \return size of static public keys in this domain /// \return size of static public keys in this domain
//! \details The length is calculated using <tt>GetEncodedElementSize(true)</tt>, which means the /// \details The length is calculated using <tt>GetEncodedElementSize(true)</tt>, which means the
//! element is encoded in a reversible format. A reversible format means it has a presentation format, /// element is encoded in a reversible format. A reversible format means it has a presentation format,
//! and its an ANS.1 encoded element or point. /// and its an ANS.1 encoded element or point.
unsigned int StaticPublicKeyLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(true);} unsigned int StaticPublicKeyLength() const {return GetAbstractGroupParameters().GetEncodedElementSize(true);}
//! \brief Generate static private key in this domain /// \brief Generate static private key in this domain
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param privateKey a byte buffer for the generated private key in this domain /// \param privateKey a byte buffer for the generated private key in this domain
//! \details The private key is a random scalar used as an exponent in the range <tt>[1,MaxExponent()]</tt>. /// \details The private key is a random scalar used as an exponent in the range <tt>[1,MaxExponent()]</tt>.
//! \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt> /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const
{ {
Integer x(rng, Integer::One(), GetAbstractGroupParameters().GetMaxExponent()); Integer x(rng, Integer::One(), GetAbstractGroupParameters().GetMaxExponent());
x.Encode(privateKey, StaticPrivateKeyLength()); x.Encode(privateKey, StaticPrivateKeyLength());
} }
//! \brief Generate a static public key from a private key in this domain /// \brief Generate a static public key from a private key in this domain
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param privateKey a byte buffer with the previously generated private key /// \param privateKey a byte buffer with the previously generated private key
//! \param publicKey a byte buffer for the generated public key in this domain /// \param publicKey a byte buffer for the generated public key in this domain
//! \details The public key is an element or point on the curve, and its stored in a revrsible format. /// \details The public key is an element or point on the curve, and its stored in a revrsible format.
//! A reversible format means it has a presentation format, and its an ANS.1 encoded element or point. /// A reversible format means it has a presentation format, and its an ANS.1 encoded element or point.
//! \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt> /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const
{ {
CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(rng);
@ -212,8 +212,8 @@ private:
GroupParameters m_groupParameters; GroupParameters m_groupParameters;
}; };
//! Menezes-Qu-Vanstone in GF(p) with key validation, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#MQV">MQV</a> /// Menezes-Qu-Vanstone in GF(p) with key validation, AKA <a href="http://www.weidai.com/scan-mirror/ka.html#MQV">MQV</a>
//! \sa MQV, HMQV_Domain, FHMQV_Domain, AuthenticatedKeyAgreementDomain /// \sa MQV, HMQV_Domain, FHMQV_Domain, AuthenticatedKeyAgreementDomain
typedef MQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> MQV; typedef MQV_Domain<DL_GroupParameters_GFP_DefaultSafePrime> MQV;
NAMESPACE_END NAMESPACE_END

View File

@ -1,7 +1,7 @@
// nbtheory.h - originally written and placed in the public domain by Wei Dai // nbtheory.h - originally written and placed in the public domain by Wei Dai
//! \file nbtheory.h /// \file nbtheory.h
//! \brief Classes and functions for number theoretic operations /// \brief Classes and functions for number theoretic operations
#ifndef CRYPTOPP_NBTHEORY_H #ifndef CRYPTOPP_NBTHEORY_H
#define CRYPTOPP_NBTHEORY_H #define CRYPTOPP_NBTHEORY_H
@ -17,31 +17,31 @@ CRYPTOPP_DLL const word16 * CRYPTOPP_API GetPrimeTable(unsigned int &size);
// ************ primality testing **************** // ************ primality testing ****************
//! \brief Generates a provable prime /// \brief Generates a provable prime
//! \param rng a RandomNumberGenerator to produce keying material /// \param rng a RandomNumberGenerator to produce keying material
//! \param bits the number of bits in the prime number /// \param bits the number of bits in the prime number
//! \returns Integer() meeting Maurer's tests for primality /// \returns Integer() meeting Maurer's tests for primality
CRYPTOPP_DLL Integer CRYPTOPP_API MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits); CRYPTOPP_DLL Integer CRYPTOPP_API MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits);
//! \brief Generates a provable prime /// \brief Generates a provable prime
//! \param rng a RandomNumberGenerator to produce keying material /// \param rng a RandomNumberGenerator to produce keying material
//! \param bits the number of bits in the prime number /// \param bits the number of bits in the prime number
//! \returns Integer() meeting Mihailescu's tests for primality /// \returns Integer() meeting Mihailescu's tests for primality
//! \details Mihailescu's methods performs a search using algorithmic progressions. /// \details Mihailescu's methods performs a search using algorithmic progressions.
CRYPTOPP_DLL Integer CRYPTOPP_API MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits); CRYPTOPP_DLL Integer CRYPTOPP_API MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int bits);
//! \brief Tests whether a number is a small prime /// \brief Tests whether a number is a small prime
//! \param p a candidate prime to test /// \param p a candidate prime to test
//! \returns true if p is a small prime, false otherwise /// \returns true if p is a small prime, false otherwise
//! \details Internally, the library maintains a table fo the first 32719 prime numbers /// \details Internally, the library maintains a table fo the first 32719 prime numbers
//! in sorted order. IsSmallPrime() searches the table and returns true if p is /// in sorted order. IsSmallPrime() searches the table and returns true if p is
//! in the table. /// in the table.
CRYPTOPP_DLL bool CRYPTOPP_API IsSmallPrime(const Integer &p); CRYPTOPP_DLL bool CRYPTOPP_API IsSmallPrime(const Integer &p);
//! ///
//! \returns true if p is divisible by some prime less than bound. /// \returns true if p is divisible by some prime less than bound.
//! \details TrialDivision() true if p is divisible by some prime less than bound. bound not be /// \details TrialDivision() true if p is divisible by some prime less than bound. bound not be
//! greater than the largest entry in the prime table, which is 32719. /// greater than the largest entry in the prime table, which is 32719.
CRYPTOPP_DLL bool CRYPTOPP_API TrialDivision(const Integer &p, unsigned bound); CRYPTOPP_DLL bool CRYPTOPP_API TrialDivision(const Integer &p, unsigned bound);
// returns true if p is NOT divisible by small primes // returns true if p is NOT divisible by small primes
@ -58,25 +58,25 @@ CRYPTOPP_DLL bool CRYPTOPP_API IsStrongLucasProbablePrime(const Integer &n);
// for several rounds with random bases // for several rounds with random bases
CRYPTOPP_DLL bool CRYPTOPP_API RabinMillerTest(RandomNumberGenerator &rng, const Integer &w, unsigned int rounds); CRYPTOPP_DLL bool CRYPTOPP_API RabinMillerTest(RandomNumberGenerator &rng, const Integer &w, unsigned int rounds);
//! \brief Verifies a prime number /// \brief Verifies a prime number
//! \param p a candidate prime to test /// \param p a candidate prime to test
//! \returns true if p is a probable prime, false otherwise /// \returns true if p is a probable prime, false otherwise
//! \details IsPrime() is suitable for testing candidate primes when creating them. Internally, /// \details IsPrime() is suitable for testing candidate primes when creating them. Internally,
//! IsPrime() utilizes SmallDivisorsTest(), IsStrongProbablePrime() and IsStrongLucasProbablePrime(). /// IsPrime() utilizes SmallDivisorsTest(), IsStrongProbablePrime() and IsStrongLucasProbablePrime().
CRYPTOPP_DLL bool CRYPTOPP_API IsPrime(const Integer &p); CRYPTOPP_DLL bool CRYPTOPP_API IsPrime(const Integer &p);
//! \brief Verifies a prime number /// \brief Verifies a prime number
//! \param rng a RandomNumberGenerator for randomized testing /// \param rng a RandomNumberGenerator for randomized testing
//! \param p a candidate prime to test /// \param p a candidate prime to test
//! \param level the level of thoroughness of testing /// \param level the level of thoroughness of testing
//! \returns true if p is a strong probable prime, false otherwise /// \returns true if p is a strong probable prime, false otherwise
//! \details VerifyPrime() is suitable for testing candidate primes created by others. Internally, /// \details VerifyPrime() is suitable for testing candidate primes created by others. Internally,
//! VerifyPrime() utilizes IsPrime() and one-round RabinMillerTest(). If the candiate passes and /// VerifyPrime() utilizes IsPrime() and one-round RabinMillerTest(). If the candiate passes and
//! level is greater than 1, then 10 round RabinMillerTest() primality testing is performed. /// level is greater than 1, then 10 round RabinMillerTest() primality testing is performed.
CRYPTOPP_DLL bool CRYPTOPP_API VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level = 1); CRYPTOPP_DLL bool CRYPTOPP_API VerifyPrime(RandomNumberGenerator &rng, const Integer &p, unsigned int level = 1);
//! \class PrimeSelector /// \class PrimeSelector
//! \brief Application callback to signal suitability of a cabdidate prime /// \brief Application callback to signal suitability of a cabdidate prime
class CRYPTOPP_DLL PrimeSelector class CRYPTOPP_DLL PrimeSelector
{ {
public: public:
@ -84,16 +84,16 @@ public:
virtual bool IsAcceptable(const Integer &candidate) const =0; virtual bool IsAcceptable(const Integer &candidate) const =0;
}; };
//! \brief Finds a random prime of special form /// \brief Finds a random prime of special form
//! \param p an Integer reference to receive the prime /// \param p an Integer reference to receive the prime
//! \param max the maximum value /// \param max the maximum value
//! \param equiv the equivalence class based on the parameter mod /// \param equiv the equivalence class based on the parameter mod
//! \param mod the modulus used to reduce the equivalence class /// \param mod the modulus used to reduce the equivalence class
//! \param pSelector pointer to a PrimeSelector function for the application to signal suitability /// \param pSelector pointer to a PrimeSelector function for the application to signal suitability
//! \returns true if and only if FirstPrime() finds a prime and returns the prime through p. If FirstPrime() /// \returns true if and only if FirstPrime() finds a prime and returns the prime through p. If FirstPrime()
//! returns false, then no such prime exists and the value of p is undefined /// returns false, then no such prime exists and the value of p is undefined
//! \details FirstPrime() uses a fast sieve to find the first probable prime /// \details FirstPrime() uses a fast sieve to find the first probable prime
//! in <tt>{x | p<=x<=max and x%mod==equiv}</tt> /// in <tt>{x | p<=x<=max and x%mod==equiv}</tt>
CRYPTOPP_DLL bool CRYPTOPP_API FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector); CRYPTOPP_DLL bool CRYPTOPP_API FirstPrime(Integer &p, const Integer &max, const Integer &equiv, const Integer &mod, const PrimeSelector *pSelector);
CRYPTOPP_DLL unsigned int CRYPTOPP_API PrimeSearchInterval(const Integer &max); CRYPTOPP_DLL unsigned int CRYPTOPP_API PrimeSearchInterval(const Integer &max);
@ -143,54 +143,54 @@ CRYPTOPP_DLL unsigned int CRYPTOPP_API FactoringWorkFactor(unsigned int bitlengt
// ******************************************************** // ********************************************************
//! \class PrimeAndGenerator /// \class PrimeAndGenerator
//! \brief Generator of prime numbers of special forms /// \brief Generator of prime numbers of special forms
class CRYPTOPP_DLL PrimeAndGenerator class CRYPTOPP_DLL PrimeAndGenerator
{ {
public: public:
//! \brief Construct a PrimeAndGenerator /// \brief Construct a PrimeAndGenerator
PrimeAndGenerator() {} PrimeAndGenerator() {}
//! \brief Construct a PrimeAndGenerator /// \brief Construct a PrimeAndGenerator
//! \param delta +1 or -1 /// \param delta +1 or -1
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param pbits the number of bits in the prime p /// \param pbits the number of bits in the prime p
//! \details PrimeAndGenerator() generates a random prime p of the form <tt>2*q+delta</tt>, where delta is 1 or -1 and q is /// \details PrimeAndGenerator() generates a random prime p of the form <tt>2*q+delta</tt>, where delta is 1 or -1 and q is
//! also prime. Internally the constructor calls <tt>Generate(delta, rng, pbits, pbits-1)</tt>. /// also prime. Internally the constructor calls <tt>Generate(delta, rng, pbits, pbits-1)</tt>.
//! \pre <tt>pbits > 5</tt> /// \pre <tt>pbits > 5</tt>
//! \warning This PrimeAndGenerator() is slow because primes of this form are harder to find. /// \warning This PrimeAndGenerator() is slow because primes of this form are harder to find.
PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits) PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits)
{Generate(delta, rng, pbits, pbits-1);} {Generate(delta, rng, pbits, pbits-1);}
//! \brief Construct a PrimeAndGenerator /// \brief Construct a PrimeAndGenerator
//! \param delta +1 or -1 /// \param delta +1 or -1
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param pbits the number of bits in the prime p /// \param pbits the number of bits in the prime p
//! \param qbits the number of bits in the prime q /// \param qbits the number of bits in the prime q
//! \details PrimeAndGenerator() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime. /// \details PrimeAndGenerator() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime.
//! Internally the constructor calls <tt>Generate(delta, rng, pbits, qbits)</tt>. /// Internally the constructor calls <tt>Generate(delta, rng, pbits, qbits)</tt>.
//! \pre <tt>qbits > 4 && pbits > qbits</tt> /// \pre <tt>qbits > 4 && pbits > qbits</tt>
PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits) PrimeAndGenerator(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits)
{Generate(delta, rng, pbits, qbits);} {Generate(delta, rng, pbits, qbits);}
//! \brief Generate a Prime and Generator /// \brief Generate a Prime and Generator
//! \param delta +1 or -1 /// \param delta +1 or -1
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param pbits the number of bits in the prime p /// \param pbits the number of bits in the prime p
//! \param qbits the number of bits in the prime q /// \param qbits the number of bits in the prime q
//! \details Generate() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime. /// \details Generate() generates a random prime p of the form <tt>2*r*q+delta</tt>, where q is also prime.
void Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits); void Generate(signed int delta, RandomNumberGenerator &rng, unsigned int pbits, unsigned qbits);
//! \brief Retrieve first prime /// \brief Retrieve first prime
//! \returns Prime() returns the prime p. /// \returns Prime() returns the prime p.
const Integer& Prime() const {return p;} const Integer& Prime() const {return p;}
//! \brief Retrieve second prime /// \brief Retrieve second prime
//! \returns SubPrime() returns the prime q. /// \returns SubPrime() returns the prime q.
const Integer& SubPrime() const {return q;} const Integer& SubPrime() const {return q;}
//! \brief Retrieve the generator /// \brief Retrieve the generator
//! \returns Generator() returns the the generator g. /// \returns Generator() returns the the generator g.
const Integer& Generator() const {return g;} const Integer& Generator() const {return g;}
private: private:

View File

@ -50,17 +50,17 @@ private:
double GetCurTimeAndCleanUp(); double GetCurTimeAndCleanUp();
}; };
//! a Source class that can pump from a device for a specified amount of time. /// a Source class that can pump from a device for a specified amount of time.
class CRYPTOPP_NO_VTABLE NonblockingSource : public AutoSignaling<Source>, public LimitedBandwidth class CRYPTOPP_NO_VTABLE NonblockingSource : public AutoSignaling<Source>, public LimitedBandwidth
{ {
public: public:
NonblockingSource(BufferedTransformation *attachment) NonblockingSource(BufferedTransformation *attachment)
: m_messageEndSent(false) , m_doPumpBlocked(false), m_blockedBySpeedLimit(false) {Detach(attachment);} : m_messageEndSent(false) , m_doPumpBlocked(false), m_blockedBySpeedLimit(false) {Detach(attachment);}
//! \name NONBLOCKING SOURCE /// \name NONBLOCKING SOURCE
//@{ //@{
//! pump up to maxSize bytes using at most maxTime milliseconds /// pump up to maxSize bytes using at most maxTime milliseconds
/*! If checkDelimiter is true, pump up to delimiter, which itself is not extracted or pumped. */ /*! If checkDelimiter is true, pump up to delimiter, which itself is not extracted or pumped. */
size_t GeneralPump2(lword &byteCount, bool blockingOutput=true, unsigned long maxTime=INFINITE_TIME, bool checkDelimiter=false, byte delimiter='\n'); size_t GeneralPump2(lword &byteCount, bool blockingOutput=true, unsigned long maxTime=INFINITE_TIME, bool checkDelimiter=false, byte delimiter='\n');
@ -89,13 +89,13 @@ private:
bool m_messageEndSent, m_doPumpBlocked, m_blockedBySpeedLimit; bool m_messageEndSent, m_doPumpBlocked, m_blockedBySpeedLimit;
}; };
//! Network Receiver /// Network Receiver
class CRYPTOPP_NO_VTABLE NetworkReceiver : public Waitable class CRYPTOPP_NO_VTABLE NetworkReceiver : public Waitable
{ {
public: public:
virtual bool MustWaitToReceive() {return false;} virtual bool MustWaitToReceive() {return false;}
virtual bool MustWaitForResult() {return false;} virtual bool MustWaitForResult() {return false;}
//! receive data from network source, returns whether result is immediately available /// receive data from network source, returns whether result is immediately available
virtual bool Receive(byte* buf, size_t bufLen) =0; virtual bool Receive(byte* buf, size_t bufLen) =0;
virtual unsigned int GetReceiveResult() =0; virtual unsigned int GetReceiveResult() =0;
virtual bool EofReceived() const =0; virtual bool EofReceived() const =0;
@ -108,13 +108,13 @@ public:
virtual size_t GetMaxBufferSize() const =0; virtual size_t GetMaxBufferSize() const =0;
virtual size_t GetCurrentBufferSize() const =0; virtual size_t GetCurrentBufferSize() const =0;
virtual bool EofPending() const =0; virtual bool EofPending() const =0;
//! compute the current speed of this sink in bytes per second /// compute the current speed of this sink in bytes per second
virtual float ComputeCurrentSpeed() =0; virtual float ComputeCurrentSpeed() =0;
//! get the maximum observed speed of this sink in bytes per second /// get the maximum observed speed of this sink in bytes per second
virtual float GetMaxObservedSpeed() const =0; virtual float GetMaxObservedSpeed() const =0;
}; };
//! a Sink class that queues input and can flush to a device for a specified amount of time. /// a Sink class that queues input and can flush to a device for a specified amount of time.
class CRYPTOPP_NO_VTABLE NonblockingSink : public Sink, public NonblockingSinkInfo, public LimitedBandwidth class CRYPTOPP_NO_VTABLE NonblockingSink : public Sink, public NonblockingSinkInfo, public LimitedBandwidth
{ {
public: public:
@ -122,7 +122,7 @@ public:
bool IsolatedFlush(bool hardFlush, bool blocking); bool IsolatedFlush(bool hardFlush, bool blocking);
//! flush to device for no more than maxTime milliseconds /// flush to device for no more than maxTime milliseconds
/*! This function will repeatedly attempt to flush data to some device, until /*! This function will repeatedly attempt to flush data to some device, until
the queue is empty, or a total of maxTime milliseconds have elapsed. the queue is empty, or a total of maxTime milliseconds have elapsed.
If maxTime == 0, at least one attempt will be made to flush some data, but If maxTime == 0, at least one attempt will be made to flush some data, but
@ -135,7 +135,7 @@ public:
lword TimedFlush(unsigned long maxTime, size_t targetSize = 0); lword TimedFlush(unsigned long maxTime, size_t targetSize = 0);
virtual void SetMaxBufferSize(size_t maxBufferSize) =0; virtual void SetMaxBufferSize(size_t maxBufferSize) =0;
//! set a bound which will cause sink to flush if exceeded by GetCurrentBufferSize() /// set a bound which will cause sink to flush if exceeded by GetCurrentBufferSize()
virtual void SetAutoFlushBound(size_t bound) =0; virtual void SetAutoFlushBound(size_t bound) =0;
protected: protected:
@ -147,7 +147,7 @@ private:
bool m_blockedBySpeedLimit; bool m_blockedBySpeedLimit;
}; };
//! Network Sender /// Network Sender
class CRYPTOPP_NO_VTABLE NetworkSender : public Waitable class CRYPTOPP_NO_VTABLE NetworkSender : public Waitable
{ {
public: public:
@ -160,7 +160,7 @@ public:
virtual bool EofSent() {return false;} // implement if MustWaitForEof() == true virtual bool EofSent() {return false;} // implement if MustWaitForEof() == true
}; };
//! Network Source /// Network Source
class CRYPTOPP_NO_VTABLE NetworkSource : public NonblockingSource class CRYPTOPP_NO_VTABLE NetworkSource : public NonblockingSource
{ {
public: public:
@ -183,7 +183,7 @@ private:
bool m_waitingForResult, m_outputBlocked; bool m_waitingForResult, m_outputBlocked;
}; };
//! Network Sink /// Network Sink
class CRYPTOPP_NO_VTABLE NetworkSink : public NonblockingSink class CRYPTOPP_NO_VTABLE NetworkSink : public NonblockingSink
{ {
public: public:
@ -204,9 +204,9 @@ public:
bool EofPending() const { return m_eofState > EOF_NONE && m_eofState < EOF_DONE; } bool EofPending() const { return m_eofState > EOF_NONE && m_eofState < EOF_DONE; }
//! compute the current speed of this sink in bytes per second /// compute the current speed of this sink in bytes per second
float ComputeCurrentSpeed(); float ComputeCurrentSpeed();
//! get the maximum observed speed of this sink in bytes per second /// get the maximum observed speed of this sink in bytes per second
float GetMaxObservedSpeed() const; float GetMaxObservedSpeed() const;
protected: protected:

6
oaep.h
View File

@ -7,7 +7,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief OAEP padding base class /// \brief OAEP padding base class
class CRYPTOPP_DLL OAEP_Base : public PK_EncryptionMessageEncodingMethod class CRYPTOPP_DLL OAEP_Base : public PK_EncryptionMessageEncodingMethod
{ {
public: public:
@ -22,8 +22,8 @@ protected:
virtual MaskGeneratingFunction * NewMGF() const =0; virtual MaskGeneratingFunction * NewMGF() const =0;
}; };
//! \brief OAEP padding /// \brief OAEP padding
//! \sa <a href="http://www.weidai.com/scan-mirror/ca.html#cem_OAEP-MGF1">EME-OAEP</a>, for use with classes derived from TF_ES /// \sa <a href="http://www.weidai.com/scan-mirror/ca.html#cem_OAEP-MGF1">EME-OAEP</a>, for use with classes derived from TF_ES
template <class H, class MGF=P1363_MGF1> template <class H, class MGF=P1363_MGF1>
class OAEP : public OAEP_Base, public EncryptionStandard class OAEP : public OAEP_Base, public EncryptionStandard
{ {

16
oids.h
View File

@ -1,13 +1,13 @@
// oids.h - originally written and placed in the public domain by Wei Dai // oids.h - originally written and placed in the public domain by Wei Dai
//! \file oids.h /// \file oids.h
//! \brief ASN.1 object identifiers for algorthms and schemes /// \brief ASN.1 object identifiers for algorthms and schemes
//! \details Most OIDs can be found at http://www.oid-info.com/. The Chinese OIDs /// \details Most OIDs can be found at http://www.oid-info.com/. The Chinese OIDs
//! are assigned in GM/T 0006-2012, Cryptographic Application Identifier Criterion /// are assigned in GM/T 0006-2012, Cryptographic Application Identifier Criterion
//! Specification. A reproduction can be found at http://gmssl.org/docs/oid.html. /// Specification. A reproduction can be found at http://gmssl.org/docs/oid.html.
//! There seems to be some confusion between the text of GmSSL's oid.html web page /// There seems to be some confusion between the text of GmSSL's oid.html web page
//! and the actual OID used in the code. We used the same OIDs that were detailed in /// and the actual OID used in the code. We used the same OIDs that were detailed in
//! http://github.com/guanzhi/GmSSL/blob/master/crypto/objects/objects.txt. /// http://github.com/guanzhi/GmSSL/blob/master/crypto/objects/objects.txt.
#ifndef CRYPTOPP_OIDS_H #ifndef CRYPTOPP_OIDS_H
#define CRYPTOPP_OIDS_H #define CRYPTOPP_OIDS_H

188
osrng.h
View File

@ -1,7 +1,7 @@
// osrng.h - originally written and placed in the public domain by Wei Dai // osrng.h - originally written and placed in the public domain by Wei Dai
//! \file osrng.h /// \file osrng.h
//! \brief Classes for access to the operating system's random number generators /// \brief Classes for access to the operating system's random number generators
#ifndef CRYPTOPP_OSRNG_H #ifndef CRYPTOPP_OSRNG_H
#define CRYPTOPP_OSRNG_H #define CRYPTOPP_OSRNG_H
@ -20,26 +20,26 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class OS_RNG_Err /// \class OS_RNG_Err
//! \brief Exception thrown when an operating system error is encountered /// \brief Exception thrown when an operating system error is encountered
class CRYPTOPP_DLL OS_RNG_Err : public Exception class CRYPTOPP_DLL OS_RNG_Err : public Exception
{ {
public: public:
//! \brief Constructs an OS_RNG_Err /// \brief Constructs an OS_RNG_Err
//! \param operation the operation or API call when the error occurs /// \param operation the operation or API call when the error occurs
OS_RNG_Err(const std::string &operation); OS_RNG_Err(const std::string &operation);
}; };
#ifdef NONBLOCKING_RNG_AVAILABLE #ifdef NONBLOCKING_RNG_AVAILABLE
#ifdef CRYPTOPP_WIN32_AVAILABLE #ifdef CRYPTOPP_WIN32_AVAILABLE
//! \class MicrosoftCryptoProvider /// \class MicrosoftCryptoProvider
//! \brief Wrapper for Microsoft crypto service provider /// \brief Wrapper for Microsoft crypto service provider
//! \sa \def USE_MS_CRYPTOAPI, \def USE_MS_CNGAPI /// \sa \def USE_MS_CRYPTOAPI, \def USE_MS_CNGAPI
class CRYPTOPP_DLL MicrosoftCryptoProvider class CRYPTOPP_DLL MicrosoftCryptoProvider
{ {
public: public:
//! \brief Construct a MicrosoftCryptoProvider /// \brief Construct a MicrosoftCryptoProvider
MicrosoftCryptoProvider(); MicrosoftCryptoProvider();
~MicrosoftCryptoProvider(); ~MicrosoftCryptoProvider();
@ -57,13 +57,13 @@ public:
typedef PVOID ProviderHandle; typedef PVOID ProviderHandle;
#endif // USE_MS_CRYPTOAPI or USE_MS_CNGAPI #endif // USE_MS_CRYPTOAPI or USE_MS_CNGAPI
//! \brief Retrieves the provider handle /// \brief Retrieves the provider handle
//! \returns CryptoAPI provider handle /// \returns CryptoAPI provider handle
//! \details If USE_MS_CRYPTOAPI is in effect, then CryptAcquireContext() /// \details If USE_MS_CRYPTOAPI is in effect, then CryptAcquireContext()
//! acquires then handle and CryptReleaseContext() releases the handle /// acquires then handle and CryptReleaseContext() releases the handle
//! upon destruction. If USE_MS_CNGAPI is in effect, then /// upon destruction. If USE_MS_CNGAPI is in effect, then
//! BCryptOpenAlgorithmProvider() acquires then handle and /// BCryptOpenAlgorithmProvider() acquires then handle and
//! BCryptCloseAlgorithmProvider() releases the handle upon destruction. /// BCryptCloseAlgorithmProvider() releases the handle upon destruction.
ProviderHandle GetProviderHandle() const {return m_hProvider;} ProviderHandle GetProviderHandle() const {return m_hProvider;}
private: private:
@ -80,10 +80,10 @@ private:
#endif // CRYPTOPP_WIN32_AVAILABLE #endif // CRYPTOPP_WIN32_AVAILABLE
//! \class NonblockingRng /// \class NonblockingRng
//! \brief Wrapper class for /dev/random and /dev/srandom /// \brief Wrapper class for /dev/random and /dev/srandom
//! \details Encapsulates CryptoAPI's CryptGenRandom() or CryptoNG's BCryptGenRandom() /// \details Encapsulates CryptoAPI's CryptGenRandom() or CryptoNG's BCryptGenRandom()
//! on Windows, or /dev/urandom on Unix and compatibles. /// on Windows, or /dev/urandom on Unix and compatibles.
class CRYPTOPP_DLL NonblockingRng : public RandomNumberGenerator class CRYPTOPP_DLL NonblockingRng : public RandomNumberGenerator
{ {
public: public:
@ -91,13 +91,13 @@ public:
~NonblockingRng(); ~NonblockingRng();
//! \brief Construct a NonblockingRng /// \brief Construct a NonblockingRng
NonblockingRng(); NonblockingRng();
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
//! \details GenerateIntoBufferedTransformation() calls are routed to GenerateBlock(). /// \details GenerateIntoBufferedTransformation() calls are routed to GenerateBlock().
void GenerateBlock(byte *output, size_t size); void GenerateBlock(byte *output, size_t size);
protected: protected:
@ -112,13 +112,13 @@ protected:
#if defined(BLOCKING_RNG_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(BLOCKING_RNG_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \class BlockingRng /// \class BlockingRng
//! \brief Wrapper class for /dev/random and /dev/srandom /// \brief Wrapper class for /dev/random and /dev/srandom
//! \details Encapsulates /dev/random on Linux, OS X and Unix; and /dev/srandom on the BSDs. /// \details Encapsulates /dev/random on Linux, OS X and Unix; and /dev/srandom on the BSDs.
//! \note On Linux the /dev/random interface is effectively deprecated. According to the /// \note On Linux the /dev/random interface is effectively deprecated. According to the
//! Kernel Crypto developers, /dev/urandom or getrandom(2) should be used instead. Also /// Kernel Crypto developers, /dev/urandom or getrandom(2) should be used instead. Also
//! see <A HREF="https://lkml.org/lkml/2017/7/20/993">[RFC PATCH v12 3/4] Linux Random /// see <A HREF="https://lkml.org/lkml/2017/7/20/993">[RFC PATCH v12 3/4] Linux Random
//! Number Generator</A> on the kernel-crypto mailing list. /// Number Generator</A> on the kernel-crypto mailing list.
class CRYPTOPP_DLL BlockingRng : public RandomNumberGenerator class CRYPTOPP_DLL BlockingRng : public RandomNumberGenerator
{ {
public: public:
@ -126,13 +126,13 @@ public:
~BlockingRng(); ~BlockingRng();
//! \brief Construct a BlockingRng /// \brief Construct a BlockingRng
BlockingRng(); BlockingRng();
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
//! \details GenerateIntoBufferedTransformation() calls are routed to GenerateBlock(). /// \details GenerateIntoBufferedTransformation() calls are routed to GenerateBlock().
void GenerateBlock(byte *output, size_t size); void GenerateBlock(byte *output, size_t size);
protected: protected:
@ -141,22 +141,22 @@ protected:
#endif #endif
//! OS_GenerateRandomBlock /// OS_GenerateRandomBlock
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param blocking specifies whther a bobcking or non-blocking generator should be used /// \param blocking specifies whther a bobcking or non-blocking generator should be used
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
//! \details OS_GenerateRandomBlock() uses the underlying operating system's /// \details OS_GenerateRandomBlock() uses the underlying operating system's
//! random number generator. On Windows, CryptGenRandom() is called using NonblockingRng. /// random number generator. On Windows, CryptGenRandom() is called using NonblockingRng.
//! \details On Unix and compatibles, /dev/urandom is called if blocking is false using /// \details On Unix and compatibles, /dev/urandom is called if blocking is false using
//! NonblockingRng. If blocking is true, then either /dev/randomd or /dev/srandom is used /// NonblockingRng. If blocking is true, then either /dev/randomd or /dev/srandom is used
//! by way of BlockingRng, if available. /// by way of BlockingRng, if available.
CRYPTOPP_DLL void CRYPTOPP_API OS_GenerateRandomBlock(bool blocking, byte *output, size_t size); CRYPTOPP_DLL void CRYPTOPP_API OS_GenerateRandomBlock(bool blocking, byte *output, size_t size);
//! \class AutoSeededRandomPool /// \class AutoSeededRandomPool
//! \brief Automatically Seeded Randomness Pool /// \brief Automatically Seeded Randomness Pool
//! \details This class seeds itself using an operating system provided RNG. /// \details This class seeds itself using an operating system provided RNG.
//! AutoSeededRandomPool was suggested by Leonard Janke. /// AutoSeededRandomPool was suggested by Leonard Janke.
class CRYPTOPP_DLL AutoSeededRandomPool : public RandomPool class CRYPTOPP_DLL AutoSeededRandomPool : public RandomPool
{ {
public: public:
@ -164,29 +164,29 @@ public:
~AutoSeededRandomPool() {} ~AutoSeededRandomPool() {}
//! \brief Construct an AutoSeededRandomPool /// \brief Construct an AutoSeededRandomPool
//! \param blocking controls seeding with BlockingRng or NonblockingRng /// \param blocking controls seeding with BlockingRng or NonblockingRng
//! \param seedSize the size of the seed, in bytes /// \param seedSize the size of the seed, in bytes
//! \details Use blocking to choose seeding with BlockingRng or NonblockingRng. /// \details Use blocking to choose seeding with BlockingRng or NonblockingRng.
//! The parameter is ignored if only one of these is available. /// The parameter is ignored if only one of these is available.
explicit AutoSeededRandomPool(bool blocking = false, unsigned int seedSize = 32) explicit AutoSeededRandomPool(bool blocking = false, unsigned int seedSize = 32)
{Reseed(blocking, seedSize);} {Reseed(blocking, seedSize);}
//! \brief Reseed an AutoSeededRandomPool /// \brief Reseed an AutoSeededRandomPool
//! \param blocking controls seeding with BlockingRng or NonblockingRng /// \param blocking controls seeding with BlockingRng or NonblockingRng
//! \param seedSize the size of the seed, in bytes /// \param seedSize the size of the seed, in bytes
void Reseed(bool blocking = false, unsigned int seedSize = 32); void Reseed(bool blocking = false, unsigned int seedSize = 32);
}; };
//! \class AutoSeededX917RNG /// \class AutoSeededX917RNG
//! \tparam BLOCK_CIPHER a block cipher /// \tparam BLOCK_CIPHER a block cipher
//! \brief Automatically Seeded X9.17 RNG /// \brief Automatically Seeded X9.17 RNG
//! \details AutoSeededX917RNG is from ANSI X9.17 Appendix C, seeded using an OS provided RNG. /// \details AutoSeededX917RNG is from ANSI X9.17 Appendix C, seeded using an OS provided RNG.
//! If 3-key TripleDES (DES_EDE3) is used, then its a X9.17 conforming generator. If AES is /// If 3-key TripleDES (DES_EDE3) is used, then its a X9.17 conforming generator. If AES is
//! used, then its a X9.31 conforming generator. /// used, then its a X9.31 conforming generator.
//! \details Though ANSI X9 prescribes 3-key TripleDES, the template parameter BLOCK_CIPHER can be any /// \details Though ANSI X9 prescribes 3-key TripleDES, the template parameter BLOCK_CIPHER can be any
//! BlockTransformation derived class. /// BlockTransformation derived class.
//! \sa X917RNG, DefaultAutoSeededRNG /// \sa X917RNG, DefaultAutoSeededRNG
template <class BLOCK_CIPHER> template <class BLOCK_CIPHER>
class AutoSeededX917RNG : public RandomNumberGenerator, public NotCopyable class AutoSeededX917RNG : public RandomNumberGenerator, public NotCopyable
{ {
@ -195,31 +195,31 @@ public:
~AutoSeededX917RNG() {} ~AutoSeededX917RNG() {}
//! \brief Construct an AutoSeededX917RNG /// \brief Construct an AutoSeededX917RNG
//! \param blocking controls seeding with BlockingRng or NonblockingRng /// \param blocking controls seeding with BlockingRng or NonblockingRng
//! \param autoSeed controls auto seeding of the generator /// \param autoSeed controls auto seeding of the generator
//! \details Use blocking to choose seeding with BlockingRng or NonblockingRng. /// \details Use blocking to choose seeding with BlockingRng or NonblockingRng.
//! The parameter is ignored if only one of these is available. /// The parameter is ignored if only one of these is available.
//! \sa X917RNG /// \sa X917RNG
explicit AutoSeededX917RNG(bool blocking = false, bool autoSeed = true) explicit AutoSeededX917RNG(bool blocking = false, bool autoSeed = true)
{if (autoSeed) Reseed(blocking);} {if (autoSeed) Reseed(blocking);}
//! \brief Reseed an AutoSeededX917RNG /// \brief Reseed an AutoSeededX917RNG
//! \param blocking controls seeding with BlockingRng or NonblockingRng /// \param blocking controls seeding with BlockingRng or NonblockingRng
//! \param additionalEntropy additional entropy to add to the generator /// \param additionalEntropy additional entropy to add to the generator
//! \param length the size of the additional entropy, in bytes /// \param length the size of the additional entropy, in bytes
//! \details Internally, the generator uses SHA256 to extract the entropy from /// \details Internally, the generator uses SHA256 to extract the entropy from
//! from the seed and then stretch the material for the block cipher's key /// from the seed and then stretch the material for the block cipher's key
//! and initialization vector. /// and initialization vector.
void Reseed(bool blocking = false, const byte *additionalEntropy = NULLPTR, size_t length = 0); void Reseed(bool blocking = false, const byte *additionalEntropy = NULLPTR, size_t length = 0);
//! \brief Deterministically reseed an AutoSeededX917RNG for testing /// \brief Deterministically reseed an AutoSeededX917RNG for testing
//! \param key the key to use for the deterministic reseeding /// \param key the key to use for the deterministic reseeding
//! \param keylength the size of the key, in bytes /// \param keylength the size of the key, in bytes
//! \param seed the seed to use for the deterministic reseeding /// \param seed the seed to use for the deterministic reseeding
//! \param timeVector a time vector to use for deterministic reseeding /// \param timeVector a time vector to use for deterministic reseeding
//! \details This is a testing interface for testing purposes, and should \a NOT /// \details This is a testing interface for testing purposes, and should \a NOT
//! be used in production. /// be used in production.
void Reseed(const byte *key, size_t keylength, const byte *seed, const byte *timeVector); void Reseed(const byte *key, size_t keylength, const byte *seed, const byte *timeVector);
bool CanIncorporateEntropy() const {return true;} bool CanIncorporateEntropy() const {return true;}
@ -262,11 +262,11 @@ void AutoSeededX917RNG<BLOCK_CIPHER>::Reseed(bool blocking, const byte *input, s
CRYPTOPP_DLL_TEMPLATE_CLASS AutoSeededX917RNG<AES>; CRYPTOPP_DLL_TEMPLATE_CLASS AutoSeededX917RNG<AES>;
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \class DefaultAutoSeededRNG /// \class DefaultAutoSeededRNG
//! \brief A typedef providing a default generator /// \brief A typedef providing a default generator
//! \details DefaultAutoSeededRNG is a typedef of either AutoSeededX917RNG<AES> or AutoSeededRandomPool. /// \details DefaultAutoSeededRNG is a typedef of either AutoSeededX917RNG<AES> or AutoSeededRandomPool.
//! If CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined, then DefaultAutoSeededRNG is /// If CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 is defined, then DefaultAutoSeededRNG is
//! AutoSeededX917RNG<AES>. Otherwise, DefaultAutoSeededRNG is AutoSeededRandomPool. /// AutoSeededX917RNG<AES>. Otherwise, DefaultAutoSeededRNG is AutoSeededRandomPool.
class DefaultAutoSeededRNG {} class DefaultAutoSeededRNG {}
#else #else
// AutoSeededX917RNG<AES> in FIPS mode, otherwise it's AutoSeededRandomPool // AutoSeededX917RNG<AES> in FIPS mode, otherwise it's AutoSeededRandomPool

96
ossig.h
View File

@ -1,8 +1,8 @@
// ossig.h - written and placed in the public domain by Jeffrey Walton // ossig.h - written and placed in the public domain by Jeffrey Walton
// //
//! \file ossig.h /// \file ossig.h
//! \brief Utility class for trapping OS signals. /// \brief Utility class for trapping OS signals.
//! \since Crypto++ 5.6.5 /// \since Crypto++ 5.6.5
#ifndef CRYPTOPP_OS_SIGNAL_H #ifndef CRYPTOPP_OS_SIGNAL_H
#define CRYPTOPP_OS_SIGNAL_H #define CRYPTOPP_OS_SIGNAL_H
@ -19,62 +19,62 @@ NAMESPACE_BEGIN(CryptoPP)
#if defined(UNIX_SIGNALS_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(UNIX_SIGNALS_AVAILABLE) || defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \brief Signal handler function pointer /// \brief Signal handler function pointer
//! \details SignalHandlerFn is provided as a stand alone function pointer with external "C" linkage /// \details SignalHandlerFn is provided as a stand alone function pointer with external "C" linkage
//! \sa SignalHandler, NullSignalHandler /// \sa SignalHandler, NullSignalHandler
extern "C" { extern "C" {
typedef void (*SignalHandlerFn) (int); typedef void (*SignalHandlerFn) (int);
}; };
//! \brief Null signal handler function /// \brief Null signal handler function
//! \param unused the signal number /// \param unused the signal number
//! \details NullSignalHandler is provided as a stand alone function with external "C" linkage /// \details NullSignalHandler is provided as a stand alone function with external "C" linkage
//! and not a static member function due to the the member function's implicit /// and not a static member function due to the the member function's implicit
//! external "C++" linkage. /// external "C++" linkage.
//! \sa SignalHandler, SignalHandlerFn /// \sa SignalHandler, SignalHandlerFn
extern "C" { extern "C" {
inline void NullSignalHandler(int unused) {CRYPTOPP_UNUSED(unused);} inline void NullSignalHandler(int unused) {CRYPTOPP_UNUSED(unused);}
}; };
//! Signal handler for Linux and Unix compatibles /// Signal handler for Linux and Unix compatibles
//! \tparam S Signal number /// \tparam S Signal number
//! \tparam O Flag indicating exsting handler should be overwriiten /// \tparam O Flag indicating exsting handler should be overwriiten
//! \details SignalHandler() can be used to install a signal handler with the signature /// \details SignalHandler() can be used to install a signal handler with the signature
//! <tt>void handler_fn(int)</tt>. If <tt>SignalHandlerFn</tt> is not <tt>NULL</tt>, then /// <tt>void handler_fn(int)</tt>. If <tt>SignalHandlerFn</tt> is not <tt>NULL</tt>, then
//! the sigaction is set to the function and the sigaction flags is set to the flags. /// the sigaction is set to the function and the sigaction flags is set to the flags.
//! If <tt>SignalHandlerFn</tt> is <tt>NULL</tt>, then a default handler is installed /// If <tt>SignalHandlerFn</tt> is <tt>NULL</tt>, then a default handler is installed
//! using sigaction flags set to 0. The default handler only returns from the call. /// using sigaction flags set to 0. The default handler only returns from the call.
//! \details Upon destruction the previous signal handler is restored if the former signal handler /// \details Upon destruction the previous signal handler is restored if the former signal handler
//! was replaced. /// was replaced.
//! \details On Cygwin systems using Newlib, you should define <tt>_XOPEN_SOURCE=700</tt> or /// \details On Cygwin systems using Newlib, you should define <tt>_XOPEN_SOURCE=700</tt> or
//! <tt>_GNU_SOURCE</tt>; or use <tt>-std=gnu++03</tt>, <tt>-std=gnu++11</tt>, or similar. If /// <tt>_GNU_SOURCE</tt>; or use <tt>-std=gnu++03</tt>, <tt>-std=gnu++11</tt>, or similar. If
//! you compile with <tt>-std=c++03</tt>, <tt>-std=c++11</tt> or similar, then define /// you compile with <tt>-std=c++03</tt>, <tt>-std=c++11</tt> or similar, then define
//! <tt>_XOPEN_SOURCE=700</tt>. /// <tt>_XOPEN_SOURCE=700</tt>.
//! \warning Do not use SignalHandler in a code block that uses <tt>setjmp</tt> or <tt>longjmp</tt> /// \warning Do not use SignalHandler in a code block that uses <tt>setjmp</tt> or <tt>longjmp</tt>
//! because the destructor may not run. /// because the destructor may not run.
//! \since Crypto++ 5.6.5 /// \since Crypto++ 5.6.5
//! \sa NullSignalHandler, SignalHandlerFn, \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT", DebugTrapHandler /// \sa NullSignalHandler, SignalHandlerFn, \ref CRYPTOPP_ASSERT "CRYPTOPP_ASSERT", DebugTrapHandler
template <int S, bool O=false> template <int S, bool O=false>
struct SignalHandler struct SignalHandler
{ {
//! \brief Construct a signal handler /// \brief Construct a signal handler
//! \param pfn Pointer to a signal handler function /// \param pfn Pointer to a signal handler function
//! \param flags Flags to use with the signal handler /// \param flags Flags to use with the signal handler
//! \details SignalHandler() installs a signal handler with the signature /// \details SignalHandler() installs a signal handler with the signature
//! <tt>void handler_fn(int)</tt>. If <tt>SignalHandlerFn</tt> is not <tt>NULL</tt>, then /// <tt>void handler_fn(int)</tt>. If <tt>SignalHandlerFn</tt> is not <tt>NULL</tt>, then
//! the sigaction is set to the function and the sigaction flags is set to the flags. /// the sigaction is set to the function and the sigaction flags is set to the flags.
//! If <tt>SignalHandlerFn</tt> is <tt>NULL</tt>, then a default handler is installed /// If <tt>SignalHandlerFn</tt> is <tt>NULL</tt>, then a default handler is installed
//! using sigaction flags set to 0. The default handler only returns from the call. /// using sigaction flags set to 0. The default handler only returns from the call.
//! \details Upon destruction the previous signal handler is restored if the former signal handler /// \details Upon destruction the previous signal handler is restored if the former signal handler
//! was overwritten. /// was overwritten.
//! \details On Cygwin systems using Newlib, you should define <tt>_XOPEN_SOURCE=700</tt> or /// \details On Cygwin systems using Newlib, you should define <tt>_XOPEN_SOURCE=700</tt> or
//! <tt>_GNU_SOURCE</tt>; or use <tt>-std=gnu++03</tt>, <tt>-std=gnu++11</tt>, or similar. If /// <tt>_GNU_SOURCE</tt>; or use <tt>-std=gnu++03</tt>, <tt>-std=gnu++11</tt>, or similar. If
//! you compile with <tt>-std=c++03</tt>, <tt>-std=c++11</tt> or similar, then define /// you compile with <tt>-std=c++03</tt>, <tt>-std=c++11</tt> or similar, then define
//! <tt>_XOPEN_SOURCE=700</tt>. /// <tt>_XOPEN_SOURCE=700</tt>.
//! \warning Do not use SignalHandler in a code block that uses <tt>setjmp</tt> or <tt>longjmp</tt> /// \warning Do not use SignalHandler in a code block that uses <tt>setjmp</tt> or <tt>longjmp</tt>
//! because the destructor may not run. <tt>setjmp</tt> is why cpu.cpp does not use SignalHandler /// because the destructor may not run. <tt>setjmp</tt> is why cpu.cpp does not use SignalHandler
//! during CPU feature testing. /// during CPU feature testing.
//! \since Crypto++ 5.6.5 /// \since Crypto++ 5.6.5
SignalHandler(SignalHandlerFn pfn = NULLPTR, int flags = 0) : m_installed(false) SignalHandler(SignalHandlerFn pfn = NULLPTR, int flags = 0) : m_installed(false)
{ {
// http://pubs.opengroup.org/onlinepubs/007908799/xsh/sigaction.html // http://pubs.opengroup.org/onlinepubs/007908799/xsh/sigaction.html

View File

@ -1,10 +1,10 @@
// via-rng.h - written and placed in public domain by Jeffrey Walton // via-rng.h - written and placed in public domain by Jeffrey Walton
//! \file padlkrng.h /// \file padlkrng.h
//! \brief Classes for VIA Padlock RNG /// \brief Classes for VIA Padlock RNG
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
//! \sa <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA /// \sa <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA
//! Padlock</A> on the Crypto++ wiki /// Padlock</A> on the Crypto++ wiki
#ifndef CRYPTOPP_PADLOCK_RNG_H #ifndef CRYPTOPP_PADLOCK_RNG_H
#define CRYPTOPP_PADLOCK_RNG_H #define CRYPTOPP_PADLOCK_RNG_H
@ -14,9 +14,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Exception thrown when a PadlockRNG generator encounters /// \brief Exception thrown when a PadlockRNG generator encounters
//! a generator related error. /// a generator related error.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class PadlockRNG_Err : public Exception class PadlockRNG_Err : public Exception
{ {
public: public:
@ -26,27 +26,27 @@ public:
: Exception(OTHER_ERROR, component + ": " + message) {} : Exception(OTHER_ERROR, component + ": " + message) {}
}; };
//! \brief Hardware generated random numbers using VIA XSTORE /// \brief Hardware generated random numbers using VIA XSTORE
//! \details Some VIA processors provide a Security Engine called Padlock. The Padlock /// \details Some VIA processors provide a Security Engine called Padlock. The Padlock
//! Security Engine provides AES, SHA and a RNG. The PadlockRNG class provides access /// Security Engine provides AES, SHA and a RNG. The PadlockRNG class provides access
//! to the RNG. /// to the RNG.
//! \details The VIA generator uses an 8 byte FIFO buffer for random numbers. The /// \details The VIA generator uses an 8 byte FIFO buffer for random numbers. The
//! generator can be configured to discard bits from the buffer to resist analysis. /// generator can be configured to discard bits from the buffer to resist analysis.
//! The <tt>divisor</tt> controls the number of bytes discarded. The formula for /// The <tt>divisor</tt> controls the number of bytes discarded. The formula for
//! the discard amount is <tt>2**divisor - 1</tt>. When <tt>divisor=0</tt> no bits /// the discard amount is <tt>2**divisor - 1</tt>. When <tt>divisor=0</tt> no bits
//! are discarded and the entire 8 byte buffer is read. If <tt>divisor=3</tt> then /// are discarded and the entire 8 byte buffer is read. If <tt>divisor=3</tt> then
//! 7 bytes are discarded and 1 byte is read. TheVIA SDK samples use <tt>divisor=1</tt>. /// 7 bytes are discarded and 1 byte is read. TheVIA SDK samples use <tt>divisor=1</tt>.
//! \details Cryptography Research, Inc (CRI) audited the Padlock Security Engine /// \details Cryptography Research, Inc (CRI) audited the Padlock Security Engine
//! in 2003. CRI provided recommendations to operate the generator for secure and /// in 2003. CRI provided recommendations to operate the generator for secure and
//! non-secure applications. Additionally, the Programmers Guide and SDK provided a /// non-secure applications. Additionally, the Programmers Guide and SDK provided a
//! different configuration in the sample code. /// different configuration in the sample code.
//! \details You can operate the generator according to CRI recommendations by setting /// \details You can operate the generator according to CRI recommendations by setting
//! <tt>divisor</tt>, reading one word (or partial word) at a time from the FIFO, and /// <tt>divisor</tt>, reading one word (or partial word) at a time from the FIFO, and
//! then inspecting the MSR after each read. /// then inspecting the MSR after each read.
//! \details The audit report with recommendations is available on the Crypto++ wiki /// \details The audit report with recommendations is available on the Crypto++ wiki
//! at <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA Padlock</A>. /// at <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA Padlock</A>.
//! \sa MaurerRandomnessTest() for random bit generators /// \sa MaurerRandomnessTest() for random bit generators
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
class PadlockRNG : public RandomNumberGenerator class PadlockRNG : public RandomNumberGenerator
{ {
public: public:
@ -54,51 +54,51 @@ public:
virtual ~PadlockRNG() {} virtual ~PadlockRNG() {}
//! \brief Construct a PadlockRNG generator /// \brief Construct a PadlockRNG generator
//! \param divisor the XSTORE divisor /// \param divisor the XSTORE divisor
//! \details Some VIA processors provide a Security Engine called Padlock. The Padlock /// \details Some VIA processors provide a Security Engine called Padlock. The Padlock
//! Security Engine provides AES, SHA and a RNG. The PadlockRNG class provides access /// Security Engine provides AES, SHA and a RNG. The PadlockRNG class provides access
//! to the RNG. /// to the RNG.
//! \details The VIA generator uses an 8 byte FIFO buffer for random numbers. The /// \details The VIA generator uses an 8 byte FIFO buffer for random numbers. The
//! generator can be configured to discard bits from the buffer to resist analysis. /// generator can be configured to discard bits from the buffer to resist analysis.
//! The <tt>divisor</tt> controls the number of bytes discarded. The formula for /// The <tt>divisor</tt> controls the number of bytes discarded. The formula for
//! the discard amount is <tt>2**divisor - 1</tt>. When <tt>divisor=0</tt> no bits /// the discard amount is <tt>2**divisor - 1</tt>. When <tt>divisor=0</tt> no bits
//! are discarded and the entire 8 byte buffer is read. If <tt>divisor=3</tt> then /// are discarded and the entire 8 byte buffer is read. If <tt>divisor=3</tt> then
//! 7 bytes are discarded and 1 byte is read. VIA SDK samples use <tt>divisor=1</tt>. /// 7 bytes are discarded and 1 byte is read. VIA SDK samples use <tt>divisor=1</tt>.
//! \details Cryptography Research, Inc (CRI) audited the Padlock Security Engine /// \details Cryptography Research, Inc (CRI) audited the Padlock Security Engine
//! in 2003. CRI provided recommendations to operate the generator for secure and /// in 2003. CRI provided recommendations to operate the generator for secure and
//! non-secure applications. Additionally, the Programmers SDK provided a different /// non-secure applications. Additionally, the Programmers SDK provided a different
//! configuration in the sample code. /// configuration in the sample code.
//! \details The audit report with recommendations is available on the Crypto++ wiki /// \details The audit report with recommendations is available on the Crypto++ wiki
//! at <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA Padlock</A>. /// at <A HREF="http://www.cryptopp.com/wiki/VIA_Padlock">VIA Padlock</A>.
//! \sa SetDivisor, GetDivisor /// \sa SetDivisor, GetDivisor
PadlockRNG(word32 divisor=1); PadlockRNG(word32 divisor=1);
//! \brief Generate random array of bytes /// \brief Generate random array of bytes
//! \param output the byte buffer /// \param output the byte buffer
//! \param size the length of the buffer, in bytes /// \param size the length of the buffer, in bytes
virtual void GenerateBlock(byte *output, size_t size); virtual void GenerateBlock(byte *output, size_t size);
//! \brief Generate and discard n bytes /// \brief Generate and discard n bytes
//! \param n the number of bytes to generate and discard /// \param n the number of bytes to generate and discard
//! \details the Padlock generator discards words, not bytes. If n is /// \details the Padlock generator discards words, not bytes. If n is
//! not a multiple of a 32-bit word, then it is rounded up to /// not a multiple of a 32-bit word, then it is rounded up to
//! that size. /// that size.
virtual void DiscardBytes(size_t n); virtual void DiscardBytes(size_t n);
//! \brief Update RNG state with additional unpredictable values /// \brief Update RNG state with additional unpredictable values
//! \param input unused /// \param input unused
//! \param length unused /// \param length unused
//! \details The operation is a nop for this generator. /// \details The operation is a nop for this generator.
virtual void IncorporateEntropy(const byte *input, size_t length) virtual void IncorporateEntropy(const byte *input, size_t length)
{ {
// Override to avoid the base class' throw. // Override to avoid the base class' throw.
CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length); CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
} }
//! \brief Set the XSTORE divisor /// \brief Set the XSTORE divisor
//! \param divisor the XSTORE divisor /// \param divisor the XSTORE divisor
//! \returns the old XSTORE divisor /// \returns the old XSTORE divisor
word32 SetDivisor(word32 divisor) word32 SetDivisor(word32 divisor)
{ {
word32 old = m_divisor; word32 old = m_divisor;
@ -106,15 +106,15 @@ public:
return old; return old;
} }
//! \brief Get the XSTORE divisor /// \brief Get the XSTORE divisor
//! \returns the current XSTORE divisor /// \returns the current XSTORE divisor
word32 GetDivisor() const word32 GetDivisor() const
{ {
return m_divisor; return m_divisor;
} }
//! \brief Get the MSR for the last operation /// \brief Get the MSR for the last operation
//! \returns the MSR for the last read operation /// \returns the MSR for the last read operation
word32 GetMSR() const word32 GetMSR() const
{ {
return m_msr; return m_msr;

View File

@ -1,7 +1,7 @@
// panama.h - originally written and placed in the public domain by Wei Dai // panama.h - originally written and placed in the public domain by Wei Dai
//! \file panama.h /// \file panama.h
//! \brief Classes for Panama hash and stream cipher /// \brief Classes for Panama hash and stream cipher
#ifndef CRYPTOPP_PANAMA_H #ifndef CRYPTOPP_PANAMA_H
#define CRYPTOPP_PANAMA_H #define CRYPTOPP_PANAMA_H
@ -33,9 +33,9 @@ protected:
}; };
namespace Weak { namespace Weak {
//! \class PanamaHash /// \class PanamaHash
//! \brief Panama hash /// \brief Panama hash
//! \sa <a href="http://www.weidai.com/scan-mirror/md.html#Panama">Panama Hash</a> /// \sa <a href="http://www.weidai.com/scan-mirror/md.html#Panama">Panama Hash</a>
template <class B = LittleEndian> template <class B = LittleEndian>
class PanamaHash : protected Panama<B>, public AlgorithmImpl<IteratedHash<word32, NativeByteOrder, 32>, PanamaHash<B> > class PanamaHash : protected Panama<B>, public AlgorithmImpl<IteratedHash<word32, NativeByteOrder, 32>, PanamaHash<B> >
{ {
@ -54,8 +54,8 @@ protected:
}; };
} }
//! \class HermeticHashFunctionMAC /// \class HermeticHashFunctionMAC
//! \brief MAC construction using a hermetic hash function /// \brief MAC construction using a hermetic hash function
template <class T_Hash, class T_Info = T_Hash> template <class T_Hash, class T_Info = T_Hash>
class HermeticHashFunctionMAC : public AlgorithmImpl<SimpleKeyingInterfaceImpl<TwoBases<MessageAuthenticationCode, VariableKeyLength<32, 0, INT_MAX> > >, T_Info> class HermeticHashFunctionMAC : public AlgorithmImpl<SimpleKeyingInterfaceImpl<TwoBases<MessageAuthenticationCode, VariableKeyLength<32, 0, INT_MAX> > >, T_Info>
{ {
@ -111,8 +111,8 @@ protected:
}; };
namespace Weak { namespace Weak {
//! \class PanamaMAC /// \class PanamaMAC
//! \brief Panama message authentication code /// \brief Panama message authentication code
template <class B = LittleEndian> template <class B = LittleEndian>
class PanamaMAC : public HermeticHashFunctionMAC<PanamaHash<B> > class PanamaMAC : public HermeticHashFunctionMAC<PanamaHash<B> >
{ {
@ -123,16 +123,16 @@ public:
}; };
} }
//! \class PanamaCipherInfo /// \class PanamaCipherInfo
//! \brief Panama stream cipher information /// \brief Panama stream cipher information
template <class B> template <class B>
struct PanamaCipherInfo : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 32> struct PanamaCipherInfo : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 32>
{ {
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return B::ToEnum() == BIG_ENDIAN_ORDER ? "Panama-BE" : "Panama-LE";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return B::ToEnum() == BIG_ENDIAN_ORDER ? "Panama-BE" : "Panama-LE";}
}; };
//! \class PanamaCipherPolicy /// \class PanamaCipherPolicy
//! \brief Panama stream cipher operation /// \brief Panama stream cipher operation
template <class B> template <class B>
class PanamaCipherPolicy : public AdditiveCipherConcretePolicy<word32, 8>, class PanamaCipherPolicy : public AdditiveCipherConcretePolicy<word32, 8>,
public PanamaCipherInfo<B>, public PanamaCipherInfo<B>,
@ -148,9 +148,9 @@ protected:
FixedSizeSecBlock<word32, 8> m_key; FixedSizeSecBlock<word32, 8> m_key;
}; };
//! \class PanamaCipher /// \class PanamaCipher
//! \brief Panama stream cipher /// \brief Panama stream cipher
//! \sa <a href="http://www.cryptolounge.org/wiki/PANAMA">Panama Stream Cipher</a> /// \sa <a href="http://www.cryptolounge.org/wiki/PANAMA">Panama Stream Cipher</a>
template <class B = LittleEndian> template <class B = LittleEndian>
struct PanamaCipher : public PanamaCipherInfo<B>, public SymmetricCipherDocumentation struct PanamaCipher : public PanamaCipherInfo<B>, public SymmetricCipherDocumentation
{ {

4
pch.h
View File

@ -1,7 +1,7 @@
// pch.h - originally written and placed in the public domain by Wei Dai // pch.h - originally written and placed in the public domain by Wei Dai
//! \headerfile pch.h /// \headerfile pch.h
//! \brief Precompiled header file /// \brief Precompiled header file
#ifndef CRYPTOPP_PCH_H #ifndef CRYPTOPP_PCH_H
#define CRYPTOPP_PCH_H #define CRYPTOPP_PCH_H

View File

@ -1,8 +1,8 @@
// pkcspad.h - originally written and placed in the public domain by Wei Dai // pkcspad.h - originally written and placed in the public domain by Wei Dai
//! \file pkcspad.h /// \file pkcspad.h
//! \brief Classes for PKCS padding schemes /// \brief Classes for PKCS padding schemes
//! \details PKCS#1 v1.5, v2.0 and P1363a allow MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, Tiger and RipeMd-160 to be instantiated. /// \details PKCS#1 v1.5, v2.0 and P1363a allow MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, Tiger and RipeMd-160 to be instantiated.
#ifndef CRYPTOPP_PKCSPAD_H #ifndef CRYPTOPP_PKCSPAD_H
#define CRYPTOPP_PKCSPAD_H #define CRYPTOPP_PKCSPAD_H
@ -16,9 +16,9 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class PKCS_EncryptionPaddingScheme /// \class PKCS_EncryptionPaddingScheme
//! \brief PKCS#1 v1.5 Encryption Padding Scheme /// \brief PKCS#1 v1.5 Encryption Padding Scheme
//! \sa <a href="http://www.weidai.com/scan-mirror/ca.html#cem_PKCS1-1.5">EME-PKCS1-v1_5</a> /// \sa <a href="http://www.weidai.com/scan-mirror/ca.html#cem_PKCS1-1.5">EME-PKCS1-v1_5</a>
class PKCS_EncryptionPaddingScheme : public PK_EncryptionMessageEncodingMethod class PKCS_EncryptionPaddingScheme : public PK_EncryptionMessageEncodingMethod
{ {
public: public:
@ -29,8 +29,8 @@ public:
DecodingResult Unpad(const byte *padded, size_t paddedLength, byte *raw, const NameValuePairs &parameters) const; DecodingResult Unpad(const byte *padded, size_t paddedLength, byte *raw, const NameValuePairs &parameters) const;
}; };
//! \class PKCS_DigestDecoration /// \class PKCS_DigestDecoration
//! \brief PKCS#1 decoration data structure /// \brief PKCS#1 decoration data structure
template <class H> class PKCS_DigestDecoration template <class H> class PKCS_DigestDecoration
{ {
public: public:
@ -78,9 +78,9 @@ template <class H>
const byte PKCS_DigestDecoration<H>::decoration[1] = {0x00}; const byte PKCS_DigestDecoration<H>::decoration[1] = {0x00};
#endif #endif
//! \class PKCS1v15_SignatureMessageEncodingMethod /// \class PKCS1v15_SignatureMessageEncodingMethod
//! \brief PKCS#1 v1.5 Signature Encoding Scheme /// \brief PKCS#1 v1.5 Signature Encoding Scheme
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PKCS1-1.5">EMSA-PKCS1-v1_5</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PKCS1-1.5">EMSA-PKCS1-v1_5</a>
class CRYPTOPP_DLL PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod class CRYPTOPP_DLL PKCS1v15_SignatureMessageEncodingMethod : public PK_DeterministicSignatureMessageEncodingMethod
{ {
public: public:
@ -106,8 +106,8 @@ public:
}; };
}; };
//! \brief PKCS #1 version 1.5, for use with RSAES and RSASS /// \brief PKCS #1 version 1.5, for use with RSAES and RSASS
//! \dontinclude pkcspad.h /// \dontinclude pkcspad.h
struct PKCS1v15 : public SignatureStandard, public EncryptionStandard struct PKCS1v15 : public SignatureStandard, public EncryptionStandard
{ {

View File

@ -1,45 +1,45 @@
// poly1305.h - written and placed in the public domain by Jeffrey Walton and Jean-Pierre Munch // poly1305.h - written and placed in the public domain by Jeffrey Walton and Jean-Pierre Munch
// Based on Andy Polyakov's Base-2^26 scalar multiplication implementation for OpenSSL. // Based on Andy Polyakov's Base-2^26 scalar multiplication implementation for OpenSSL.
//! \file poly1305.h /// \file poly1305.h
//! \brief Classes for Poly1305 message authentication code /// \brief Classes for Poly1305 message authentication code
//! \details Poly1305-AES is a state-of-the-art message-authentication code suitable for a wide /// \details Poly1305-AES is a state-of-the-art message-authentication code suitable for a wide
//! variety of applications. Poly1305-AES computes a 16-byte authenticator of a variable-length /// variety of applications. Poly1305-AES computes a 16-byte authenticator of a variable-length
//! message, using a 16-byte AES key, a 16-byte additional key, and a 16-byte nonce. /// message, using a 16-byte AES key, a 16-byte additional key, and a 16-byte nonce.
//! \details Each message must use a unique security context, which means either the key or nonce /// \details Each message must use a unique security context, which means either the key or nonce
//! must be changed after each message. It can be accomplished in one of two ways. First, you /// must be changed after each message. It can be accomplished in one of two ways. First, you
//! can create a new Poly1305 object with a key and nonce each time its needed. /// can create a new Poly1305 object with a key and nonce each time its needed.
//! <pre> SecByteBlock key(32), nonce(16); /// <pre> SecByteBlock key(32), nonce(16);
//! prng.GenerateBlock(key, key.size()); /// prng.GenerateBlock(key, key.size());
//! prng.GenerateBlock(nonce, nonce.size()); /// prng.GenerateBlock(nonce, nonce.size());
//! ///
//! Poly1305<AES> poly1305(key, key.size(), nonce, nonce.size()); /// Poly1305<AES> poly1305(key, key.size(), nonce, nonce.size());
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...);</pre> /// poly1305.Final(...);</pre>
//! ///
//! \details Second, you can create a Poly1305 object, reuse the key, and set a fresh nonce /// \details Second, you can create a Poly1305 object, reuse the key, and set a fresh nonce
//! for each message. The second and subsequent nonces can be generated directly using a /// for each message. The second and subsequent nonces can be generated directly using a
//! RandomNumberGenerator() derived class; or it can be generated using GetNextIV(). /// RandomNumberGenerator() derived class; or it can be generated using GetNextIV().
//! <pre> SecByteBlock key(32), nonce(16); /// <pre> SecByteBlock key(32), nonce(16);
//! prng.GenerateBlock(key, key.size()); /// prng.GenerateBlock(key, key.size());
//! prng.GenerateBlock(nonce, nonce.size()); /// prng.GenerateBlock(nonce, nonce.size());
//! ///
//! // First message /// // First message
//! Poly1305<AES> poly1305(key, key.size()); /// Poly1305<AES> poly1305(key, key.size());
//! poly1305.Resynchronize(nonce); /// poly1305.Resynchronize(nonce);
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...); /// poly1305.Final(...);
//! ///
//! // Second message /// // Second message
//! poly1305.GetNextIV(prng, nonce); /// poly1305.GetNextIV(prng, nonce);
//! poly1305.Resynchronize(nonce); /// poly1305.Resynchronize(nonce);
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...); /// poly1305.Final(...);
//! ...</pre> /// ...</pre>
//! \sa Daniel J. Bernstein <A HREF="http://cr.yp.to/mac/poly1305-20050329.pdf">The Poly1305-AES /// \sa Daniel J. Bernstein <A HREF="http://cr.yp.to/mac/poly1305-20050329.pdf">The Poly1305-AES
//! Message-Authentication Code (20050329)</A> and Andy Polyakov <A /// Message-Authentication Code (20050329)</A> and Andy Polyakov <A
//! HREF="http://www.openssl.org/blog/blog/2016/02/15/poly1305-revised/">Poly1305 Revised</A> /// HREF="http://www.openssl.org/blog/blog/2016/02/15/poly1305-revised/">Poly1305 Revised</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
#ifndef CRYPTOPP_POLY1305_H #ifndef CRYPTOPP_POLY1305_H
#define CRYPTOPP_POLY1305_H #define CRYPTOPP_POLY1305_H
@ -52,10 +52,10 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class Poly1305_Base /// \class Poly1305_Base
//! \brief Poly1305 message authentication code base class /// \brief Poly1305 message authentication code base class
//! \tparam T class derived from BlockCipherDocumentation with 16-byte key and 16-byte blocksize /// \tparam T class derived from BlockCipherDocumentation with 16-byte key and 16-byte blocksize
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T> template <class T>
class CRYPTOPP_NO_VTABLE Poly1305_Base : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 16>, public MessageAuthenticationCode class CRYPTOPP_NO_VTABLE Poly1305_Base : public FixedKeyLength<32, SimpleKeyingInterface::UNIQUE_IV, 16>, public MessageAuthenticationCode
{ {
@ -100,66 +100,66 @@ protected:
bool m_used; bool m_used;
}; };
//! \class Poly1305 /// \class Poly1305
//! \brief Poly1305 message authentication code /// \brief Poly1305 message authentication code
//! \tparam T class derived from BlockCipherDocumentation with 16-byte key and 16-byte blocksize /// \tparam T class derived from BlockCipherDocumentation with 16-byte key and 16-byte blocksize
//! \details Poly1305-AES is a state-of-the-art message-authentication code suitable for a wide /// \details Poly1305-AES is a state-of-the-art message-authentication code suitable for a wide
//! variety of applications. Poly1305-AES computes a 16-byte authenticator of a variable-length /// variety of applications. Poly1305-AES computes a 16-byte authenticator of a variable-length
//! message, using a 16-byte AES key, a 16-byte additional key, and a 16-byte nonce. /// message, using a 16-byte AES key, a 16-byte additional key, and a 16-byte nonce.
//! \details Each message must use a unique security context, which means either the key or nonce /// \details Each message must use a unique security context, which means either the key or nonce
//! must be changed after each message. It can be accomplished in one of two ways. First, you /// must be changed after each message. It can be accomplished in one of two ways. First, you
//! can create a new Poly1305 object with a key and nonce each time its needed. /// can create a new Poly1305 object with a key and nonce each time its needed.
//! <pre> SecByteBlock key(32), nonce(16); /// <pre> SecByteBlock key(32), nonce(16);
//! prng.GenerateBlock(key, key.size()); /// prng.GenerateBlock(key, key.size());
//! prng.GenerateBlock(nonce, nonce.size()); /// prng.GenerateBlock(nonce, nonce.size());
//! ///
//! Poly1305<AES> poly1305(key, key.size(), nonce, nonce.size()); /// Poly1305<AES> poly1305(key, key.size(), nonce, nonce.size());
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...);</pre> /// poly1305.Final(...);</pre>
//! ///
//! \details Second, you can create a Poly1305 object, reuse the key, and set a fresh nonce /// \details Second, you can create a Poly1305 object, reuse the key, and set a fresh nonce
//! for each message. The second and subsequent nonces can be generated directly using a /// for each message. The second and subsequent nonces can be generated directly using a
//! RandomNumberGenerator() derived class; or it can be generated using GetNextIV(). /// RandomNumberGenerator() derived class; or it can be generated using GetNextIV().
//! <pre> SecByteBlock key(32), nonce(16); /// <pre> SecByteBlock key(32), nonce(16);
//! prng.GenerateBlock(key, key.size()); /// prng.GenerateBlock(key, key.size());
//! prng.GenerateBlock(nonce, nonce.size()); /// prng.GenerateBlock(nonce, nonce.size());
//! ///
//! // First message /// // First message
//! Poly1305<AES> poly1305(key, key.size()); /// Poly1305<AES> poly1305(key, key.size());
//! poly1305.Resynchronize(nonce); /// poly1305.Resynchronize(nonce);
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...); /// poly1305.Final(...);
//! ///
//! // Second message /// // Second message
//! poly1305.GetNextIV(prng, nonce); /// poly1305.GetNextIV(prng, nonce);
//! poly1305.Resynchronize(nonce); /// poly1305.Resynchronize(nonce);
//! poly1305.Update(...); /// poly1305.Update(...);
//! poly1305.Final(...); /// poly1305.Final(...);
//! ...</pre> /// ...</pre>
//! \warning The Poly1305 class does not enforce a fresh nonce for each message. The source code /// \warning The Poly1305 class does not enforce a fresh nonce for each message. The source code
//! will assert in debug builds to alert of nonce reuse. No action is taken in release builds. /// will assert in debug builds to alert of nonce reuse. No action is taken in release builds.
//! \sa Daniel J. Bernstein <A HREF="http://cr.yp.to/mac/poly1305-20050329.pdf">The Poly1305-AES /// \sa Daniel J. Bernstein <A HREF="http://cr.yp.to/mac/poly1305-20050329.pdf">The Poly1305-AES
//! Message-Authentication Code (20050329)</A> and Andy Polyakov <A /// Message-Authentication Code (20050329)</A> and Andy Polyakov <A
//! HREF="http://www.openssl.org/blog/blog/2016/02/15/poly1305-revised/">Poly1305 Revised</A> /// HREF="http://www.openssl.org/blog/blog/2016/02/15/poly1305-revised/">Poly1305 Revised</A>
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T> template <class T>
class Poly1305 : public MessageAuthenticationCodeFinal<Poly1305_Base<T> > class Poly1305 : public MessageAuthenticationCodeFinal<Poly1305_Base<T> >
{ {
public: public:
CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH=Poly1305_Base<T>::DEFAULT_KEYLENGTH) CRYPTOPP_CONSTANT(DEFAULT_KEYLENGTH=Poly1305_Base<T>::DEFAULT_KEYLENGTH)
//! \brief Construct a Poly1305 /// \brief Construct a Poly1305
Poly1305() {} Poly1305() {}
//! \brief Construct a Poly1305 /// \brief Construct a Poly1305
//! \param key a byte array used to key the cipher /// \param key a byte array used to key the cipher
//! \param keyLength the size of the byte array, in bytes /// \param keyLength the size of the byte array, in bytes
//! \param nonce a byte array used to key the cipher /// \param nonce a byte array used to key the cipher
//! \param nonceLength the size of the byte array, in bytes /// \param nonceLength the size of the byte array, in bytes
//! \details key is the 32-byte key composed of the 16-byte AES key and the 16 additional key /// \details key is the 32-byte key composed of the 16-byte AES key and the 16 additional key
//! bytes used for <tt>r</tt>. /// bytes used for <tt>r</tt>.
//! \details Each message requires a unique security context. You can use GetNextIV() and /// \details Each message requires a unique security context. You can use GetNextIV() and
//! Resynchronize() to set a new nonce under a key for a message. /// Resynchronize() to set a new nonce under a key for a message.
Poly1305(const byte *key, size_t keyLength=DEFAULT_KEYLENGTH, const byte *nonce=NULLPTR, size_t nonceLength=0) Poly1305(const byte *key, size_t keyLength=DEFAULT_KEYLENGTH, const byte *nonce=NULLPTR, size_t nonceLength=0)
{this->SetKey(key, keyLength, MakeParameters(Name::IV(), ConstByteArrayParameter(nonce, nonceLength)));} {this->SetKey(key, keyLength, MakeParameters(Name::IV(), ConstByteArrayParameter(nonce, nonceLength)));}
}; };

View File

@ -1,8 +1,8 @@
// polynomi.h - originally written and placed in the public domain by Wei Dai // polynomi.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \headerfile polynomi.h /// \headerfile polynomi.h
//! \brief Classes for polynomial basis and operations /// \brief Classes for polynomial basis and operations
#ifndef CRYPTOPP_POLYNOMI_H #ifndef CRYPTOPP_POLYNOMI_H
@ -20,21 +20,21 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! represents single-variable polynomials over arbitrary rings /// represents single-variable polynomials over arbitrary rings
/*! \nosubgrouping */ /*! \nosubgrouping */
template <class T> class PolynomialOver template <class T> class PolynomialOver
{ {
public: public:
//! \name ENUMS, EXCEPTIONS, and TYPEDEFS /// \name ENUMS, EXCEPTIONS, and TYPEDEFS
//@{ //@{
//! division by zero exception /// division by zero exception
class DivideByZero : public Exception class DivideByZero : public Exception
{ {
public: public:
DivideByZero() : Exception(OTHER_ERROR, "PolynomialOver<T>: division by zero") {} DivideByZero() : Exception(OTHER_ERROR, "PolynomialOver<T>: division by zero") {}
}; };
//! specify the distribution for randomization functions /// specify the distribution for randomization functions
class RandomizationParameter class RandomizationParameter
{ {
public: public:
@ -51,74 +51,74 @@ public:
typedef typename T::Element CoefficientType; typedef typename T::Element CoefficientType;
//@} //@}
//! \name CREATORS /// \name CREATORS
//@{ //@{
//! creates the zero polynomial /// creates the zero polynomial
PolynomialOver() {} PolynomialOver() {}
//! ///
PolynomialOver(const Ring &ring, unsigned int count) PolynomialOver(const Ring &ring, unsigned int count)
: m_coefficients((size_t)count, ring.Identity()) {} : m_coefficients((size_t)count, ring.Identity()) {}
//! copy constructor /// copy constructor
PolynomialOver(const PolynomialOver<Ring> &t) PolynomialOver(const PolynomialOver<Ring> &t)
: m_coefficients(t.m_coefficients.size()) {*this = t;} : m_coefficients(t.m_coefficients.size()) {*this = t;}
//! construct constant polynomial /// construct constant polynomial
PolynomialOver(const CoefficientType &element) PolynomialOver(const CoefficientType &element)
: m_coefficients(1, element) {} : m_coefficients(1, element) {}
//! construct polynomial with specified coefficients, starting from coefficient of x^0 /// construct polynomial with specified coefficients, starting from coefficient of x^0
template <typename Iterator> PolynomialOver(Iterator begin, Iterator end) template <typename Iterator> PolynomialOver(Iterator begin, Iterator end)
: m_coefficients(begin, end) {} : m_coefficients(begin, end) {}
//! convert from string /// convert from string
PolynomialOver(const char *str, const Ring &ring) {FromStr(str, ring);} PolynomialOver(const char *str, const Ring &ring) {FromStr(str, ring);}
//! convert from big-endian byte array /// convert from big-endian byte array
PolynomialOver(const byte *encodedPolynomialOver, unsigned int byteCount); PolynomialOver(const byte *encodedPolynomialOver, unsigned int byteCount);
//! convert from Basic Encoding Rules encoded byte array /// convert from Basic Encoding Rules encoded byte array
explicit PolynomialOver(const byte *BEREncodedPolynomialOver); explicit PolynomialOver(const byte *BEREncodedPolynomialOver);
//! convert from BER encoded byte array stored in a BufferedTransformation object /// convert from BER encoded byte array stored in a BufferedTransformation object
explicit PolynomialOver(BufferedTransformation &bt); explicit PolynomialOver(BufferedTransformation &bt);
//! create a random PolynomialOver<T> /// create a random PolynomialOver<T>
PolynomialOver(RandomNumberGenerator &rng, const RandomizationParameter &parameter, const Ring &ring) PolynomialOver(RandomNumberGenerator &rng, const RandomizationParameter &parameter, const Ring &ring)
{Randomize(rng, parameter, ring);} {Randomize(rng, parameter, ring);}
//@} //@}
//! \name ACCESSORS /// \name ACCESSORS
//@{ //@{
//! the zero polynomial will return a degree of -1 /// the zero polynomial will return a degree of -1
int Degree(const Ring &ring) const {return int(CoefficientCount(ring))-1;} int Degree(const Ring &ring) const {return int(CoefficientCount(ring))-1;}
//! ///
unsigned int CoefficientCount(const Ring &ring) const; unsigned int CoefficientCount(const Ring &ring) const;
//! return coefficient for x^i /// return coefficient for x^i
CoefficientType GetCoefficient(unsigned int i, const Ring &ring) const; CoefficientType GetCoefficient(unsigned int i, const Ring &ring) const;
//@} //@}
//! \name MANIPULATORS /// \name MANIPULATORS
//@{ //@{
//! ///
PolynomialOver<Ring>& operator=(const PolynomialOver<Ring>& t); PolynomialOver<Ring>& operator=(const PolynomialOver<Ring>& t);
//! ///
void Randomize(RandomNumberGenerator &rng, const RandomizationParameter &parameter, const Ring &ring); void Randomize(RandomNumberGenerator &rng, const RandomizationParameter &parameter, const Ring &ring);
//! set the coefficient for x^i to value /// set the coefficient for x^i to value
void SetCoefficient(unsigned int i, const CoefficientType &value, const Ring &ring); void SetCoefficient(unsigned int i, const CoefficientType &value, const Ring &ring);
//! ///
void Negate(const Ring &ring); void Negate(const Ring &ring);
//! ///
void swap(PolynomialOver<Ring> &t); void swap(PolynomialOver<Ring> &t);
//@} //@}
//! \name BASIC ARITHMETIC ON POLYNOMIALS /// \name BASIC ARITHMETIC ON POLYNOMIALS
//@{ //@{
bool Equals(const PolynomialOver<Ring> &t, const Ring &ring) const; bool Equals(const PolynomialOver<Ring> &t, const Ring &ring) const;
bool IsZero(const Ring &ring) const {return CoefficientCount(ring)==0;} bool IsZero(const Ring &ring) const {return CoefficientCount(ring)==0;}
@ -136,9 +136,9 @@ public:
PolynomialOver<Ring>& Accumulate(const PolynomialOver<Ring>& t, const Ring &ring); PolynomialOver<Ring>& Accumulate(const PolynomialOver<Ring>& t, const Ring &ring);
PolynomialOver<Ring>& Reduce(const PolynomialOver<Ring>& t, const Ring &ring); PolynomialOver<Ring>& Reduce(const PolynomialOver<Ring>& t, const Ring &ring);
//! ///
PolynomialOver<Ring> Doubled(const Ring &ring) const {return Plus(*this, ring);} PolynomialOver<Ring> Doubled(const Ring &ring) const {return Plus(*this, ring);}
//! ///
PolynomialOver<Ring> Squared(const Ring &ring) const {return Times(*this, ring);} PolynomialOver<Ring> Squared(const Ring &ring) const {return Times(*this, ring);}
CoefficientType EvaluateAt(const CoefficientType &x, const Ring &ring) const; CoefficientType EvaluateAt(const CoefficientType &x, const Ring &ring) const;
@ -146,11 +146,11 @@ public:
PolynomialOver<Ring>& ShiftLeft(unsigned int n, const Ring &ring); PolynomialOver<Ring>& ShiftLeft(unsigned int n, const Ring &ring);
PolynomialOver<Ring>& ShiftRight(unsigned int n, const Ring &ring); PolynomialOver<Ring>& ShiftRight(unsigned int n, const Ring &ring);
//! calculate r and q such that (a == d*q + r) && (0 <= degree of r < degree of d) /// calculate r and q such that (a == d*q + r) && (0 <= degree of r < degree of d)
static void Divide(PolynomialOver<Ring> &r, PolynomialOver<Ring> &q, const PolynomialOver<Ring> &a, const PolynomialOver<Ring> &d, const Ring &ring); static void Divide(PolynomialOver<Ring> &r, PolynomialOver<Ring> &q, const PolynomialOver<Ring> &a, const PolynomialOver<Ring> &d, const Ring &ring);
//@} //@}
//! \name INPUT/OUTPUT /// \name INPUT/OUTPUT
//@{ //@{
std::istream& Input(std::istream &in, const Ring &ring); std::istream& Input(std::istream &in, const Ring &ring);
std::ostream& Output(std::ostream &out, const Ring &ring) const; std::ostream& Output(std::ostream &out, const Ring &ring) const;
@ -162,7 +162,7 @@ private:
std::vector<CoefficientType> m_coefficients; std::vector<CoefficientType> m_coefficients;
}; };
//! Polynomials over a fixed ring /// Polynomials over a fixed ring
/*! Having a fixed ring allows overloaded operators */ /*! Having a fixed ring allows overloaded operators */
template <class T, int instance> class PolynomialOverFixedRing : private PolynomialOver<T> template <class T, int instance> class PolynomialOverFixedRing : private PolynomialOver<T>
{ {
@ -175,129 +175,129 @@ public:
typedef typename B::DivideByZero DivideByZero; typedef typename B::DivideByZero DivideByZero;
typedef typename B::RandomizationParameter RandomizationParameter; typedef typename B::RandomizationParameter RandomizationParameter;
//! \name CREATORS /// \name CREATORS
//@{ //@{
//! creates the zero polynomial /// creates the zero polynomial
PolynomialOverFixedRing(unsigned int count = 0) : B(ms_fixedRing, count) {} PolynomialOverFixedRing(unsigned int count = 0) : B(ms_fixedRing, count) {}
//! copy constructor /// copy constructor
PolynomialOverFixedRing(const ThisType &t) : B(t) {} PolynomialOverFixedRing(const ThisType &t) : B(t) {}
explicit PolynomialOverFixedRing(const B &t) : B(t) {} explicit PolynomialOverFixedRing(const B &t) : B(t) {}
//! construct constant polynomial /// construct constant polynomial
PolynomialOverFixedRing(const CoefficientType &element) : B(element) {} PolynomialOverFixedRing(const CoefficientType &element) : B(element) {}
//! construct polynomial with specified coefficients, starting from coefficient of x^0 /// construct polynomial with specified coefficients, starting from coefficient of x^0
template <typename Iterator> PolynomialOverFixedRing(Iterator first, Iterator last) template <typename Iterator> PolynomialOverFixedRing(Iterator first, Iterator last)
: B(first, last) {} : B(first, last) {}
//! convert from string /// convert from string
explicit PolynomialOverFixedRing(const char *str) : B(str, ms_fixedRing) {} explicit PolynomialOverFixedRing(const char *str) : B(str, ms_fixedRing) {}
//! convert from big-endian byte array /// convert from big-endian byte array
PolynomialOverFixedRing(const byte *encodedPoly, unsigned int byteCount) : B(encodedPoly, byteCount) {} PolynomialOverFixedRing(const byte *encodedPoly, unsigned int byteCount) : B(encodedPoly, byteCount) {}
//! convert from Basic Encoding Rules encoded byte array /// convert from Basic Encoding Rules encoded byte array
explicit PolynomialOverFixedRing(const byte *BEREncodedPoly) : B(BEREncodedPoly) {} explicit PolynomialOverFixedRing(const byte *BEREncodedPoly) : B(BEREncodedPoly) {}
//! convert from BER encoded byte array stored in a BufferedTransformation object /// convert from BER encoded byte array stored in a BufferedTransformation object
explicit PolynomialOverFixedRing(BufferedTransformation &bt) : B(bt) {} explicit PolynomialOverFixedRing(BufferedTransformation &bt) : B(bt) {}
//! create a random PolynomialOverFixedRing /// create a random PolynomialOverFixedRing
PolynomialOverFixedRing(RandomNumberGenerator &rng, const RandomizationParameter &parameter) : B(rng, parameter, ms_fixedRing) {} PolynomialOverFixedRing(RandomNumberGenerator &rng, const RandomizationParameter &parameter) : B(rng, parameter, ms_fixedRing) {}
static const ThisType &Zero(); static const ThisType &Zero();
static const ThisType &One(); static const ThisType &One();
//@} //@}
//! \name ACCESSORS /// \name ACCESSORS
//@{ //@{
//! the zero polynomial will return a degree of -1 /// the zero polynomial will return a degree of -1
int Degree() const {return B::Degree(ms_fixedRing);} int Degree() const {return B::Degree(ms_fixedRing);}
//! degree + 1 /// degree + 1
unsigned int CoefficientCount() const {return B::CoefficientCount(ms_fixedRing);} unsigned int CoefficientCount() const {return B::CoefficientCount(ms_fixedRing);}
//! return coefficient for x^i /// return coefficient for x^i
CoefficientType GetCoefficient(unsigned int i) const {return B::GetCoefficient(i, ms_fixedRing);} CoefficientType GetCoefficient(unsigned int i) const {return B::GetCoefficient(i, ms_fixedRing);}
//! return coefficient for x^i /// return coefficient for x^i
CoefficientType operator[](unsigned int i) const {return B::GetCoefficient(i, ms_fixedRing);} CoefficientType operator[](unsigned int i) const {return B::GetCoefficient(i, ms_fixedRing);}
//@} //@}
//! \name MANIPULATORS /// \name MANIPULATORS
//@{ //@{
//! ///
ThisType& operator=(const ThisType& t) {B::operator=(t); return *this;} ThisType& operator=(const ThisType& t) {B::operator=(t); return *this;}
//! ///
ThisType& operator+=(const ThisType& t) {Accumulate(t, ms_fixedRing); return *this;} ThisType& operator+=(const ThisType& t) {Accumulate(t, ms_fixedRing); return *this;}
//! ///
ThisType& operator-=(const ThisType& t) {Reduce(t, ms_fixedRing); return *this;} ThisType& operator-=(const ThisType& t) {Reduce(t, ms_fixedRing); return *this;}
//! ///
ThisType& operator*=(const ThisType& t) {return *this = *this*t;} ThisType& operator*=(const ThisType& t) {return *this = *this*t;}
//! ///
ThisType& operator/=(const ThisType& t) {return *this = *this/t;} ThisType& operator/=(const ThisType& t) {return *this = *this/t;}
//! ///
ThisType& operator%=(const ThisType& t) {return *this = *this%t;} ThisType& operator%=(const ThisType& t) {return *this = *this%t;}
//! ///
ThisType& operator<<=(unsigned int n) {ShiftLeft(n, ms_fixedRing); return *this;} ThisType& operator<<=(unsigned int n) {ShiftLeft(n, ms_fixedRing); return *this;}
//! ///
ThisType& operator>>=(unsigned int n) {ShiftRight(n, ms_fixedRing); return *this;} ThisType& operator>>=(unsigned int n) {ShiftRight(n, ms_fixedRing); return *this;}
//! set the coefficient for x^i to value /// set the coefficient for x^i to value
void SetCoefficient(unsigned int i, const CoefficientType &value) {B::SetCoefficient(i, value, ms_fixedRing);} void SetCoefficient(unsigned int i, const CoefficientType &value) {B::SetCoefficient(i, value, ms_fixedRing);}
//! ///
void Randomize(RandomNumberGenerator &rng, const RandomizationParameter &parameter) {B::Randomize(rng, parameter, ms_fixedRing);} void Randomize(RandomNumberGenerator &rng, const RandomizationParameter &parameter) {B::Randomize(rng, parameter, ms_fixedRing);}
//! ///
void Negate() {B::Negate(ms_fixedRing);} void Negate() {B::Negate(ms_fixedRing);}
void swap(ThisType &t) {B::swap(t);} void swap(ThisType &t) {B::swap(t);}
//@} //@}
//! \name UNARY OPERATORS /// \name UNARY OPERATORS
//@{ //@{
//! ///
bool operator!() const {return CoefficientCount()==0;} bool operator!() const {return CoefficientCount()==0;}
//! ///
ThisType operator+() const {return *this;} ThisType operator+() const {return *this;}
//! ///
ThisType operator-() const {return ThisType(Inverse(ms_fixedRing));} ThisType operator-() const {return ThisType(Inverse(ms_fixedRing));}
//@} //@}
//! \name BINARY OPERATORS /// \name BINARY OPERATORS
//@{ //@{
//! ///
friend ThisType operator>>(ThisType a, unsigned int n) {return ThisType(a>>=n);} friend ThisType operator>>(ThisType a, unsigned int n) {return ThisType(a>>=n);}
//! ///
friend ThisType operator<<(ThisType a, unsigned int n) {return ThisType(a<<=n);} friend ThisType operator<<(ThisType a, unsigned int n) {return ThisType(a<<=n);}
//@} //@}
//! \name OTHER ARITHMETIC FUNCTIONS /// \name OTHER ARITHMETIC FUNCTIONS
//@{ //@{
//! ///
ThisType MultiplicativeInverse() const {return ThisType(B::MultiplicativeInverse(ms_fixedRing));} ThisType MultiplicativeInverse() const {return ThisType(B::MultiplicativeInverse(ms_fixedRing));}
//! ///
bool IsUnit() const {return B::IsUnit(ms_fixedRing);} bool IsUnit() const {return B::IsUnit(ms_fixedRing);}
//! ///
ThisType Doubled() const {return ThisType(B::Doubled(ms_fixedRing));} ThisType Doubled() const {return ThisType(B::Doubled(ms_fixedRing));}
//! ///
ThisType Squared() const {return ThisType(B::Squared(ms_fixedRing));} ThisType Squared() const {return ThisType(B::Squared(ms_fixedRing));}
CoefficientType EvaluateAt(const CoefficientType &x) const {return B::EvaluateAt(x, ms_fixedRing);} CoefficientType EvaluateAt(const CoefficientType &x) const {return B::EvaluateAt(x, ms_fixedRing);}
//! calculate r and q such that (a == d*q + r) && (0 <= r < abs(d)) /// calculate r and q such that (a == d*q + r) && (0 <= r < abs(d))
static void Divide(ThisType &r, ThisType &q, const ThisType &a, const ThisType &d) static void Divide(ThisType &r, ThisType &q, const ThisType &a, const ThisType &d)
{B::Divide(r, q, a, d, ms_fixedRing);} {B::Divide(r, q, a, d, ms_fixedRing);}
//@} //@}
//! \name INPUT/OUTPUT /// \name INPUT/OUTPUT
//@{ //@{
//! ///
friend std::istream& operator>>(std::istream& in, ThisType &a) friend std::istream& operator>>(std::istream& in, ThisType &a)
{return a.Input(in, ms_fixedRing);} {return a.Input(in, ms_fixedRing);}
//! ///
friend std::ostream& operator<<(std::ostream& out, const ThisType &a) friend std::ostream& operator<<(std::ostream& out, const ThisType &a)
{return a.Output(out, ms_fixedRing);} {return a.Output(out, ms_fixedRing);}
//@} //@}
@ -314,7 +314,7 @@ private:
static const Ring ms_fixedRing; static const Ring ms_fixedRing;
}; };
//! Ring of polynomials over another ring /// Ring of polynomials over another ring
template <class T> class RingOfPolynomialsOver : public AbstractEuclideanDomain<PolynomialOver<T> > template <class T> class RingOfPolynomialsOver : public AbstractEuclideanDomain<PolynomialOver<T> >
{ {
public: public:
@ -404,49 +404,49 @@ void PrepareBulkPolynomialInterpolationAt(const Ring &ring, Element *v, const El
template <class Ring, class Element> template <class Ring, class Element>
Element BulkPolynomialInterpolateAt(const Ring &ring, const Element y[], const Element v[], unsigned int n); Element BulkPolynomialInterpolateAt(const Ring &ring, const Element y[], const Element v[], unsigned int n);
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator==(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator==(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return a.Equals(b, a.ms_fixedRing);} {return a.Equals(b, a.ms_fixedRing);}
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator!=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator!=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return !(a==b);} {return !(a==b);}
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator> (const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator> (const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return a.Degree() > b.Degree();} {return a.Degree() > b.Degree();}
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator>=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator>=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return a.Degree() >= b.Degree();} {return a.Degree() >= b.Degree();}
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator< (const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator< (const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return a.Degree() < b.Degree();} {return a.Degree() < b.Degree();}
//! ///
template <class T, int instance> template <class T, int instance>
inline bool operator<=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline bool operator<=(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return a.Degree() <= b.Degree();} {return a.Degree() <= b.Degree();}
//! ///
template <class T, int instance> template <class T, int instance>
inline CryptoPP::PolynomialOverFixedRing<T, instance> operator+(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline CryptoPP::PolynomialOverFixedRing<T, instance> operator+(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Plus(b, a.ms_fixedRing));} {return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Plus(b, a.ms_fixedRing));}
//! ///
template <class T, int instance> template <class T, int instance>
inline CryptoPP::PolynomialOverFixedRing<T, instance> operator-(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline CryptoPP::PolynomialOverFixedRing<T, instance> operator-(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Minus(b, a.ms_fixedRing));} {return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Minus(b, a.ms_fixedRing));}
//! ///
template <class T, int instance> template <class T, int instance>
inline CryptoPP::PolynomialOverFixedRing<T, instance> operator*(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline CryptoPP::PolynomialOverFixedRing<T, instance> operator*(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Times(b, a.ms_fixedRing));} {return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Times(b, a.ms_fixedRing));}
//! ///
template <class T, int instance> template <class T, int instance>
inline CryptoPP::PolynomialOverFixedRing<T, instance> operator/(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline CryptoPP::PolynomialOverFixedRing<T, instance> operator/(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return CryptoPP::PolynomialOverFixedRing<T, instance>(a.DividedBy(b, a.ms_fixedRing));} {return CryptoPP::PolynomialOverFixedRing<T, instance>(a.DividedBy(b, a.ms_fixedRing));}
//! ///
template <class T, int instance> template <class T, int instance>
inline CryptoPP::PolynomialOverFixedRing<T, instance> operator%(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b) inline CryptoPP::PolynomialOverFixedRing<T, instance> operator%(const CryptoPP::PolynomialOverFixedRing<T, instance> &a, const CryptoPP::PolynomialOverFixedRing<T, instance> &b)
{return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Modulo(b, a.ms_fixedRing));} {return CryptoPP::PolynomialOverFixedRing<T, instance>(a.Modulo(b, a.ms_fixedRing));}

View File

@ -1,17 +1,17 @@
// ppc-crypto.h - written and placed in public domain by Jeffrey Walton // ppc-crypto.h - written and placed in public domain by Jeffrey Walton
//! \file ppc-crypto.h /// \file ppc-crypto.h
//! \brief Support functions for PowerPC and Power8 vector operations /// \brief Support functions for PowerPC and Power8 vector operations
//! \details This header provides an agnostic interface into GCC and /// \details This header provides an agnostic interface into GCC and
//! IBM XL C/C++ compilers modulo their different built-in functions /// IBM XL C/C++ compilers modulo their different built-in functions
//! for accessing vector intructions. /// for accessing vector intructions.
//! \details The abstractions are necesssary to support back to GCC 4.8. /// \details The abstractions are necesssary to support back to GCC 4.8.
//! GCC 4.8 and 4.9 are still popular, and they are the default /// GCC 4.8 and 4.9 are still popular, and they are the default
//! compiler for GCC112, GCC118 and others on the compile farm. Older /// compiler for GCC112, GCC118 and others on the compile farm. Older
//! IBM XL C/C++ compilers also experience it due to lack of /// IBM XL C/C++ compilers also experience it due to lack of
//! <tt>vec_xl_be</tt> support on some platforms. Modern compilers /// <tt>vec_xl_be</tt> support on some platforms. Modern compilers
//! provide best support and don't need many of the little hacks below. /// provide best support and don't need many of the little hacks below.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
#ifndef CRYPTOPP_PPC_CRYPTO_H #ifndef CRYPTOPP_PPC_CRYPTO_H
#define CRYPTOPP_PPC_CRYPTO_H #define CRYPTOPP_PPC_CRYPTO_H
@ -41,19 +41,19 @@ typedef uint64x2_p8 VectorType;
#endif #endif
#if defined(CRYPTOPP_DOXYGEN_PROCESSING) #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
//! \brief Default vector typedef /// \brief Default vector typedef
//! \details IBM XL C/C++ provides equally good support for all vector types, /// \details IBM XL C/C++ provides equally good support for all vector types,
//! including <tt>uint8x16_p8</tt>. GCC provides good support for /// including <tt>uint8x16_p8</tt>. GCC provides good support for
//! <tt>uint64x2_p8</tt>. <tt>VectorType</tt> is typedef'd accordingly to /// <tt>uint64x2_p8</tt>. <tt>VectorType</tt> is typedef'd accordingly to
//! minimize casting to and from buit-in function calls. /// minimize casting to and from buit-in function calls.
# define VectorType ... # define VectorType ...
#endif #endif
//! \brief Reverse a 16-byte array /// \brief Reverse a 16-byte array
//! \param src the byte array /// \param src the byte array
//! \details ReverseByteArrayLE reverses a 16-byte array on a little endian /// \details ReverseByteArrayLE reverses a 16-byte array on a little endian
//! system. It does nothing on a big endian system. /// system. It does nothing on a big endian system.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline void ReverseByteArrayLE(byte src[16]) inline void ReverseByteArrayLE(byte src[16])
{ {
#if defined(CRYPTOPP_XLC_VERSION) && defined(CRYPTOPP_LITTLE_ENDIAN) #if defined(CRYPTOPP_XLC_VERSION) && defined(CRYPTOPP_LITTLE_ENDIAN)
@ -65,12 +65,12 @@ inline void ReverseByteArrayLE(byte src[16])
#endif #endif
} }
//! \brief Reverse a vector /// \brief Reverse a vector
//! \tparam T vector type /// \tparam T vector type
//! \param src the vector /// \param src the vector
//! \details Reverse() endian swaps the bytes in a vector /// \details Reverse() endian swaps the bytes in a vector
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T> template <class T>
inline T Reverse(const T& src) inline T Reverse(const T& src)
{ {
@ -79,13 +79,13 @@ inline T Reverse(const T& src)
return vec_perm(src, zero, mask); return vec_perm(src, zero, mask);
} }
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \details Loads a vector in big endian format from a byte array. /// \details Loads a vector in big endian format from a byte array.
//! VectorLoadBE will swap endianess on little endian systems. /// VectorLoadBE will swap endianess on little endian systems.
//! \note VectorLoadBE() does not require an aligned array. /// \note VectorLoadBE() does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoadBE(const uint8_t src[16]) inline VectorType VectorLoadBE(const uint8_t src[16])
{ {
#if defined(CRYPTOPP_XLC_VERSION) #if defined(CRYPTOPP_XLC_VERSION)
@ -99,14 +99,14 @@ inline VectorType VectorLoadBE(const uint8_t src[16])
#endif #endif
} }
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \param off offset into the src byte array /// \param off offset into the src byte array
//! \details Loads a vector in big endian format from a byte array. /// \details Loads a vector in big endian format from a byte array.
//! VectorLoadBE will swap endianess on little endian systems. /// VectorLoadBE will swap endianess on little endian systems.
//! \note VectorLoadBE does not require an aligned array. /// \note VectorLoadBE does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoadBE(int off, const uint8_t src[16]) inline VectorType VectorLoadBE(int off, const uint8_t src[16])
{ {
#if defined(CRYPTOPP_XLC_VERSION) #if defined(CRYPTOPP_XLC_VERSION)
@ -122,38 +122,38 @@ inline VectorType VectorLoadBE(int off, const uint8_t src[16])
////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \details Loads a vector in big endian format from a byte array. /// \details Loads a vector in big endian format from a byte array.
//! VectorLoad will swap endianess on little endian systems. /// VectorLoad will swap endianess on little endian systems.
//! \note VectorLoad does not require an aligned array. /// \note VectorLoad does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoad(const byte src[16]) inline VectorType VectorLoad(const byte src[16])
{ {
return (VectorType)VectorLoadBE((uint8_t*)src); return (VectorType)VectorLoadBE((uint8_t*)src);
} }
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \param off offset into the src byte array /// \param off offset into the src byte array
//! \details Loads a vector in big endian format from a byte array. /// \details Loads a vector in big endian format from a byte array.
//! VectorLoad will swap endianess on little endian systems. /// VectorLoad will swap endianess on little endian systems.
//! \note VectorLoad does not require an aligned array. /// \note VectorLoad does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoad(int off, const byte src[16]) inline VectorType VectorLoad(int off, const byte src[16])
{ {
return (VectorType)VectorLoadBE(off, (uint8_t*)src); return (VectorType)VectorLoadBE(off, (uint8_t*)src);
} }
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \details Loads a vector from a byte array. /// \details Loads a vector from a byte array.
//! VectorLoadKey does not swap endianess on little endian systems. /// VectorLoadKey does not swap endianess on little endian systems.
//! \note VectorLoadKey does not require an aligned array. /// \note VectorLoadKey does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoadKey(const byte src[16]) inline VectorType VectorLoadKey(const byte src[16])
{ {
#if defined(CRYPTOPP_XLC_VERSION) #if defined(CRYPTOPP_XLC_VERSION)
@ -163,13 +163,13 @@ inline VectorType VectorLoadKey(const byte src[16])
#endif #endif
} }
//! \brief Loads a vector from a 32-bit word array /// \brief Loads a vector from a 32-bit word array
//! \param src the 32-bit word array /// \param src the 32-bit word array
//! \details Loads a vector from a 32-bit word array. /// \details Loads a vector from a 32-bit word array.
//! VectorLoadKey does not swap endianess on little endian systems. /// VectorLoadKey does not swap endianess on little endian systems.
//! \note VectorLoadKey does not require an aligned array. /// \note VectorLoadKey does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoadKey(const word32 src[4]) inline VectorType VectorLoadKey(const word32 src[4])
{ {
#if defined(CRYPTOPP_XLC_VERSION) #if defined(CRYPTOPP_XLC_VERSION)
@ -179,14 +179,14 @@ inline VectorType VectorLoadKey(const word32 src[4])
#endif #endif
} }
//! \brief Loads a vector from a byte array /// \brief Loads a vector from a byte array
//! \param src the byte array /// \param src the byte array
//! \param off offset into the src byte array /// \param off offset into the src byte array
//! \details Loads a vector from a byte array. /// \details Loads a vector from a byte array.
//! VectorLoadKey does not swap endianess on little endian systems. /// VectorLoadKey does not swap endianess on little endian systems.
//! \note VectorLoadKey does not require an aligned array. /// \note VectorLoadKey does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
inline VectorType VectorLoadKey(int off, const byte src[16]) inline VectorType VectorLoadKey(int off, const byte src[16])
{ {
#if defined(CRYPTOPP_XLC_VERSION) #if defined(CRYPTOPP_XLC_VERSION)
@ -196,15 +196,15 @@ inline VectorType VectorLoadKey(int off, const byte src[16])
#endif #endif
} }
//! \brief Stores a vector to a byte array /// \brief Stores a vector to a byte array
//! \tparam T vector type /// \tparam T vector type
//! \param src the vector /// \param src the vector
//! \param dest the byte array /// \param dest the byte array
//! \details Stores a vector in big endian format to a byte array. /// \details Stores a vector in big endian format to a byte array.
//! VectorStoreBE will swap endianess on little endian systems. /// VectorStoreBE will swap endianess on little endian systems.
//! \note VectorStoreBE does not require an aligned array. /// \note VectorStoreBE does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T> template <class T>
inline void VectorStoreBE(const T& src, uint8_t dest[16]) inline void VectorStoreBE(const T& src, uint8_t dest[16])
{ {
@ -218,16 +218,16 @@ inline void VectorStoreBE(const T& src, uint8_t dest[16])
# endif # endif
#endif #endif
} }
//! \brief Stores a vector to a byte array /// \brief Stores a vector to a byte array
//! \tparam T vector type /// \tparam T vector type
//! \param src the vector /// \param src the vector
//! \param off offset into the dest byte array /// \param off offset into the dest byte array
//! \param dest the byte array /// \param dest the byte array
//! \details Stores a vector in big endian format to a byte array. /// \details Stores a vector in big endian format to a byte array.
//! VectorStoreBE will swap endianess on little endian systems. /// VectorStoreBE will swap endianess on little endian systems.
//! \note VectorStoreBE does not require an aligned array. /// \note VectorStoreBE does not require an aligned array.
//! \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey() /// \sa Reverse(), VectorLoadBE(), VectorLoad(), VectorLoadKey()
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T> template <class T>
inline void VectorStoreBE(const T& src, int off, uint8_t dest[16]) inline void VectorStoreBE(const T& src, int off, uint8_t dest[16])
{ {
@ -242,14 +242,14 @@ inline void VectorStoreBE(const T& src, int off, uint8_t dest[16])
#endif #endif
} }
//! \brief Stores a vector to a byte array /// \brief Stores a vector to a byte array
//! \tparam T vector type /// \tparam T vector type
//! \param src the vector /// \param src the vector
//! \param dest the byte array /// \param dest the byte array
//! \details Stores a vector in big endian format to a byte array. /// \details Stores a vector in big endian format to a byte array.
//! VectorStore will swap endianess on little endian systems. /// VectorStore will swap endianess on little endian systems.
//! \note VectorStore does not require an aligned array. /// \note VectorStore does not require an aligned array.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template<class T> template<class T>
inline void VectorStore(const T& src, byte dest[16]) inline void VectorStore(const T& src, byte dest[16])
{ {
@ -265,15 +265,15 @@ inline void VectorStore(const T& src, byte dest[16])
#endif #endif
} }
//! \brief Stores a vector to a byte array /// \brief Stores a vector to a byte array
//! \tparam T vector type /// \tparam T vector type
//! \param src the vector /// \param src the vector
//! \param off offset into the dest byte array /// \param off offset into the dest byte array
//! \param dest the byte array /// \param dest the byte array
//! \details Stores a vector in big endian format to a byte array. /// \details Stores a vector in big endian format to a byte array.
//! VectorStore will swap endianess on little endian systems. /// VectorStore will swap endianess on little endian systems.
//! \note VectorStore does not require an aligned array. /// \note VectorStore does not require an aligned array.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template<class T> template<class T>
inline void VectorStore(const T& src, int off, byte dest[16]) inline void VectorStore(const T& src, int off, byte dest[16])
{ {
@ -289,73 +289,73 @@ inline void VectorStore(const T& src, int off, byte dest[16])
#endif #endif
} }
//! \brief Permutes two vectors /// \brief Permutes two vectors
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param vec1 the first vector /// \param vec1 the first vector
//! \param vec2 the second vector /// \param vec2 the second vector
//! \param mask vector mask /// \param mask vector mask
//! \details VectorPermute returns a new vector from vec1 and vec2 /// \details VectorPermute returns a new vector from vec1 and vec2
//! based on mask. mask is an uint8x16_p8 type vector. The return /// based on mask. mask is an uint8x16_p8 type vector. The return
//! vector is the same type as vec1. /// vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorPermute(const T1& vec1, const T1& vec2, const T2& mask) inline T1 VectorPermute(const T1& vec1, const T1& vec2, const T2& mask)
{ {
return (T1)vec_perm(vec1, vec2, (uint8x16_p8)mask); return (T1)vec_perm(vec1, vec2, (uint8x16_p8)mask);
} }
//! \brief XOR two vectors /// \brief XOR two vectors
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param vec1 the first vector /// \param vec1 the first vector
//! \param vec2 the second vector /// \param vec2 the second vector
//! \details VectorXor returns a new vector from vec1 and vec2. The return /// \details VectorXor returns a new vector from vec1 and vec2. The return
//! vector is the same type as vec1. /// vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorXor(const T1& vec1, const T2& vec2) inline T1 VectorXor(const T1& vec1, const T2& vec2)
{ {
return (T1)vec_xor(vec1, (T1)vec2); return (T1)vec_xor(vec1, (T1)vec2);
} }
//! \brief Add two vector /// \brief Add two vector
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param vec1 the first vector /// \param vec1 the first vector
//! \param vec2 the second vector /// \param vec2 the second vector
//! \details VectorAdd returns a new vector from vec1 and vec2. /// \details VectorAdd returns a new vector from vec1 and vec2.
//! vec2 is cast to the same type as vec1. The return vector /// vec2 is cast to the same type as vec1. The return vector
//! is the same type as vec1. /// is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorAdd(const T1& vec1, const T2& vec2) inline T1 VectorAdd(const T1& vec1, const T2& vec2)
{ {
return (T1)vec_add(vec1, (T1)vec2); return (T1)vec_add(vec1, (T1)vec2);
} }
//! \brief Shift two vectors left /// \brief Shift two vectors left
//! \tparam C shift byte count /// \tparam C shift byte count
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param vec1 the first vector /// \param vec1 the first vector
//! \param vec2 the second vector /// \param vec2 the second vector
//! \details VectorShiftLeft() concatenates vec1 and vec2 and returns a /// \details VectorShiftLeft() concatenates vec1 and vec2 and returns a
//! new vector after shifting the concatenation by the specified number /// new vector after shifting the concatenation by the specified number
//! of bytes. Both vec1 and vec2 are cast to uint8x16_p8. The return /// of bytes. Both vec1 and vec2 are cast to uint8x16_p8. The return
//! vector is the same type as vec1. /// vector is the same type as vec1.
//! \details On big endian machines VectorShiftLeft() is <tt>vec_sld(a, b, /// \details On big endian machines VectorShiftLeft() is <tt>vec_sld(a, b,
//! c)</tt>. On little endian machines VectorShiftLeft() is translated to /// c)</tt>. On little endian machines VectorShiftLeft() is translated to
//! <tt>vec_sld(b, a, 16-c)</tt>. You should always call the function as /// <tt>vec_sld(b, a, 16-c)</tt>. You should always call the function as
//! if on a big endian machine as shown below. /// if on a big endian machine as shown below.
//! <pre> /// <pre>
//! uint8x16_p8 r0 = {0}; /// uint8x16_p8 r0 = {0};
//! uint8x16_p8 r1 = VectorLoad(ptr); /// uint8x16_p8 r1 = VectorLoad(ptr);
//! uint8x16_p8 r5 = VectorShiftLeft<12>(r0, r1); /// uint8x16_p8 r5 = VectorShiftLeft<12>(r0, r1);
//! </pre> /// </pre>
//! \sa <A HREF="https://stackoverflow.com/q/46341923/608639">Is vec_sld /// \sa <A HREF="https://stackoverflow.com/q/46341923/608639">Is vec_sld
//! endian sensitive?</A> on Stack Overflow /// endian sensitive?</A> on Stack Overflow
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <unsigned int C, class T1, class T2> template <unsigned int C, class T1, class T2>
inline T1 VectorShiftLeft(const T1& vec1, const T2& vec2) inline T1 VectorShiftLeft(const T1& vec1, const T2& vec2)
{ {
@ -366,14 +366,14 @@ inline T1 VectorShiftLeft(const T1& vec1, const T2& vec2)
#endif #endif
} }
//! \brief One round of AES encryption /// \brief One round of AES encryption
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param state the state vector /// \param state the state vector
//! \param key the subkey vector /// \param key the subkey vector
//! \details VectorEncrypt performs one round of AES encryption of state /// \details VectorEncrypt performs one round of AES encryption of state
//! using subkey key. The return vector is the same type as vec1. /// using subkey key. The return vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorEncrypt(const T1& state, const T2& key) inline T1 VectorEncrypt(const T1& state, const T2& key)
{ {
@ -386,14 +386,14 @@ inline T1 VectorEncrypt(const T1& state, const T2& key)
#endif #endif
} }
//! \brief Final round of AES encryption /// \brief Final round of AES encryption
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param state the state vector /// \param state the state vector
//! \param key the subkey vector /// \param key the subkey vector
//! \details VectorEncryptLast performs the final round of AES encryption /// \details VectorEncryptLast performs the final round of AES encryption
//! of state using subkey key. The return vector is the same type as vec1. /// of state using subkey key. The return vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorEncryptLast(const T1& state, const T2& key) inline T1 VectorEncryptLast(const T1& state, const T2& key)
{ {
@ -406,14 +406,14 @@ inline T1 VectorEncryptLast(const T1& state, const T2& key)
#endif #endif
} }
//! \brief One round of AES decryption /// \brief One round of AES decryption
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param state the state vector /// \param state the state vector
//! \param key the subkey vector /// \param key the subkey vector
//! \details VectorDecrypt performs one round of AES decryption of state /// \details VectorDecrypt performs one round of AES decryption of state
//! using subkey key. The return vector is the same type as vec1. /// using subkey key. The return vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorDecrypt(const T1& state, const T2& key) inline T1 VectorDecrypt(const T1& state, const T2& key)
{ {
@ -426,14 +426,14 @@ inline T1 VectorDecrypt(const T1& state, const T2& key)
#endif #endif
} }
//! \brief Final round of AES decryption /// \brief Final round of AES decryption
//! \tparam T1 vector type /// \tparam T1 vector type
//! \tparam T2 vector type /// \tparam T2 vector type
//! \param state the state vector /// \param state the state vector
//! \param key the subkey vector /// \param key the subkey vector
//! \details VectorDecryptLast performs the final round of AES decryption /// \details VectorDecryptLast performs the final round of AES decryption
//! of state using subkey key. The return vector is the same type as vec1. /// of state using subkey key. The return vector is the same type as vec1.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <class T1, class T2> template <class T1, class T2>
inline T1 VectorDecryptLast(const T1& state, const T2& key) inline T1 VectorDecryptLast(const T1& state, const T2& key)
{ {
@ -446,14 +446,14 @@ inline T1 VectorDecryptLast(const T1& state, const T2& key)
#endif #endif
} }
//! \brief SHA256 Sigma functions /// \brief SHA256 Sigma functions
//! \tparam func function /// \tparam func function
//! \tparam subfunc sub-function /// \tparam subfunc sub-function
//! \tparam T vector type /// \tparam T vector type
//! \param vec the block to transform /// \param vec the block to transform
//! \details VectorSHA256 selects sigma0, sigma1, Sigma0, Sigma1 based on /// \details VectorSHA256 selects sigma0, sigma1, Sigma0, Sigma1 based on
//! func and subfunc. The return vector is the same type as vec. /// func and subfunc. The return vector is the same type as vec.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <int func, int subfunc, class T> template <int func, int subfunc, class T>
inline T VectorSHA256(const T& vec) inline T VectorSHA256(const T& vec)
{ {
@ -466,14 +466,14 @@ inline T VectorSHA256(const T& vec)
#endif #endif
} }
//! \brief SHA512 Sigma functions /// \brief SHA512 Sigma functions
//! \tparam func function /// \tparam func function
//! \tparam subfunc sub-function /// \tparam subfunc sub-function
//! \tparam T vector type /// \tparam T vector type
//! \param vec the block to transform /// \param vec the block to transform
//! \details VectorSHA512 selects sigma0, sigma1, Sigma0, Sigma1 based on /// \details VectorSHA512 selects sigma0, sigma1, Sigma0, Sigma1 based on
//! func and subfunc. The return vector is the same type as vec. /// func and subfunc. The return vector is the same type as vec.
//! \since Crypto++ 6.0 /// \since Crypto++ 6.0
template <int func, int subfunc, class T> template <int func, int subfunc, class T>
inline T VectorSHA512(const T& vec) inline T VectorSHA512(const T& vec)
{ {

48
pssr.h
View File

@ -1,7 +1,7 @@
// pssr.h - originally written and placed in the public domain by Wei Dai // pssr.h - originally written and placed in the public domain by Wei Dai
//! \file pssr.h /// \file pssr.h
//! \brief Classes for probablistic signature schemes /// \brief Classes for probablistic signature schemes
#ifndef CRYPTOPP_PSSR_H #ifndef CRYPTOPP_PSSR_H
#define CRYPTOPP_PSSR_H #define CRYPTOPP_PSSR_H
@ -16,7 +16,7 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief PSSR Message Encoding Method interface /// \brief PSSR Message Encoding Method interface
class CRYPTOPP_DLL PSSR_MEM_Base : public PK_RecoverableSignatureMessageEncodingMethod class CRYPTOPP_DLL PSSR_MEM_Base : public PK_RecoverableSignatureMessageEncodingMethod
{ {
public: public:
@ -44,27 +44,27 @@ private:
byte *recoverableMessage) const; byte *recoverableMessage) const;
}; };
//! \brief PSSR Message Encoding Method with Hash Identifier /// \brief PSSR Message Encoding Method with Hash Identifier
//! \tparam USE_HASH_ID flag indicating whether the HashId is used /// \tparam USE_HASH_ID flag indicating whether the HashId is used
template <bool USE_HASH_ID> class PSSR_MEM_BaseWithHashId; template <bool USE_HASH_ID> class PSSR_MEM_BaseWithHashId;
//! \brief PSSR Message Encoding Method with Hash Identifier /// \brief PSSR Message Encoding Method with Hash Identifier
//! \details If USE_HASH_ID is true, then EMSA2HashIdLookup<PSSR_MEM_Base> is used for the base class /// \details If USE_HASH_ID is true, then EMSA2HashIdLookup<PSSR_MEM_Base> is used for the base class
template<> class PSSR_MEM_BaseWithHashId<true> : public EMSA2HashIdLookup<PSSR_MEM_Base> {}; template<> class PSSR_MEM_BaseWithHashId<true> : public EMSA2HashIdLookup<PSSR_MEM_Base> {};
//! \brief PSSR Message Encoding Method without Hash Identifier /// \brief PSSR Message Encoding Method without Hash Identifier
//! \details If USE_HASH_ID is false, then PSSR_MEM_Base is used for the base class /// \details If USE_HASH_ID is false, then PSSR_MEM_Base is used for the base class
template<> class PSSR_MEM_BaseWithHashId<false> : public PSSR_MEM_Base {}; template<> class PSSR_MEM_BaseWithHashId<false> : public PSSR_MEM_Base {};
//! \brief PSSR Message Encoding Method /// \brief PSSR Message Encoding Method
//! \tparam ALLOW_RECOVERY flag indicating whether the scheme provides message recovery /// \tparam ALLOW_RECOVERY flag indicating whether the scheme provides message recovery
//! \tparam MGF mask generation function /// \tparam MGF mask generation function
//! \tparam SALT_LEN length of the salt /// \tparam SALT_LEN length of the salt
//! \tparam MIN_PAD_LEN minimum length of the pad /// \tparam MIN_PAD_LEN minimum length of the pad
//! \tparam USE_HASH_ID flag indicating whether the HashId is used /// \tparam USE_HASH_ID flag indicating whether the HashId is used
//! \details If ALLOW_RECOVERY is true, the the signature scheme provides message recovery. If /// \details If ALLOW_RECOVERY is true, the the signature scheme provides message recovery. If
//! ALLOW_RECOVERY is false, the the signature scheme is appendix, and the message must be /// ALLOW_RECOVERY is false, the the signature scheme is appendix, and the message must be
//! provided during verification. /// provided during verification.
template <bool ALLOW_RECOVERY, class MGF=P1363_MGF1, int SALT_LEN=-1, int MIN_PAD_LEN=0, bool USE_HASH_ID=false> template <bool ALLOW_RECOVERY, class MGF=P1363_MGF1, int SALT_LEN=-1, int MIN_PAD_LEN=0, bool USE_HASH_ID=false>
class PSSR_MEM : public PSSR_MEM_BaseWithHashId<USE_HASH_ID> class PSSR_MEM : public PSSR_MEM_BaseWithHashId<USE_HASH_ID>
{ {
@ -77,17 +77,17 @@ public:
static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string(ALLOW_RECOVERY ? "PSSR-" : "PSS-") + MGF::StaticAlgorithmName();} static std::string CRYPTOPP_API StaticAlgorithmName() {return std::string(ALLOW_RECOVERY ? "PSSR-" : "PSS-") + MGF::StaticAlgorithmName();}
}; };
//! \brief Probabilistic Signature Scheme with Recovery /// \brief Probabilistic Signature Scheme with Recovery
//! \details Signature Schemes with Recovery encode the message with the signature. /// \details Signature Schemes with Recovery encode the message with the signature.
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PSSR-MGF1">PSSR-MGF1</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PSSR-MGF1">PSSR-MGF1</a>
struct PSSR : public SignatureStandard struct PSSR : public SignatureStandard
{ {
typedef PSSR_MEM<true> SignatureMessageEncodingMethod; typedef PSSR_MEM<true> SignatureMessageEncodingMethod;
}; };
//! \brief Probabilistic Signature Scheme with Appendix /// \brief Probabilistic Signature Scheme with Appendix
//! \details Signature Schemes with Appendix require the message to be provided during verification. /// \details Signature Schemes with Appendix require the message to be provided during verification.
//! \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PSS-MGF1">PSS-MGF1</a> /// \sa <a href="http://www.weidai.com/scan-mirror/sig.html#sem_PSS-MGF1">PSS-MGF1</a>
struct PSS : public SignatureStandard struct PSS : public SignatureStandard
{ {
typedef PSSR_MEM<false> SignatureMessageEncodingMethod; typedef PSSR_MEM<false> SignatureMessageEncodingMethod;

1126
pubkey.h

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
// pwdbased.h - originally written and placed in the public domain by Wei Dai // pwdbased.h - originally written and placed in the public domain by Wei Dai
//! \file pwdbased.h /// \file pwdbased.h
//! \brief Password based key derivation functions /// \brief Password based key derivation functions
#ifndef CRYPTOPP_PWDBASED_H #ifndef CRYPTOPP_PWDBASED_H
#define CRYPTOPP_PWDBASED_H #define CRYPTOPP_PWDBASED_H
@ -13,39 +13,39 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \brief Abstract base class for password based key derivation function /// \brief Abstract base class for password based key derivation function
class PasswordBasedKeyDerivationFunction class PasswordBasedKeyDerivationFunction
{ {
public: public:
virtual ~PasswordBasedKeyDerivationFunction() {} virtual ~PasswordBasedKeyDerivationFunction() {}
//! \brief Provides the maximum derived key length /// \brief Provides the maximum derived key length
//! \returns maximum derived key length, in bytes /// \returns maximum derived key length, in bytes
virtual size_t MaxDerivedKeyLength() const =0; virtual size_t MaxDerivedKeyLength() const =0;
//! \brief Determines if the derivation function uses the purpose byte /// \brief Determines if the derivation function uses the purpose byte
//! \returns true if the derivation function uses the purpose byte, false otherwise /// \returns true if the derivation function uses the purpose byte, false otherwise
virtual bool UsesPurposeByte() const =0; virtual bool UsesPurposeByte() const =0;
//! \brief Derive key from the password /// \brief Derive key from the password
//! \param derived the byte buffer to receive the derived password /// \param derived the byte buffer to receive the derived password
//! \param derivedLen the size of the byte buffer to receive the derived password /// \param derivedLen the size of the byte buffer to receive the derived password
//! \param purpose an octet indicating the purpose of the derivation /// \param purpose an octet indicating the purpose of the derivation
//! \param password the byte buffer with the password /// \param password the byte buffer with the password
//! \param passwordLen the size of the password, in bytes /// \param passwordLen the size of the password, in bytes
//! \param salt the byte buffer with the salt /// \param salt the byte buffer with the salt
//! \param saltLen the size of the salt, in bytes /// \param saltLen the size of the salt, in bytes
//! \param iterations the number of iterations to attempt /// \param iterations the number of iterations to attempt
//! \param timeInSeconds the length of time the derivation function should execute /// \param timeInSeconds the length of time the derivation function should execute
//! \returns iteration count achieved /// \returns iteration count achieved
//! \details DeriveKey returns the actual iteration count achieved. If <tt>timeInSeconds == 0</tt>, then the complete number /// \details DeriveKey returns the actual iteration count achieved. If <tt>timeInSeconds == 0</tt>, then the complete number
//! of iterations will be obtained. If <tt>timeInSeconds != 0</tt>, then DeriveKey will iterate until time elapsed, as /// of iterations will be obtained. If <tt>timeInSeconds != 0</tt>, then DeriveKey will iterate until time elapsed, as
//! measured by ThreadUserTimer. /// measured by ThreadUserTimer.
virtual unsigned int DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const =0; virtual unsigned int DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const =0;
}; };
//! \brief PBKDF1 from PKCS #5 /// \brief PBKDF1 from PKCS #5
//! \tparam T a HashTransformation class /// \tparam T a HashTransformation class
template <class T> template <class T>
class PKCS5_PBKDF1 : public PasswordBasedKeyDerivationFunction class PKCS5_PBKDF1 : public PasswordBasedKeyDerivationFunction
{ {
@ -56,8 +56,8 @@ public:
unsigned int DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const; unsigned int DeriveKey(byte *derived, size_t derivedLen, byte purpose, const byte *password, size_t passwordLen, const byte *salt, size_t saltLen, unsigned int iterations, double timeInSeconds=0) const;
}; };
//! \brief PBKDF2 from PKCS #5 /// \brief PBKDF2 from PKCS #5
//! \tparam T a HashTransformation class /// \tparam T a HashTransformation class
template <class T> template <class T>
class PKCS5_PBKDF2_HMAC : public PasswordBasedKeyDerivationFunction class PKCS5_PBKDF2_HMAC : public PasswordBasedKeyDerivationFunction
{ {
@ -167,8 +167,8 @@ unsigned int PKCS5_PBKDF2_HMAC<T>::DeriveKey(byte *derived, size_t derivedLen, b
return iterations; return iterations;
} }
//! \brief PBKDF from PKCS #12, appendix B /// \brief PBKDF from PKCS #12, appendix B
//! \tparam T a HashTransformation class /// \tparam T a HashTransformation class
template <class T> template <class T>
class PKCS12_PBKDF : public PasswordBasedKeyDerivationFunction class PKCS12_PBKDF : public PasswordBasedKeyDerivationFunction
{ {

36
queue.h
View File

@ -1,7 +1,7 @@
// queue.h - originally written and placed in the public domain by Wei Dai // queue.h - originally written and placed in the public domain by Wei Dai
//! \file /// \file
//! \brief Classes for an unlimited queue to store bytes /// \brief Classes for an unlimited queue to store bytes
#ifndef CRYPTOPP_QUEUE_H #ifndef CRYPTOPP_QUEUE_H
#define CRYPTOPP_QUEUE_H #define CRYPTOPP_QUEUE_H
@ -13,21 +13,21 @@ NAMESPACE_BEGIN(CryptoPP)
class ByteQueueNode; class ByteQueueNode;
//! \class ByteQueue /// \class ByteQueue
//! \brief Data structure used to store byte strings /// \brief Data structure used to store byte strings
//! \details The queue is implemented as a linked list of byte arrays /// \details The queue is implemented as a linked list of byte arrays
class CRYPTOPP_DLL ByteQueue : public Bufferless<BufferedTransformation> class CRYPTOPP_DLL ByteQueue : public Bufferless<BufferedTransformation>
{ {
public: public:
//! \brief Construct a ByteQueue /// \brief Construct a ByteQueue
//! \param nodeSize the initial node size /// \param nodeSize the initial node size
//! \details Internally, ByteQueue uses a ByteQueueNode to store bytes, and \p nodeSize determines the /// \details Internally, ByteQueue uses a ByteQueueNode to store bytes, and \p nodeSize determines the
//! size of the ByteQueueNode. A value of 0 indicates the ByteQueueNode should be automatically sized, /// size of the ByteQueueNode. A value of 0 indicates the ByteQueueNode should be automatically sized,
//! which means a value of 256 is used. /// which means a value of 256 is used.
ByteQueue(size_t nodeSize=0); ByteQueue(size_t nodeSize=0);
//! \brief Copy construct a ByteQueue /// \brief Copy construct a ByteQueue
//! \param copy the other ByteQueue /// \param copy the other ByteQueue
ByteQueue(const ByteQueue &copy); ByteQueue(const ByteQueue &copy);
~ByteQueue(); ~ByteQueue();
@ -73,13 +73,13 @@ public:
byte operator[](lword i) const; byte operator[](lword i) const;
void swap(ByteQueue &rhs); void swap(ByteQueue &rhs);
//! \class Walker /// \class Walker
//! \brief A ByteQueue iterator /// \brief A ByteQueue iterator
class Walker : public InputRejecting<BufferedTransformation> class Walker : public InputRejecting<BufferedTransformation>
{ {
public: public:
//! \brief Construct a ByteQueue Walker /// \brief Construct a ByteQueue Walker
//! \param queue a ByteQueue /// \param queue a ByteQueue
Walker(const ByteQueue &queue) Walker(const ByteQueue &queue)
: m_queue(queue), m_node(NULLPTR), m_position(0), m_offset(0), m_lazyString(NULLPTR), m_lazyLength(0) : m_queue(queue), m_node(NULLPTR), m_position(0), m_offset(0), m_lazyString(NULLPTR), m_lazyLength(0)
{Initialize();} {Initialize();}
@ -124,7 +124,7 @@ private:
bool m_lazyStringModifiable; bool m_lazyStringModifiable;
}; };
//! use this to make sure LazyPut is finalized in event of exception /// use this to make sure LazyPut is finalized in event of exception
class CRYPTOPP_DLL LazyPutter class CRYPTOPP_DLL LazyPutter
{ {
public: public:
@ -138,7 +138,7 @@ private:
ByteQueue &m_bq; ByteQueue &m_bq;
}; };
//! like LazyPutter, but does a LazyPutModifiable instead /// like LazyPutter, but does a LazyPutModifiable instead
class LazyPutterModifiable : public LazyPutter class LazyPutterModifiable : public LazyPutter
{ {
public: public:

64
rabin.h
View File

@ -1,7 +1,7 @@
// rabin.h - originally written and placed in the public domain by Wei Dai // rabin.h - originally written and placed in the public domain by Wei Dai
//! \file rabin.h /// \file rabin.h
//! \brief Classes for Rabin encryption and signature schemes /// \brief Classes for Rabin encryption and signature schemes
#ifndef CRYPTOPP_RABIN_H #ifndef CRYPTOPP_RABIN_H
#define CRYPTOPP_RABIN_H #define CRYPTOPP_RABIN_H
@ -13,19 +13,19 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class RabinFunction /// \class RabinFunction
//! \brief Rabin trapdoor function using the public key /// \brief Rabin trapdoor function using the public key
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
class RabinFunction : public TrapdoorFunction, public PublicKey class RabinFunction : public TrapdoorFunction, public PublicKey
{ {
typedef RabinFunction ThisClass; typedef RabinFunction ThisClass;
public: public:
//! \brief Initialize a Rabin public key /// \brief Initialize a Rabin public key
//! \param n the modulus /// \param n the modulus
//! \param r element r /// \param r element r
//! \param s element s /// \param s element s
void Initialize(const Integer &n, const Integer &r, const Integer &s) void Initialize(const Integer &n, const Integer &r, const Integer &s)
{m_n = n; m_r = r; m_s = s;} {m_n = n; m_r = r; m_s = s;}
@ -52,32 +52,32 @@ protected:
Integer m_n, m_r, m_s; Integer m_n, m_r, m_s;
}; };
//! \class InvertibleRabinFunction /// \class InvertibleRabinFunction
//! \brief Rabin trapdoor function using the private key /// \brief Rabin trapdoor function using the private key
//! \since Crypto++ 2.0 /// \since Crypto++ 2.0
class InvertibleRabinFunction : public RabinFunction, public TrapdoorFunctionInverse, public PrivateKey class InvertibleRabinFunction : public RabinFunction, public TrapdoorFunctionInverse, public PrivateKey
{ {
typedef InvertibleRabinFunction ThisClass; typedef InvertibleRabinFunction ThisClass;
public: public:
//! \brief Initialize a Rabin private key /// \brief Initialize a Rabin private key
//! \param n modulus /// \param n modulus
//! \param r element r /// \param r element r
//! \param s element s /// \param s element s
//! \param p first prime factor /// \param p first prime factor
//! \param q second prime factor /// \param q second prime factor
//! \param u q<sup>-1</sup> mod p /// \param u q<sup>-1</sup> mod p
//! \details This Initialize() function overload initializes a private key from existing parameters. /// \details This Initialize() function overload initializes a private key from existing parameters.
void Initialize(const Integer &n, const Integer &r, const Integer &s, const Integer &p, const Integer &q, const Integer &u) void Initialize(const Integer &n, const Integer &r, const Integer &s, const Integer &p, const Integer &q, const Integer &u)
{m_n = n; m_r = r; m_s = s; m_p = p; m_q = q; m_u = u;} {m_n = n; m_r = r; m_s = s; m_p = p; m_q = q; m_u = u;}
//! \brief Create a Rabin private key /// \brief Create a Rabin private key
//! \param rng a RandomNumberGenerator derived class /// \param rng a RandomNumberGenerator derived class
//! \param keybits the size of the key, in bits /// \param keybits the size of the key, in bits
//! \details This function overload of Initialize() creates a new private key because it /// \details This function overload of Initialize() creates a new private key because it
//! takes a RandomNumberGenerator() as a parameter. If you have an existing keypair, /// takes a RandomNumberGenerator() as a parameter. If you have an existing keypair,
//! then use one of the other Initialize() overloads. /// then use one of the other Initialize() overloads.
void Initialize(RandomNumberGenerator &rng, unsigned int keybits) void Initialize(RandomNumberGenerator &rng, unsigned int keybits)
{GenerateRandomWithKeySize(rng, keybits);} {GenerateRandomWithKeySize(rng, keybits);}
@ -104,7 +104,7 @@ protected:
Integer m_p, m_q, m_u; Integer m_p, m_q, m_u;
}; };
//! \brief Rabin keys /// \brief Rabin keys
struct Rabin struct Rabin
{ {
static std::string StaticAlgorithmName() {return "Rabin-Crypto++Variant";} static std::string StaticAlgorithmName() {return "Rabin-Crypto++Variant";}
@ -112,16 +112,16 @@ struct Rabin
typedef InvertibleRabinFunction PrivateKey; typedef InvertibleRabinFunction PrivateKey;
}; };
//! \brief Rabin encryption scheme /// \brief Rabin encryption scheme
//! \tparam STANDARD encryption standard /// \tparam STANDARD encryption standard
template <class STANDARD> template <class STANDARD>
struct RabinES : public TF_ES<Rabin, STANDARD> struct RabinES : public TF_ES<Rabin, STANDARD>
{ {
}; };
//! \brief Rabin signature scheme /// \brief Rabin signature scheme
//! \tparam STANDARD signature standard /// \tparam STANDARD signature standard
//! \tparam H hash transformation /// \tparam H hash transformation
template <class STANDARD, class H> template <class STANDARD, class H>
struct RabinSS : public TF_SS<Rabin, STANDARD, H> struct RabinSS : public TF_SS<Rabin, STANDARD, H>
{ {

View File

@ -1,19 +1,19 @@
// randpool.h - originally written and placed in the public domain by Wei Dai // randpool.h - originally written and placed in the public domain by Wei Dai
// OldRandPool added by JW in August, 2017. // OldRandPool added by JW in August, 2017.
//! \file randpool.h /// \file randpool.h
//! \brief Class file for Randomness Pool /// \brief Class file for Randomness Pool
//! \details RandomPool can be used to generate cryptographic quality pseudorandom bytes /// \details RandomPool can be used to generate cryptographic quality pseudorandom bytes
//! after seeding the pool with IncorporateEntropy(). Internally, the generator uses /// after seeding the pool with IncorporateEntropy(). Internally, the generator uses
//! AES-256 to produce the stream. Entropy is stirred in using SHA-256. /// AES-256 to produce the stream. Entropy is stirred in using SHA-256.
//! \details RandomPool used to follow the design of randpool in PGP 2.6.x. At version 5.5 /// \details RandomPool used to follow the design of randpool in PGP 2.6.x. At version 5.5
//! RandomPool was redesigned to reduce the risk of reusing random numbers after state /// RandomPool was redesigned to reduce the risk of reusing random numbers after state
//! rollback (which may occur when running in a virtual machine like VMware or a hosted /// rollback (which may occur when running in a virtual machine like VMware or a hosted
//! environment). /// environment).
//! \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. You /// \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. You
//! should migrate away from OldRandomPool at the earliest opportunity. Use RandomPool /// should migrate away from OldRandomPool at the earliest opportunity. Use RandomPool
//! or AutoSeededRandomPool instead. /// or AutoSeededRandomPool instead.
//! \since Crypto++ 4.0 (PGP 2.6.x style), Crypto++ 5.5 (AES-256 based) /// \since Crypto++ 4.0 (PGP 2.6.x style), Crypto++ 5.5 (AES-256 based)
#ifndef CRYPTOPP_RANDPOOL_H #ifndef CRYPTOPP_RANDPOOL_H
#define CRYPTOPP_RANDPOOL_H #define CRYPTOPP_RANDPOOL_H
@ -26,23 +26,23 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class RandomPool /// \class RandomPool
//! \brief Randomness Pool based on AES-256 /// \brief Randomness Pool based on AES-256
//! \details RandomPool can be used to generate cryptographic quality pseudorandom bytes /// \details RandomPool can be used to generate cryptographic quality pseudorandom bytes
//! after seeding the pool with IncorporateEntropy(). Internally, the generator uses /// after seeding the pool with IncorporateEntropy(). Internally, the generator uses
//! AES-256 to produce the stream. Entropy is stirred in using SHA-256. /// AES-256 to produce the stream. Entropy is stirred in using SHA-256.
//! \details RandomPool used to follow the design of randpool in PGP 2.6.x. At version 5.5 /// \details RandomPool used to follow the design of randpool in PGP 2.6.x. At version 5.5
//! RandomPool was redesigned to reduce the risk of reusing random numbers after state /// RandomPool was redesigned to reduce the risk of reusing random numbers after state
//! rollback, which may occur when running in a virtual machine like VMware or a hosted /// rollback, which may occur when running in a virtual machine like VMware or a hosted
//! environment. /// environment.
//! \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. You /// \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. You
//! should migrate away from OldRandomPool at the earliest opportunity. /// should migrate away from OldRandomPool at the earliest opportunity.
//! \sa OldRandomPool /// \sa OldRandomPool
//! \since Crypto++ 4.0 (PGP 2.6.x style), Crypto++ 5.5 (AES-256 based) /// \since Crypto++ 4.0 (PGP 2.6.x style), Crypto++ 5.5 (AES-256 based)
class CRYPTOPP_DLL RandomPool : public RandomNumberGenerator, public NotCopyable class CRYPTOPP_DLL RandomPool : public RandomNumberGenerator, public NotCopyable
{ {
public: public:
//! \brief Construct a RandomPool /// \brief Construct a RandomPool
RandomPool(); RandomPool();
bool CanIncorporateEntropy() const {return true;} bool CanIncorporateEntropy() const {return true;}
@ -56,27 +56,27 @@ private:
bool m_keySet; bool m_keySet;
}; };
//! \class OldRandomPool /// \class OldRandomPool
//! \brief Randomness Pool based on PGP 2.6.x with MDC /// \brief Randomness Pool based on PGP 2.6.x with MDC
//! \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. The /// \details If you need the pre-Crypto++ 5.5 generator then use OldRandomPool class. The
//! OldRandomPool class is always available so you dont need to define /// OldRandomPool class is always available so you dont need to define
//! CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY. OldRandomPool also provides the modern /// CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY. OldRandomPool also provides the modern
//! interface, including <tt>CanIncorporateEntropy</tt>, <tt>IncorporateEntropy</tt> and /// interface, including <tt>CanIncorporateEntropy</tt>, <tt>IncorporateEntropy</tt> and
//! <tt>GenerateIntoBufferedTransformation</tt>. /// <tt>GenerateIntoBufferedTransformation</tt>.
//! \details You should migrate away from OldRandomPool at the earliest opportunity. Use a /// \details You should migrate away from OldRandomPool at the earliest opportunity. Use a
//! modern random number generator or key derivation function, like AutoSeededRandomPool or /// modern random number generator or key derivation function, like AutoSeededRandomPool or
//! HKDF. /// HKDF.
//! \deprecated This class uses an old style PGP 2.6.x with MDC. The generator risks reusing /// \deprecated This class uses an old style PGP 2.6.x with MDC. The generator risks reusing
//! random random numbers after state rollback. You should migrate away from OldRandomPool /// random random numbers after state rollback. You should migrate away from OldRandomPool
//! at the earliest opportunity. /// at the earliest opportunity.
//! \sa RandomPool, AutoSeededRandomPool, HKDF, P1363_KDF2, PKCS12_PBKDF, PKCS5_PBKDF2_HMAC /// \sa RandomPool, AutoSeededRandomPool, HKDF, P1363_KDF2, PKCS12_PBKDF, PKCS5_PBKDF2_HMAC
//! \since Crypto++ 6.0 (PGP 2.6.x style) /// \since Crypto++ 6.0 (PGP 2.6.x style)
class CRYPTOPP_DLL OldRandomPool : public RandomNumberGenerator class CRYPTOPP_DLL OldRandomPool : public RandomNumberGenerator
{ {
public: public:
//! \brief Construct an OldRandomPool /// \brief Construct an OldRandomPool
//! \param poolSize internal pool size of the generator /// \param poolSize internal pool size of the generator
//! \details poolSize must be greater than 16 /// \details poolSize must be greater than 16
OldRandomPool(unsigned int poolSize=384); OldRandomPool(unsigned int poolSize=384);
// RandomNumberGenerator interface (Crypto++ 5.5 and above) // RandomNumberGenerator interface (Crypto++ 5.5 and above)

44
rc2.h
View File

@ -1,7 +1,7 @@
// rc2.h - originally written and placed in the public domain by Wei Dai // rc2.h - originally written and placed in the public domain by Wei Dai
//! \file rc2.h /// \file rc2.h
//! \brief Classes for the RC2 block cipher /// \brief Classes for the RC2 block cipher
#ifndef CRYPTOPP_RC2_H #ifndef CRYPTOPP_RC2_H
#define CRYPTOPP_RC2_H #define CRYPTOPP_RC2_H
@ -12,8 +12,8 @@
NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(CryptoPP)
//! \class RC2_Info /// \class RC2_Info
//! \brief RC2 block cipher information /// \brief RC2 block cipher information
struct RC2_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, 128> struct RC2_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, 128>
{ {
CRYPTOPP_CONSTANT(DEFAULT_EFFECTIVE_KEYLENGTH = 1024) CRYPTOPP_CONSTANT(DEFAULT_EFFECTIVE_KEYLENGTH = 1024)
@ -21,14 +21,14 @@ struct RC2_Info : public FixedBlockSize<8>, public VariableKeyLength<16, 1, 128>
CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "RC2";} CRYPTOPP_STATIC_CONSTEXPR const char* StaticAlgorithmName() {return "RC2";}
}; };
//! \class RC2 /// \class RC2
//! \brief RC2 block cipher /// \brief RC2 block cipher
//! \sa <a href="http://www.cryptopp.com/wiki/RC2">RC2</a> on the Crypto Lounge. /// \sa <a href="http://www.cryptopp.com/wiki/RC2">RC2</a> on the Crypto Lounge.
class RC2 : public RC2_Info, public BlockCipherDocumentation class RC2 : public RC2_Info, public BlockCipherDocumentation
{ {
//! \class Base /// \class Base
//! \brief Class specific methods used to operate the cipher. /// \brief Class specific methods used to operate the cipher.
//! \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions /// \details Implementations and overrides in \p Base apply to both \p ENCRYPTION and \p DECRYPTION directions
class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<RC2_Info> class CRYPTOPP_NO_VTABLE Base : public BlockCipherImpl<RC2_Info>
{ {
public: public:
@ -39,18 +39,18 @@ class RC2 : public RC2_Info, public BlockCipherDocumentation
FixedSizeSecBlock<word16, 64> K; // expanded key table FixedSizeSecBlock<word16, 64> K; // expanded key table
}; };
//! \class Enc /// \class Enc
//! \brief Class specific methods used to operate the cipher in the forward direction. /// \brief Class specific methods used to operate the cipher in the forward direction.
//! \details Implementations and overrides in \p Enc apply to \p ENCRYPTION. /// \details Implementations and overrides in \p Enc apply to \p ENCRYPTION.
class CRYPTOPP_NO_VTABLE Enc : public Base class CRYPTOPP_NO_VTABLE Enc : public Base
{ {
public: public:
void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const; void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const;
}; };
//! \class Dec /// \class Dec
//! \brief Class specific methods used to operate the cipher in the reverse direction. /// \brief Class specific methods used to operate the cipher in the reverse direction.
//! \details Implementations and overrides in \p Dec apply to \p DECRYPTION. /// \details Implementations and overrides in \p Dec apply to \p DECRYPTION.
class CRYPTOPP_NO_VTABLE Dec : public Base class CRYPTOPP_NO_VTABLE Dec : public Base
{ {
public: public:
@ -59,9 +59,9 @@ class RC2 : public RC2_Info, public BlockCipherDocumentation
public: public:
//! \class Encryption /// \class Encryption
//! \brief Class specific methods used to operate the cipher in the forward direction. /// \brief Class specific methods used to operate the cipher in the forward direction.
//! \details Implementations and overrides in \p Encryption apply to \p ENCRYPTION. /// \details Implementations and overrides in \p Encryption apply to \p ENCRYPTION.
class Encryption : public BlockCipherFinal<ENCRYPTION, Enc> class Encryption : public BlockCipherFinal<ENCRYPTION, Enc>
{ {
public: public:
@ -72,9 +72,9 @@ public:
{SetKey(key, keyLen, MakeParameters("EffectiveKeyLength", effectiveKeyLen));} {SetKey(key, keyLen, MakeParameters("EffectiveKeyLength", effectiveKeyLen));}
}; };
//! \class Decryption /// \class Decryption
//! \brief Class specific methods used to operate the cipher in the reverse direction. /// \brief Class specific methods used to operate the cipher in the reverse direction.
//! \details Implementations and overrides in \p Decryption apply to \p DECRYPTION. /// \details Implementations and overrides in \p Decryption apply to \p DECRYPTION.
class Decryption : public BlockCipherFinal<DECRYPTION, Dec> class Decryption : public BlockCipherFinal<DECRYPTION, Dec>
{ {
public: public:

Some files were not shown because too many files have changed in this diff Show More