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.size());
    static const std::string s1 = "master key";
    tb = SecByteBlock((const byte*), master.size()) + SecByteBlock((const byte*), s1.size());
    PKCS5_PBKDF2_HMAC<SHA512> pbkdf;
    const byte unused = 0;
    pbkdf.DeriveKey(tm, tm.size(),
                    tb, tb.size(),
                    ts, ts.size(),
    static const std::string s2 = "encryption key";
    tb = tm + SecByteBlock((const byte*), s2.size());
    pbkdf.DeriveKey(key, key.size(),
                    tb, tb.size(),
                    ts, ts.size(),
    static const std::string s3 = "initialization vector";
    tb = tm + SecByteBlock((const byte*), s3.size());
    pbkdf.DeriveKey(iv, iv.size(),
                    tb, tb.size(),
                    ts, ts.size(),

No comments:

Post a Comment

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