Skip to content

Instantly share code, notes, and snippets.

@marsepu
Created October 10, 2012 17:00
Show Gist options
  • Select an option

  • Save marsepu/3866910 to your computer and use it in GitHub Desktop.

Select an option

Save marsepu/3866910 to your computer and use it in GitHub Desktop.
Triple DES Key creation example using CommonCrypto Library
#import <CommonCrypto/CommonKeyDerivation.h>
#import <CommonCrypto/CommonCryptor.h>
- (NSData *)derivedKeyFromPassword:(NSString*)password salt:(NSData*)saltData length:(NSUInteger)keyLength
{
NSMutableData *derivedKey = [NSMutableData dataWithLength:keyLength];
int result = CCKeyDerivationPBKDF(kCCPBKDF2, // algorithm
password.UTF8String, // password
password.length, // passwordLength
saltData.bytes, // salt
saltData.length, // saltLen
kCCPRFHmacAlgSHA256, // PRF
10000, // rounds
derivedKey.mutableBytes, // derivedKey
keyLength); // derivedKeyLen
if (result != kCCSuccess) {
NSError *error = [NSError errorWithDomain:@"com.your_domain.your_project_name.your_class_name" code:result userInfo:nil];
NSLog(@"error: %@", error);
return nil;
}
return derivedKey;
}
- (NSData *)randomDataOfLength:(size_t)length
{
NSMutableData *data = [NSMutableData dataWithLength:length];
int result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes);
if (result != 0) return nil;
return data;
}
- (void)tripleDesKeyCreation
{
NSString *password = @"asdfQWER1234!@#$";
NSUInteger keyLength = kCCKeySize3DES;
NSUInteger saltLength = 8;
NSData *saltData = [self randomDataOfLength:saltLength];
NSData *derivedKey = [self derivedKeyFromPassword:password salt:saltData length:keyLength];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment