PBKDF2.m 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #import <CommonCrypto/CommonCryptor.h>
  2. #import <CommonCrypto/CommonDigest.h>
  3. #import <CommonCrypto/CommonKeyDerivation.h>
  4. #import "PBKDF2.h"
  5. @implementation PBKDF2
  6. + (NSString *) toHex:(NSData *)nsdata {
  7. NSString * hexStr = [NSString stringWithFormat:@"%@", nsdata];
  8. for(NSString * toRemove in [NSArray arrayWithObjects:@"<", @">", @" ", nil])
  9. hexStr = [hexStr stringByReplacingOccurrencesOfString:toRemove withString:@""];
  10. return hexStr;
  11. }
  12. + (NSMutableData *) fromHex:(NSString *)str {
  13. const char *chars = [str UTF8String];
  14. int i = 0, len = str.length;
  15. NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
  16. char byteChars[3] = {'\0','\0','\0'};
  17. unsigned long wholeByte;
  18. while (i < len) {
  19. byteChars[0] = chars[i++];
  20. byteChars[1] = chars[i++];
  21. wholeByte = strtoul(byteChars, NULL, 16);
  22. [data appendBytes:&wholeByte length:1];
  23. }
  24. return data;
  25. }
  26. + (NSString *) derivationKey:(NSString *)password salt: (NSString *)salt iterations: (nonnull int *)iterations {
  27. // Data of String to generate Hash key(hexa decimal string).
  28. NSData *passwordData = [self fromHex:password];
  29. NSData *saltData = [self fromHex:salt];
  30. // Hash key (hexa decimal) string data length.
  31. NSMutableData *hashKeyData = [NSMutableData dataWithLength:CC_SHA512_DIGEST_LENGTH];
  32. // Key Derivation using PBKDF2 algorithm.
  33. int status = CCKeyDerivationPBKDF(
  34. kCCPBKDF2,
  35. passwordData.bytes,
  36. passwordData.length,
  37. saltData.bytes,
  38. saltData.length,
  39. kCCPRFHmacAlgSHA512,
  40. iterations,
  41. hashKeyData.mutableBytes,
  42. hashKeyData.length);
  43. if (status == kCCParamError) {
  44. NSLog(@"Key derivation error");
  45. return @"";
  46. }
  47. return [self toHex:hashKeyData];
  48. }
  49. @end