Skip to content

Instantly share code, notes, and snippets.

@marsepu
Created October 8, 2012 18:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marsepu/3854078 to your computer and use it in GitHub Desktop.
Save marsepu/3854078 to your computer and use it in GitHub Desktop.
Triple DES encryption example using the CommonCrypto Library
#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;
}
@marsepu
Copy link
Author

marsepu commented Oct 8, 2012

Notice that the Initialization Vector (iv) is nil in this example.

@marsepu
Copy link
Author

marsepu commented Oct 8, 2012

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.

@marsepu
Copy link
Author

marsepu commented Oct 8, 2012

to decrypt just change kCCEncrypt to kCCDecrypt

@Jitender-k123
Copy link

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