Created
October 8, 2012 18:28
-
-
Save marsepu/3854078 to your computer and use it in GitHub Desktop.
Triple DES encryption example using the CommonCrypto Library
This file contains 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/CommonCryptor.h> | |
#warning ADD Security.framework to your project | |
+ (NSData *)tripleDesEncryptData:(NSData *)inputData | |
key:(NSData *)keyData | |
error:(NSError **)error | |
{ | |
NSParameterAssert(inputData); | |
NSParameterAssert(keyData); | |
size_t outLength; | |
NSAssert(keyData.length == kCCKeySize3DES, @"the keyData is an invalid size"); | |
NSMutableData *outputData = [NSMutableData dataWithLength:(inputData.length + kCCBlockSize3DES)]; | |
CCCryptorStatus | |
result = CCCrypt(kCCEncrypt, // operation | |
kCCAlgorithm3DES, // Algorithm | |
0, // options | |
keyData.bytes, // key | |
keyData.length, // keylength | |
nil,// iv | |
inputData.bytes, // dataIn | |
inputData.length, // dataInLength, | |
outputData.mutableBytes, // dataOut | |
outputData.length, // dataOutAvailable | |
&outLength); // dataOutMoved | |
if (result != kCCSuccess) { | |
if (error != NULL) { | |
*error = [NSError errorWithDomain:@"com.your_domain.your_project_name.your_class_name." | |
code:result | |
userInfo:nil]; | |
} | |
return nil; | |
} | |
[outputData setLength:outLength]; | |
return outputData; | |
} |
Notice that I'm passing zero for "options" parameter for the CCCrypt method. You could specify kCCOptionPKCS7Padding or kCCOptionECBMode instead. Look in CommonCryptor.h for details.
to decrypt just change kCCEncrypt to kCCDecrypt
From where I can get CommonCrypto File
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Notice that the Initialization Vector (iv) is nil in this example.