Skip to content

Instantly share code, notes, and snippets.

@lukhnos
Created July 19, 2012 05:25
Show Gist options
  • Save lukhnos/3140946 to your computer and use it in GitHub Desktop.
Save lukhnos/3140946 to your computer and use it in GitHub Desktop.
An example of using CommonCrypto's PBKDF2 function
// an example of using CommonCrypto's PBKDF2 function
//
// build with:
//
// clang -o pbkdf2test pbkdf2test.c
//
// test with:
//
// ./pbkdf2test <some plaintext password here>
//
// note that an arbitary salt is used (64-bit 0's)
// you actually need to use crpytographically secure pseudo-random number
//
#include <stdio.h>
#include <CommonCrypto/CommonKeyDerivation.h>
int main(int argc, const char * argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: CrpytoTest password\n");
return 1;
}
// 64-bit of salt; in reality, this needs to be a crpytographically secure pseudo-random number
uint8_t salt[8] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
uint8_t derivedKey[8];
int j;
for (j = 0; j <= 1000; j+= 100) {
bzero(derivedKey, sizeof(derivedKey));
int result = CCKeyDerivationPBKDF(kCCPBKDF2, argv[1], strlen(argv[1]), salt, sizeof(salt), kCCPRFHmacAlgSHA256, j, derivedKey, sizeof(derivedKey));
printf("%d rounds, result: %d, key: ", j, result);
for (int i = 0; i < sizeof(derivedKey); i++) {
printf("%02x ", derivedKey[i]);
}
printf("\n");
}
// remember to store the derived key along with the salt
for (j = 0; j <= 2000; j+= 100) {
uint rounds = CCCalibratePBKDF(kCCPBKDF2, strlen(argv[1]), sizeof(salt), kCCPRFHmacAlgSHA256, sizeof(derivedKey), j);
printf("recommended rounds for %d msecs of delay: %u\n", j, rounds);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment