Skip to content

Instantly share code, notes, and snippets.

@graetzer
Created September 19, 2014 22:25
Show Gist options
  • Save graetzer/7653606a5652fd592c8b to your computer and use it in GitHub Desktop.
Save graetzer/7653606a5652fd592c8b to your computer and use it in GitHub Desktop.
Provides HKDF with sha256 as hash function
#import <CommonCrypto/CommonCrypto.h>
// ...
NSData * HKDF_SHA256(NSData *seed, NSData *info, NSData *salt, int outputSize) {
char prk[kCCHmacAlgSHA256] = {0};
CCHmac(CC_SHA256_DIGEST_LENGTH, [salt bytes], [salt length], [seed bytes], [seed length], prk);
int iterations = (int)ceil((double)outputSize/(double)CC_SHA256_DIGEST_LENGTH);
NSData *mixin = [NSData data];
NSMutableData *results = [NSMutableData data];
for (int i=0; i<iterations; i++) {
CCHmacContext ctx;
CCHmacInit(&ctx, kCCHmacAlgSHA256, prk, CC_SHA256_DIGEST_LENGTH);
CCHmacUpdate(&ctx, [mixin bytes], [mixin length]);
if (info != nil) {
CCHmacUpdate(&ctx, [info bytes], [info length]);
}
unsigned char c = i+1;
CCHmacUpdate(&ctx, &c, 1);
unsigned char T[CC_SHA256_DIGEST_LENGTH];
memset(T, 0, CC_SHA256_DIGEST_LENGTH);
CCHmacFinal(&ctx, T);
NSData *stepResult = [NSData dataWithBytes:T length:sizeof(T)];
[results appendData:stepResult];
mixin = [stepResult copy];
}
return [NSData dataWithData:results];
}
@ywang7
Copy link

ywang7 commented Oct 27, 2015

line 5 should be char prk[CC_SHA256_DIGEST_LENGTH] and line 6 CCHmac(kCCHmacAlgSHA256... maybe a typo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment