Skip to content

Instantly share code, notes, and snippets.

@roustem
Created March 20, 2012 16:42
Show Gist options
  • Save roustem/2138065 to your computer and use it in GitHub Desktop.
Save roustem/2138065 to your computer and use it in GitHub Desktop.
PBKDF2 based on OpenSSL implementation
static int PKCS5_PBKDF2_HMAC(CCHmacAlgorithm algorithm, int digestLength, const char *pass, int passlen,
const unsigned char *salt, int saltlen, int iter,
int keylen, unsigned char *out)
{
unsigned char digtmp[digestLength], *p, itmp[4];
int cplen, j, k, tkeylen;
unsigned long i = 1;
CCHmacContext ctx;
p = out;
tkeylen = keylen;
if (!pass) passlen = 0;
else if (passlen == -1) passlen = strlen(pass);
while (tkeylen) {
if(tkeylen > digestLength) cplen = digestLength;
else cplen = tkeylen;
/* We are unlikely to ever use more than 256 blocks (5120 bits!)
* but just in case...
*/
itmp[0] = (unsigned char)((i >> 24) & 0xff);
itmp[1] = (unsigned char)((i >> 16) & 0xff);
itmp[2] = (unsigned char)((i >> 8) & 0xff);
itmp[3] = (unsigned char)(i & 0xff);
CCHmacInit(&ctx, algorithm, pass, passlen);
CCHmacUpdate(&ctx, salt, saltlen);
CCHmacUpdate(&ctx, itmp, 4);
CCHmacFinal(&ctx, digtmp);
memcpy(p, digtmp, cplen);
for(j = 1; j < iter; j++) {
CCHmac(algorithm, pass, passlen, digtmp, digestLength, digtmp);
for(k = 0; k < cplen; k++) p[k] ^= digtmp[k];
}
tkeylen -= cplen;
i++;
p += cplen;
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment