12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- #import <CommonCrypto/CommonCryptor.h>
- #import <CommonCrypto/CommonDigest.h>
- #import <CommonCrypto/CommonKeyDerivation.h>
- #import "PBKDF2.h"
- @implementation PBKDF2
- + (NSString *) toHex:(NSData *)nsdata {
- NSString * hexStr = [NSString stringWithFormat:@"%@", nsdata];
- for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
- hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
- return hexStr;
- }
- + (NSMutableData *) fromHex:(NSString *)str {
- const char *chars = [str UTF8String];
- int i = 0, len = str.length;
- NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
- char byteChars[3] = {'\0','\0','\0'};
- unsigned long wholeByte;
- while (i < len) {
- byteChars[0] = chars[i++];
- byteChars[1] = chars[i++];
- wholeByte = strtoul(byteChars, NULL, 16);
- [data appendBytes:&wholeByte length:1];
- }
- return data;
- }
- + (NSString *) derivationKey:(NSString *)password salt: (NSString *)salt iterations: (nonnull int *)iterations {
- // Data of String to generate Hash key(hexa decimal string).
- NSData *passwordData = [self fromHex:password];
- NSData *saltData = [self fromHex:salt];
- // Hash key (hexa decimal) string data length.
- NSMutableData *hashKeyData = [NSMutableData dataWithLength:CC_SHA512_DIGEST_LENGTH];
- // Key Derivation using PBKDF2 algorithm.
- int status = CCKeyDerivationPBKDF(
- kCCPBKDF2,
- passwordData.bytes,
- passwordData.length,
- saltData.bytes,
- saltData.length,
- kCCPRFHmacAlgSHA512,
- iterations,
- hashKeyData.mutableBytes,
- hashKeyData.length);
- if (status == kCCParamError) {
- NSLog(@"Key derivation error");
- return @"";
- }
- return [self toHex:hashKeyData];
- }
- @end
|