Skip to content

Instantly share code, notes, and snippets.

@graetzer
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graetzer/b9b465e7813d20ba53df to your computer and use it in GitHub Desktop.
Save graetzer/b9b465e7813d20ba53df to your computer and use it in GitHub Desktop.
Generate keys from passwords using PBKDF2-HMAC-SHA256
#import <CommonCrypto/CommonCrypto.h>
// ...
// http://www.opensource.apple.com/source/OpenSSL/OpenSSL-12/openssl/crypto/evp/p5_crpt2.c
// This is the method specified by RSA's PKCS #5 standard.
// Compatible to https://github.com/bitwiseshiftleft/sjcl/blob/master/core/pbkdf2.js
NSData * PBKDF2_HMAC_SHA256(NSData *data,NSData *salt, int iter, int keylen) {
unsigned char digtmp[CC_SHA256_DIGEST_LENGTH], *p, *buffer, itmp[4];
NSInteger cplen, j, k, tkeylen;
unsigned long i = 1;
CCHmacContext hctx;
tkeylen = keylen;
buffer = calloc(keylen, sizeof(unsigned char));
p = buffer;
while(tkeylen) {
if(tkeylen > CC_SHA256_DIGEST_LENGTH) cplen = CC_SHA256_DIGEST_LENGTH;
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(&hctx, kCCHmacAlgSHA256, data.bytes, data.length);
CCHmacUpdate(&hctx, salt.bytes, salt.length);
CCHmacUpdate(&hctx, itmp, 4);
CCHmacFinal(&hctx, digtmp);
memcpy(p, digtmp, cplen);
for(j = 1; j < iter; j++) {
CCHmac(kCCHmacAlgSHA256, data.bytes, data.length,
digtmp, CC_SHA256_DIGEST_LENGTH, digtmp);
for(k = 0; k < cplen; k++) p[k] ^= digtmp[k];
}
tkeylen-= cplen;
i++;
p+= cplen;
}
return [NSData dataWithBytesNoCopy:buffer length:keylen];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment