Add KeyDerivationFunction interface (GH #610, PR #611)

pull/612/head
Jeffrey Walton 2018-03-29 20:18:27 -04:00 committed by GitHub
parent 8c5abe604a
commit 32abab75f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 280 additions and 129 deletions

View File

@ -62,6 +62,7 @@ Plaintext - encoded string
Ciphertext - encoded string
Header - encoded string
Footer - encoded string
Secret - encoded string, used by some key derivation functions
DerivedKey - encoded string
DerivedLength - encoded string
Digest - encoded string

View File

@ -1,8 +1,8 @@
AlgorithmType: KDF
Name: HKDF(SHA-1)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 4
Key: 0x0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b
Salt: 0x000102030405060708090a0b0c
Info: 0xf0f1f2f3f4f5f6f7f8f9
DerivedKeyLength: 42
@ -11,9 +11,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-1)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 5
Key: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Secret: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Salt: 0x606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
Info: 0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
DerivedKeyLength: 82
@ -22,9 +22,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-1)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 6
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: ""
Info: ""
DerivedKeyLength: 42
@ -33,10 +33,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-1)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 7
Key: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Salt: ""
Secret: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Info: ""
DerivedKeyLength: 42
DerivedKey: 0x2c91117204d745f3500d636a62f64f0ab3bae548aa53d423b0d1f27ebba6f5e5673a081d70cce7acfc48
@ -44,9 +43,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-256)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 1
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: 0x000102030405060708090a0b0c
Info: 0xf0f1f2f3f4f5f6f7f8f9
DerivedKeyLength: 42
@ -55,9 +54,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-256)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 2
Key: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Secret: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Salt: 0x606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
Info: 0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
DerivedKeyLength: 82
@ -66,9 +65,9 @@ Test: Verify
AlgorithmType: KDF
Name: HKDF(SHA-256)
Source: RFC 5689
Source: RFC 5869
Comment: Test Case 3
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: ""
Info: ""
DerivedKeyLength: 42
@ -79,7 +78,7 @@ AlgorithmType: KDF
Name: HKDF(SHA-512)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 8 (Mirror Tests 1 and 4)
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: 0x000102030405060708090a0b0c
Info: 0xf0f1f2f3f4f5f6f7f8f9
DerivedKeyLength: 42
@ -90,7 +89,7 @@ AlgorithmType: KDF
Name: HKDF(SHA-512)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 9 (Mirror Tests 2 and 5)
Key: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Secret: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Salt: 0x606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
Info: 0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
DerivedKeyLength: 82
@ -101,7 +100,7 @@ AlgorithmType: KDF
Name: HKDF(SHA-512)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 10 (Mirror Test 3 and 6)
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: ""
Info: ""
DerivedKeyLength: 42
@ -112,7 +111,7 @@ AlgorithmType: KDF
Name: HKDF(SHA-512)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 11
Key: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Secret: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Salt: ""
Info:
DerivedKeyLength: 42
@ -123,7 +122,7 @@ AlgorithmType: KDF
Name: HKDF(SHA-512)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 12 (Mirror Tests 3 and 6)
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: ""
Info: ""
DerivedKeyLength: 42
@ -134,7 +133,7 @@ AlgorithmType: KDF
Name: HKDF(Whirlpool)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 13 (Mirror Tests 1 and 4)
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: 0x000102030405060708090a0b0c
Info: 0xf0f1f2f3f4f5f6f7f8f9
DerivedKeyLength: 42
@ -145,7 +144,7 @@ AlgorithmType: KDF
Name: HKDF(Whirlpool)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 14 (Mirror Tests 2 and 5)
Key: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Secret: 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f
Salt: 0x606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf
Info: 0xb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
DerivedKeyLength: 82
@ -156,7 +155,7 @@ AlgorithmType: KDF
Name: HKDF(Whirlpool)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 15 (Mirror Tests 3 and 6)
Key: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Secret: 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b
Salt: ""
Info: ""
DerivedKeyLength: 42
@ -167,8 +166,7 @@ AlgorithmType: KDF
Name: HKDF(Whirlpool)
Source: Generated by Crypto++ 5.6.3
Comment: Test Case 16 (Mirror Test 7)
Key: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Salt: r64 0x00
Secret: 0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c
Info: ""
DerivedKeyLength: 42
DerivedKey: 0x4089286EBFB23DD8A02F0C9DAA35D538EB09CD0A8CBAB203F39083AA3E0BD313E6F91E64F21A187510B0

