Monday, November 08, 2021

Generate KEY and IV for CryptoPP in C++


In this tutorial, I will share strategies to generate random keys and initialization vector in C++ using CryptoPP library.

Approach 1:

SecByteBlock key(32), iv(24);
AutoSeededRandomPool prng;
prng.GenerateBlock(key, key.size());
prng.GenerateBlock(iv, iv.size());

Approach 2:

SecByteBlock key(16), iv(16);
std::string password = "Super secret password";
DeriveKeyAndIV(password, "encryption example", 100, key, key.size(), iv, iv.size());

void DeriveKeyAndIV(const std::string& master,
const std::string& salt, unsigned int iterations,
SecByteBlock& key, unsigned long ksize,
SecByteBlock& iv, unsigned long vsize) {
    SecByteBlock tb, ts(SHA512::DIGESTSIZE), tm(SHA512::DIGESTSIZE);
    SHA512 hash;
    hash.CalculateDigest(ts, (const byte*)salt.data(), salt.size());
    
    static const std::string s1 = "master key";
    tb = SecByteBlock((const byte*)master.data(), master.size()) + SecByteBlock((const byte*)s1.data(), s1.size());
    
    PKCS5_PBKDF2_HMAC<SHA512> pbkdf;
    const byte unused = 0;
    pbkdf.DeriveKey(tm, tm.size(),
                    unused,
                    tb, tb.size(),
                    ts, ts.size(),
                    iterations);
    
    static const std::string s2 = "encryption key";
    key.resize(ksize);
    tb = tm + SecByteBlock((const byte*)s2.data(), s2.size());
    pbkdf.DeriveKey(key, key.size(),
                    unused,
                    tb, tb.size(),
                    ts, ts.size(),
                    iterations);
    
    static const std::string s3 = "initialization vector";
    iv.resize(vsize);
    tb = tm + SecByteBlock((const byte*)s3.data(), s3.size());
    pbkdf.DeriveKey(iv, iv.size(),
                    unused,
                    tb, tb.size(),
                    ts, ts.size(),
                    iterations);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.