a firstworks project
Rudiments
About Documentation Download Licensing News

Using the pbkdf2 class

The pbkdf2 class provides a PBKDF2 (Password-Based Key Derivation Function 2) implementation which derives a cryptographic key from a password.

The pbkdf2 class inherits from the hash class. The append() method feeds in the password data and getHash() retrieves the derived key. The clear() method resets the data while preserving the salt, iterations, algorithm, and key size settings, and reset() clears everything.

The setAlgorithm() method sets the underlying hash algorithm. Supported algorithms are PBKDF2_ALGORITHM_SHA1, PBKDF2_ALGORITHM_SHA256, and PBKDF2_ALGORITHM_SHA512. The default is SHA256.

The setIterations() method sets the number of times the hash algorithm is applied. The default is 10000.

The setKeySize() method sets the size of the derived key in bytes.

The setSalt() method sets the salt used during key derivation.

The isSupported() method can be used to determine if PBKDF2 is available on the current platform.

The following example derives a key from a password using SHA256, clears and derives from a different password, then resets and derives using SHA512.

#include <rudiments/pbkdf2.h>
#include <rudiments/charstring.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

	pbkdf2	p;

	// check whether pbkdf2 is supported
	if (!p.isSupported()) {
		stdoutput.write("pbkdf2 is not supported\n");
		return 1;
	}


	// configure pbkdf2
	p.setAlgorithm(PBKDF2_ALGORITHM_SHA256);
	p.setIterations(10000);
	p.setKeySize(32);

	// set a salt
	const byte_t	*salt=(const byte_t *)"somesalt";
	p.setSalt(salt,8);

	// derive a key from a password
	const char	*password="hello world";
	p.append((const byte_t *)password,charstring::getLength(password));

	// print the derived key in hexadecimal
	const byte_t	*hashval=p.getHash();
	uint64_t	hashsize=p.getHashSize();

	stdoutput.printf("pbkdf2(\"%s\") = ",password);
	for (uint64_t i=0; i<hashsize; i++) {
		stdoutput.printf("%02x",hashval[i]);
	}
	stdoutput.write('\n');


	// clear and derive from a different password
	p.clear();

	password="goodbye world";
	p.append((const byte_t *)password,charstring::getLength(password));

	hashval=p.getHash();
	hashsize=p.getHashSize();

	stdoutput.printf("pbkdf2(\"%s\") = ",password);
	for (uint64_t i=0; i<hashsize; i++) {
		stdoutput.printf("%02x",hashval[i]);
	}
	stdoutput.write('\n');


	// derive with a different algorithm
	p.reset();

	p.setAlgorithm(PBKDF2_ALGORITHM_SHA512);
	p.setIterations(10000);
	p.setKeySize(64);
	p.setSalt(salt,8);

	password="hello world";
	p.append((const byte_t *)password,charstring::getLength(password));

	hashval=p.getHash();
	hashsize=p.getHashSize();

	stdoutput.printf("pbkdf2-sha512(\"%s\") = ",password);
	for (uint64_t i=0; i<hashsize; i++) {
		stdoutput.printf("%02x",hashval[i]);
	}
	stdoutput.write('\n');
}
Copyright 2017 - David Muse - Contact