View File

@ -333,6 +333,31 @@ void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransform
}
}
const Algorithm & KeyDerivationFunction::GetAlgorithm() const
{
return *this;
}
size_t KeyDerivationFunction::MinDerivedLength() const
{
return 0;
}
size_t KeyDerivationFunction::MaxDerivedLength() const
{
return static_cast<size_t>(-1);
}
void KeyDerivationFunction::ThrowIfInvalidDerivedLength(size_t length) const
{
if (!IsValidDerivedLength(length))
throw InvalidDerivedLength(GetAlgorithm().AlgorithmName(), length);
}
void KeyDerivationFunction::SetParameters(const NameValuePairs& params) {
CRYPTOPP_UNUSED(params);
}
/// \brief Random Number Generator that does not produce random numbers
/// \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.

View File

@ -632,8 +632,7 @@ public:
/// \brief Sets or reset the key of this object
/// \param key the key to use when keying the object
/// \param length the size of the key, in bytes
/// \param params additional initialization parameters that cannot be passed
/// directly through the constructor
/// \param params additional initialization parameters to configure this object
virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
/// \brief Sets or reset the key of this object
@ -1325,8 +1324,10 @@ protected:
};
/// \brief Interface for random number generators
/// \details The library provides a number of random number generators, from software based to hardware based generators.
/// \details The library provides a number of random number generators, from software based
/// to hardware based generators.
/// \details All generated values are uniformly distributed over the range specified.
/// \since Crypto++ 3.1
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
{
public:
@ -1336,10 +1337,10 @@ public:
/// \param input the entropy to add to the generator
/// \param length the size of the input buffer
/// \throws NotImplemented
/// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy() to test for the
/// ability to use additional entropy.
/// \details If a derived class does not override IncorporateEntropy(), then the base class throws
/// NotImplemented.
/// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
/// to test for the ability to use additional entropy.
/// \details If a derived class does not override IncorporateEntropy(), then the base class
/// throws NotImplemented.
virtual void IncorporateEntropy(const byte *input, size_t length)
{
CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
@ -1411,6 +1412,70 @@ public:
}
};
/// \brief Interface for key derivation functions
/// \since Crypto++ 6.2
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
{
public:
virtual ~KeyDerivationFunction() {}
virtual const Algorithm & GetAlgorithm() const =0;
/// \brief Provides the name of this algorithm
/// \return the standard algorithm name
virtual std::string AlgorithmName() const =0;
/// \brief Determine minimum number of bytes
/// \returns Minimum number of bytes which can be derived
virtual size_t MinDerivedLength() const;
/// \brief Determine maximum number of bytes
/// \returns Maximum number of bytes which can be derived
virtual size_t MaxDerivedLength() const;
/// \brief Returns a valid key length for the derivation function
/// \param keylength the size of the derived key, in bytes
/// \returns the valid key length, in bytes
virtual size_t GetValidDerivedLength(size_t keylength) const =0;
/// \brief Returns whether keylength is a valid key length
/// \param keylength the requested keylength
/// \return true if the derived keylength is valid, false otherwise
/// \details Internally the function calls GetValidKeyLength()
virtual bool IsValidDerivedLength(size_t keylength) const {
return keylength == GetValidDerivedLength(keylength);
}
/// \brief Derive a key from a seed
/// \param derived the derived output buffer
/// \param derivedLen the size of the derived buffer, in bytes
/// \param secret the seed input buffer
/// \param secretLen the size of the secret buffer, in bytes
/// \param params additional initialization parameters to configure this object
/// \returns the number of bytes derived
/// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
/// \details DeriveKey() provides a standard interface to derive a key from
/// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
/// provides an overload that accepts most parameters used by the derivation function.
/// \details the number of bytes derived by DeriveKey() may be less than the number
/// requested in <tt>derivedLen</tt>. For example, a scheme may be limited to a
/// certain amount of time for derivation.
virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params) const =0;
/// \brief Set or change parameters
/// \param params additional initialization parameters to configure this object
/// \details SetParameters() is useful for setting common parameters when an object is
/// reused. Some derivation function classes may choose to implement it.
virtual void SetParameters(const NameValuePairs& params);
protected:
/// \brief Validates the derived key length
/// \param length the size of the derived key material, in bytes
/// \throws InvalidKeyLength if the key length is invalid
void ThrowIfInvalidDerivedLength(size_t length) const;
};
/// \brief Random Number Generator that does not produce random numbers
/// \return reference that can be passed to functions that require a RandomNumberGenerator
/// \details NullRNG() returns a reference that can be passed to functions that require a
@ -2047,7 +2112,7 @@ public:
/// \brief Request space which can be written into by the caller
/// \param channel the channel to process the data
/// \param size the requested size of the buffer
/// \return a pointer to a memroy block with length size
/// \return a pointer to a memory block with length size
/// \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,
/// size is the requested size of the buffer. When the call returns, size is the size of

View File

@ -15,7 +15,6 @@
#include "queue.h"
#include "smartptr.h"
#include "validate.h"
#include "hkdf.h"
#include "stdcpp.h"
#include <iostream>
#include <sstream>
@ -150,13 +149,15 @@ void PutDecodedDatumInto(const TestData &data, const char *name, BufferedTransfo
}
else if (s1.substr(0, 2) == "0x")
{
StringSource(s1.substr(2, s1.find(' ')), true, new HexDecoder(new StringSink(s2)));
s1 = s1.substr(STDMIN(s1.find(' '), s1.length()));
std::string::size_type pos = s1.find(' ');
StringSource(s1.substr(2, pos), true, new HexDecoder(new StringSink(s2)));
s1 = s1.substr(STDMIN(pos, s1.length()));
}
else
{
StringSource(s1.substr(0, s1.find(' ')), true, new HexDecoder(new StringSink(s2)));
s1 = s1.substr(STDMIN(s1.find(' '), s1.length()));
std::string::size_type pos = s1.find(' ');
StringSource(s1.substr(0, pos), true, new HexDecoder(new StringSink(s2)));
s1 = s1.substr(STDMIN(pos, s1.length()));
}
while (repeat--)
@ -222,7 +223,7 @@ public:
{
m_temp.clear();
PutDecodedDatumInto(m_data, name, StringSink(m_temp).Ref());
reinterpret_cast<ConstByteArrayParameter *>(pValue)->Assign((const byte *)m_temp.data(), m_temp.size(), false);
reinterpret_cast<ConstByteArrayParameter *>(pValue)->Assign((const byte *)&m_temp[0], m_temp.size(), false);
}
else
throw ValueTypeMismatch(name, typeid(std::string), valueType);
@ -258,12 +259,12 @@ void TestSignatureScheme(TestData &v)
member_ptr<PK_Signer> signer(ObjectFactoryRegistry<PK_Signer>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Verifier> verifier(ObjectFactoryRegistry<PK_Verifier>::Registry().CreateObject(name.c_str()));
TestDataNameValuePairs pairs(v);
// Code coverage
(void)signer->AlgorithmName();
(void)verifier->AlgorithmName();
TestDataNameValuePairs pairs(v);
if (test == "GenerateKey")
{
signer->AccessPrivateKey().GenerateRandom(Test::GlobalRNG(), pairs);
@ -329,11 +330,6 @@ void TestSignatureScheme(TestData &v)
return;
}
else if (test == "RandomSign")
{
SignalTestError();
CRYPTOPP_ASSERT(false); // TODO: implement
}
else
{
SignalTestError();
@ -349,6 +345,10 @@ void TestAsymmetricCipher(TestData &v)
member_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str()));
member_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str()));
// Code coverage
(void)encryptor->AlgorithmName();
(void)decryptor->AlgorithmName();
std::string keyFormat = GetRequiredDatum(v, "KeyFormat");
if (keyFormat == "DER")
@ -363,10 +363,6 @@ void TestAsymmetricCipher(TestData &v)
encryptor->AccessMaterial().AssignFrom(pairs);
}
// Code coverage
(void)encryptor->AlgorithmName();
(void)decryptor->AlgorithmName();
if (test == "DecryptMatch")
{
std::string decrypted, expected = GetDecodedDatum(v, "Plaintext");
@ -406,6 +402,16 @@ void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
encryptor.reset(ObjectFactoryRegistry<SymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str()));
decryptor.reset(ObjectFactoryRegistry<SymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str()));
lastName = name;
// Code coverage
(void)encryptor->AlgorithmName();
(void)decryptor->AlgorithmName();
(void)encryptor->MinKeyLength();
(void)decryptor->MinKeyLength();
(void)encryptor->MaxKeyLength();
(void)decryptor->MaxKeyLength();
(void)encryptor->DefaultKeyLength();
(void)decryptor->DefaultKeyLength();
}
// Most block ciphers don't specify BlockPaddingScheme. Kalyna uses it in test vectors.
@ -429,16 +435,6 @@ void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
decryptor->SetKey((const byte *)key.data(), key.size(), pairs);
}
// Code coverage
(void)encryptor->AlgorithmName();
(void)decryptor->AlgorithmName();
(void)encryptor->MinKeyLength();
(void)decryptor->MinKeyLength();
(void)encryptor->MaxKeyLength();
(void)decryptor->MaxKeyLength();
(void)encryptor->DefaultKeyLength();
(void)decryptor->DefaultKeyLength();
int seek = pairs.GetIntValueWithDefault("Seek", 0);
if (seek)
{
@ -681,27 +677,27 @@ void TestKeyDerivationFunction(TestData &v)
if(test == "Skip") return;
CRYPTOPP_ASSERT(test == "Verify");
std::string key = GetDecodedDatum(v, "Key");
std::string salt = GetDecodedDatum(v, "Salt");
std::string info = GetDecodedDatum(v, "Info");
std::string derived = GetDecodedDatum(v, "DerivedKey");
std::string t = GetDecodedDatum(v, "DerivedKeyLength");
std::string secret = GetDecodedDatum(v, "Secret");
std::string expected = GetDecodedDatum(v, "DerivedKey");
TestDataNameValuePairs pairs(v);
unsigned int length = pairs.GetIntValueWithDefault(Name::DerivedKeyLength(), (int)derived.size());
member_ptr<KeyDerivationFunction> kdf;
kdf.reset(ObjectFactoryRegistry<KeyDerivationFunction>::Registry().CreateObject(name.c_str()));
std::string calc; calc.resize(length);
unsigned int ret = kdf->DeriveKey(reinterpret_cast<byte*>(&calc[0]), calc.size(),
reinterpret_cast<const byte*>(key.data()), key.size(),
reinterpret_cast<const byte*>(salt.data()), salt.size(),
reinterpret_cast<const byte*>(info.data()), info.size());
std::string calculated; calculated.resize(expected.size());
kdf->DeriveKey(reinterpret_cast<byte*>(&calculated[0]), calculated.size(),
reinterpret_cast<const byte*>(&secret[0]), secret.size(), pairs);
if(calculated != expected)
{
std::cerr << "Calculated: ";
StringSource(calculated, true, new HexEncoder(new FileSink(std::cerr)));
std::cerr << std::endl;
if(calc != derived || ret != length)
SignalTestFailure();
}
}
// GetField parses the name/value pairs. The tricky part is the insertion operator
// because Unix&Linux uses LF, OS X uses CR, and Windows uses CRLF. If this function

154
hkdf.h
View File

@ -4,29 +4,15 @@
/// \brief Classes for HKDF from RFC 5869
/// \since Crypto++ 5.6.3
#ifndef CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H
#define CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H
#ifndef CRYPTOPP_HKDF_H
#define CRYPTOPP_HKDF_H
#include "cryptlib.h"
#include "hrtimer.h"
#include "secblock.h"
#include "hmac.h"
NAMESPACE_BEGIN(CryptoPP)
/// abstract base class for key derivation function
class KeyDerivationFunction
{
public:
/// maximum number of bytes which can be produced under a secuirty context
virtual size_t MaxDerivedKeyLength() const =0;
virtual bool Usesinfo() const =0;
/// 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 ~KeyDerivationFunction() {}
};
/// \brief Extract-and-Expand Key Derivation Function (HKDF)
/// \tparam T HashTransformation class
/// \sa <A HREF="http://eprint.iacr.org/2010/264">Cryptographic Extraction and Key Derivation: The HKDF Scheme</A>
@ -36,20 +22,57 @@ template <class T>
class HKDF : public KeyDerivationFunction
{
public:
CRYPTOPP_CONSTANT(DIGESTSIZE = T::DIGESTSIZE)
CRYPTOPP_CONSTANT(SALTSIZE = T::DIGESTSIZE)
static const char* StaticAlgorithmName () {
static const std::string name(std::string("HKDF(") + std::string(T::StaticAlgorithmName()) + std::string(")"));
return name.c_str();
virtual ~HKDF() {}
static std::string StaticAlgorithmName () {
const std::string name(std::string("HKDF(") +
std::string(T::StaticAlgorithmName()) + std::string(")"));
return name;
}
size_t MaxDerivedKeyLength() const {return static_cast<size_t>(T::DIGESTSIZE) * 255;}
bool Usesinfo() const {return true;}
unsigned int DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, const byte* info, size_t infoLen) const;
const Algorithm & GetAlgorithm() const {
return *this;
}
std::string AlgorithmName() const {
return StaticAlgorithmName();
}
size_t MaxDerivedLength() const {
return static_cast<size_t>(T::DIGESTSIZE) * 255;
}
size_t GetValidDerivedLength(size_t keylength) const;
// Base class override
size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const NameValuePairs& params) const;
/// \brief Derive a key from a seed
/// \param derived the derived output buffer
/// \param derivedLen the size of the derived buffer, in bytes
/// \param secret the seed input buffer
/// \param secretLen the size of the secret buffer, in bytes
/// \param salt the salt input buffer
/// \param saltLen the size of the salt buffer, in bytes
/// \param info the additional input buffer
/// \param infoLen the size of the info buffer, in bytes
/// \throws InvalidDerivedLength if <tt>derivedLen</tt> is invalid for the scheme
/// \details DeriveKey() provides a standard interface to derive a key from
/// a seed and other parameters. Each class that derives from KeyDerivationFunction
/// provides an overload that accepts most parameters used by the derivation function.
/// \details <tt>salt</tt> and <tt>info</tt> can be <tt>nullptr</tt> with 0 length.
/// HDF is unusual in that a non-NULL salt with length 0 is different than a
/// NULL <tt>salt</tt>. A NULL <tt>salt</tt> causes HDF to use a string of 0's
/// of length <tt>T::DIGESTSIZE</tt> for the <tt>salt</tt>.
size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const byte *salt, size_t saltLen, const byte* info, size_t infoLen) const;
protected:
// If salt is missing (NULLPTR), then use the NULL vector. Missing is different than EMPTY (0 length). The length
// of s_NullVector used depends on the Hash function. SHA-256 will use 32 bytes of s_NullVector.
typedef byte NullVectorType[SALTSIZE];
// If salt is absent (NULL), then use the NULL vector. Missing is different than
// EMPTY (Non-NULL, 0 length). The length of s_NullVector used depends on the Hash
// function. SHA-256 will use 32 bytes of s_NullVector.
typedef byte NullVectorType[T::DIGESTSIZE];
static const NullVectorType& GetNullVector() {
static const NullVectorType s_NullVector = {0};
return s_NullVector;
@ -57,53 +80,88 @@ protected:
};
template <class T>
unsigned int HKDF<T>::DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, const byte* info, size_t infoLen) const
size_t HKDF<T>::GetValidDerivedLength(size_t keylength) const
{
static const size_t DIGEST_SIZE = static_cast<size_t>(T::DIGESTSIZE);
const unsigned int req = static_cast<unsigned int>(derivedLen);
if (keylength > MaxDerivedLength())
return MaxDerivedLength();
return keylength;
}
template <class T>
size_t HKDF<T>::DeriveKey(byte *derived, size_t derivedLen,
const byte *secret, size_t secretLen, const NameValuePairs& params) const
{
CRYPTOPP_ASSERT(secret && secretLen);
CRYPTOPP_ASSERT(derived && derivedLen);
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedKeyLength());
CRYPTOPP_ASSERT(derivedLen <= MaxDerivedLength());
if (derivedLen > MaxDerivedKeyLength())
throw InvalidArgument("HKDF: derivedLen must be less than or equal to MaxDerivedKeyLength");
ThrowIfInvalidDerivedLength(derivedLen);
// Copy-out Salt to a temporary
ConstByteArrayParameter p;
if (!params.GetValue("Salt", p))
p = ConstByteArrayParameter(GetNullVector(), T::DIGESTSIZE);
SecByteBlock salt(p.begin(), p.size());
// Warning: the 'params.GetValue' for Info blows away the data
// from the previous call to 'params.GetValue' for Salt.
// It is the reason we copy-out the data after Salt.
if (!params.GetValue("Info", p))
p = ConstByteArrayParameter(GetNullVector(), 0);
SecByteBlock info(p.begin(), p.size());
// key is PRK from the RFC, salt is IKM from the RFC
HMAC<T> hmac;
FixedSizeSecBlock<byte, DIGEST_SIZE> prk, buffer;
SecByteBlock key(T::DIGESTSIZE), buffer(T::DIGESTSIZE);
// Extract
const byte* key = (salt ? salt : GetNullVector());
const size_t klen = (salt ? saltLen : DIGEST_SIZE);
hmac.SetKey(salt.begin(), salt.size());
hmac.CalculateDigest(key, secret, secretLen);
hmac.SetKey(key, klen);
hmac.CalculateDigest(prk, secret, secretLen);
// Expand
hmac.SetKey(prk.data(), prk.size());
// Key
hmac.SetKey(key.begin(), key.size());
byte block = 0;
while (derivedLen > 0)
size_t bytesRemaining = derivedLen;
size_t digestSize = static_cast<size_t>(T::DIGESTSIZE);
// Expand
while (bytesRemaining > 0)
{
if (block++) {hmac.Update(buffer, buffer.size());}
if (info && infoLen) {hmac.Update(info, infoLen);}
if (info.size()) {hmac.Update(info.begin(), info.size());}
hmac.CalculateDigest(buffer, &block, 1);
#if CRYPTOPP_MSC_VERSION
const size_t segmentLen = STDMIN(derivedLen, DIGEST_SIZE);
const size_t segmentLen = STDMIN(bytesRemaining, digestSize);
memcpy_s(derived, segmentLen, buffer, segmentLen);
#else
const size_t segmentLen = STDMIN(derivedLen, DIGEST_SIZE);
const size_t segmentLen = STDMIN(bytesRemaining, digestSize);
std::memcpy(derived, buffer, segmentLen);
#endif
derived += segmentLen;
derivedLen -= segmentLen;
bytesRemaining -= segmentLen;
}
return req;
return derivedLen;
}
template <class T>
size_t HKDF<T>::DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen,
const byte *salt, size_t saltLen, const byte* info, size_t infoLen) const
{
AlgorithmParameters params;
if (salt != NULLPTR) // Non-NULL and 0 length is valid for HKDF salt
params.operator()(Name::Salt(), ConstByteArrayParameter(salt, saltLen));
if (info != NULLPTR) // Non-NULL and 0 length is valid for HKDF salt
params.operator()("Info", ConstByteArrayParameter(info, infoLen));
return DeriveKey(derived, derivedLen, secret, secretLen, params);
}
NAMESPACE_END
#endif // CRYPTOPP_HASH_KEY_DERIVATION_FUNCTION_H
#endif // CRYPTOPP_HKDF_H

View File

@ -69,6 +69,13 @@ public:
explicit InvalidBlockSize(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid block size") {}
};
/// \brief Exception thrown when an invalid derived key length is encountered
class CRYPTOPP_DLL InvalidDerivedLength : public InvalidArgument
{
public:
explicit InvalidDerivedLength(const std::string &algorithm, size_t length) : InvalidArgument(algorithm + ": " + IntToString(length) + " is not a valid derived key length") {}
};
/// \brief Exception thrown when an invalid personalization string length is encountered
class CRYPTOPP_DLL InvalidPersonalizationLength : public InvalidArgument
{

View File

@ -662,15 +662,18 @@ bool TestHKDF(KeyDerivationFunction &kdf, const HKDF_TestTuple *testSet, unsigne
StringSource(tuple.hexSalt ? tuple.hexSalt : "", true, new HexDecoder(new StringSink(salt)));
StringSource(tuple.hexInfo ? tuple.hexInfo : "", true, new HexDecoder(new StringSink(info)));
StringSource(tuple.hexExpected, true, new HexDecoder(new StringSink(expected)));
SecByteBlock derived(expected.size());
unsigned int ret = kdf.DeriveKey(derived, derived.size(),
reinterpret_cast<const unsigned char*>(secret.data()), secret.size(),
(tuple.hexSalt ? reinterpret_cast<const unsigned char*>(salt.data()) : NULLPTR), salt.size(),
(tuple.hexInfo ? reinterpret_cast<const unsigned char*>(info.data()) : NULLPTR), info.size());
bool fail = !VerifyBufsEqual(derived, reinterpret_cast<const unsigned char*>(expected.data()), derived.size());
pass = pass && (ret == tuple.len) && !fail;
AlgorithmParameters params;
if (tuple.hexSalt)
params.operator()(Name::Salt(), ConstByteArrayParameter((const byte*)&salt[0], salt.size()));
if (tuple.hexSalt)
params.operator()("Info", ConstByteArrayParameter((const byte*)&info[0], info.size()));
kdf.DeriveKey((byte*)&derived[0], derived.size(), (const byte*)&secret[0], secret.size(), params);
bool fail = !VerifyBufsEqual(derived, (const byte*)&expected[0], derived.size());
pass = pass && !fail;
HexEncoder enc(new FileSink(std::cout));
std::cout << (fail ? "FAILED " : "passed ");
@ -748,8 +751,6 @@ bool ValidateHKDF()
pass = TestHKDF(hkdf, testSet, COUNTOF(testSet)) && pass;
}
{
// Whirlpool, Crypto++ generated, based on RFC 5869, https://tools.ietf.org/html/rfc5869
static const HKDF_TestTuple testSet[] =