Created
October 10, 2012 17:00
-
-
Save marsepu/3866910 to your computer and use it in GitHub Desktop.
Triple DES Key creation example using CommonCrypto Library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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