CryptoExcercise Encryption/Decryption Problem - iphone

I am using apples "cryptoexcercise" (Security.Framework) in my application to encrypt and decrypt a data of numeric value. When I give the input 950,128 the values got encrypted, but it is not getting decrypted and exists with the encrypted value only. This happens only with the mentioned numeric values. Could you please check this issue and give the solution to solve this problem?
here is my code
(void)testAsymmetricEncryptionAndDecryption {
uint8_t *plainBuffer; uint8_t *cipherBuffer; uint8_t *decryptedBuffer;
const char inputString[] = "950"; int len = strlen(inputString);
if (len > BUFFER_SIZE) len = BUFFER_SIZE-1;
plainBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t)); cipherBuffer = (uint8_t *)calloc(CIPHER_BUFFER_SIZE, sizeof(uint8_t)); decryptedBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
strncpy( (char *)plainBuffer, inputString, len);
NSLog(#"plain text : %s", plainBuffer);
[self encryptWithPublicKey:(UInt8 *)plainBuffer cipherBuffer:cipherBuffer];
NSLog(#"encrypted data: %s", cipherBuffer);
[self decryptWithPrivateKey:cipherBuffer plainBuffer:decryptedBuffer];
NSLog(#"decrypted data: %s", decryptedBuffer);
free(plainBuffer); free(cipherBuffer); free(decryptedBuffer); }
(void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer {
OSStatus status = noErr;
size_t plainBufferSize = strlen((char *)plainBuffer); size_t cipherBufferSize = CIPHER_BUFFER_SIZE;
NSLog(#"SecKeyGetBlockSize() public = %d", SecKeyGetBlockSize([self getPublicKeyRef])); // Error handling // Encrypt using the public. status = SecKeyEncrypt([self getPublicKeyRef], PADDING, plainBuffer, plainBufferSize, &cipherBuffer[0], &cipherBufferSize ); NSLog(#"encryption result code: %d (size: %d)", status, cipherBufferSize); NSLog(#"encrypted text: %s", cipherBuffer); }
(void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer { OSStatus status = noErr;
size_t cipherBufferSize = strlen((char *)cipherBuffer);
NSLog(#"decryptWithPrivateKey: length of buffer: %d", BUFFER_SIZE); NSLog(#"decryptWithPrivateKey: length of input: %d", cipherBufferSize);
// DECRYPTION size_t plainBufferSize = BUFFER_SIZE;
// Error handling status = SecKeyDecrypt([self getPrivateKeyRef], PADDING, &cipherBuffer[0], cipherBufferSize, &plainBuffer[0], &plainBufferSize ); NSLog(#"decryption result code: %d (size: %d)", status, plainBufferSize); NSLog(#"FINAL decrypted text: %s", plainBuffer);
}
(SecKeyRef)getPublicKeyRef { OSStatus sanityCheck = noErr; SecKeyRef publicKeyReference = NULL;
if (publicKeyRef == NULL) { NSMutableDictionary *queryPublicKey = [[NSMutableDictionary alloc] init];
// Set the public key query dictionary.
[queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag];
[queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];
// Get the key.
sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);
if (sanityCheck != noErr)
{
publicKeyReference = NULL;
}
[queryPublicKey release];
} else { publicKeyReference = publicKeyRef; }
return publicKeyReference; }
(SecKeyRef)getPrivateKeyRef { OSStatus resultCode = noErr; SecKeyRef privateKeyReference = NULL;
if(privateKeyRef == NULL) { NSMutableDictionary * queryPrivateKey = [[NSMutableDictionary alloc] init];
// Set the private key query dictionary.
[queryPrivateKey setObject:(id)kSecClassKey forKey:(id)kSecClass];
[queryPrivateKey setObject:privateTag forKey:(id)kSecAttrApplicationTag];
[queryPrivateKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];
// Get the key.
resultCode = SecItemCopyMatching((CFDictionaryRef)queryPrivateKey, (CFTypeRef *)&privateKeyReference);
NSLog(#"getPrivateKey: result code: %d", resultCode);
if(resultCode != noErr)
{
privateKeyReference = NULL;
}
[queryPrivateKey release];
} else { privateKeyReference = privateKeyRef; }
return privateKeyReference; }

I am sorry for the late reply... but your example worked perfectly for me, except the fact,
1) for privateTag and publicTag I had to declare
NSData *privateTag = [NSData dataWithBytes:privateKeyIdentifier length:strlen((const char *)privateKeyIdentifier)];
NSData *publicTag = [NSData dataWithBytes:publicKeyIdentifier length:strlen((const char *)privateKeyIdentifier)];
2) and also changing privateKey == NULL rather than privateKeyRef ==NULL in the key reference IF condition..

Related

3des encryption kCCAlignmentError error

I am trying to encrypt an xml string.After the encryption is done then the decrypt the encrypted d I am getting the string as ALIGNMENT.
I dont understand what is the reason
(NSString*) doCipher:(NSString*)plainText:(CCOperation)encryptOrDecrypt {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt)
{
NSData *EncryptData = [NSData dataFromBase64String:plainText];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else
{
plainTextBufferSize = [plainText length];
vplainText = (const void *) [plainText UTF8String];
}
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t iv[kCCBlockSize3DES];
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));
NSString *key = #"123456789012345678901234";
NSString *initVec = #"init Vec";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];
ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
vinitVec, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
//else/
if (ccStatus == kCCParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED";
NSString *result;
if (encryptOrDecrypt == kCCDecrypt)
{
result = [ [NSString alloc] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding];
}
else
{
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64EncodedString];
}
return result;
}
kCCAlignmentError means that the data you are passing is not correctly padded (specifically that the entire data length including padding is not a multiple of the block size). The most likely cause is that you are truncating your encrypted data somewhere, possibly outside of this routine.
You should check your encrypted data at each step and make sure that it is always a multiple of the block size (8 bytes). You'll need to base64-decode before checking the length.

Extracting a public key from key pair in key chain

The Problem: Retrieving a public key
For an iPhone App, I need to create a rsa key pair, store it in the key chain and retrieve the public key.
Fortunately, Apple released a Crypto Exercise Sample where everything i need can be found (class SecKeyWrapper, functions generateKeyPair and getPublicKeyBits).
But after trying to use these functions, I always get the same output for my public key for different key pairs (instead of different public key bits for different key pairs).
Implementation of my generateKeyPair and getPublicKeyBits Function:
I first create a key pair by calling generateKeyPairWithKeySizeInBits (which seems to work fine), afterwards I extract the public key bits with getPublicKeyBits and NSLog them...
- (void) generateKeyPairWithKeySizeInBits:(int)bits withPublicIdentifier:(NSString *)publicIdentifier andPrivateIdentifier:(NSString *)privateIdentifier
{
NSLog(#"begin generating key...");
OSStatus status = noErr;
NSMutableDictionary* privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary* publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary* keyPairAttr = [[NSMutableDictionary alloc] init];
NSData* publicTag = [publicIdentifier dataUsingEncoding:NSUTF8StringEncoding];
NSData* privateTag = [privateIdentifier dataUsingEncoding:NSUTF8StringEncoding];
SecKeyRef publicKey = NULL;
SecKeyRef privateKey = NULL;
[keyPairAttr setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id) kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithInt:bits] forKey:(__bridge id) kSecAttrKeySizeInBits];
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id) kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag forKey:(__bridge id) kSecAttrApplicationTag];
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[keyPairAttr setObject:privateKeyAttr forKey:(__bridge id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(__bridge id)kSecPublicKeyAttrs];
SecItemDelete((__bridge CFDictionaryRef)keyPairAttr);
status = SecKeyGeneratePair((__bridge CFDictionaryRef) keyPairAttr, &publicKey, &privateKey);
if(status != noErr){
NSLog(#"status = %#",status);
}
if(publicKey){
NSLog(#"public key %#",publicKey);
}
if(privateKey){
NSLog(#"private key %#",privateKey);
}
[self getPublicKeyBits:publicIdentifier];
}
- (NSData *)getPublicKeyBits: (NSString*) publicKeyIdentifier {
OSStatus sanityCheck = noErr;
NSData * publicKeyBits = nil;
CFTypeRef pk;
NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
NSData* publicTag = [publicKeyIdentifier dataUsingEncoding:NSUTF8StringEncoding];
// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge_transfer id)kSecClassKey forKey:(__bridge_transfer id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge_transfer id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge_transfer id)kSecAttrKeyTypeRSA forKey:(__bridge_transfer id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge_transfer id)kSecReturnData];
// Get the key bits.
sanityCheck = SecItemCopyMatching((__bridge_retained CFDictionaryRef)queryPublicKey, &pk);
if (sanityCheck != noErr)
{
publicKeyBits = nil;
}
publicKeyBits = (__bridge_transfer NSData*)pk;
NSLog(#"public bits %#",publicKeyBits);
return publicKeyBits;
}
Output (the "public bits"-part (last line) is always the same):
2012-07-13 10:39:28.391 [12279:707] begin generating key...
2012-07-13 10:39:39.376 [12279:707] public key <SecKeyRef: 0xeb56e00>
2012-07-13 10:39:39.381 [12279:707] private key <SecKeyRef: 0xeb57800>
2012-07-13 10:39:39.397 [12279:707] public bits <3082010a 02820101 00ea41ec 12780dff 20a55d67 62ec9890 028ed031 eccd1163 5b4bd039 01adffb5 766f37b8 31be8d03 4a41240b 4e127b75 bc4dd8fb 5b404d4d ad18d711 5cf64a04 61c49970 1fef5434 215f80e4 efee8894 1f282f77 8ea5f7e3 35673260 80ee5f80 818d19d3 b7b15e5c f013ad7d 5ff5dd33 b3e57544 de50dc02 f28aa2ae d4b9590a 1e71bd05 79e81fb7 2a9cd592 cf412fe1 db7a89d4 05bd1731 f95f7aae 56ec4171 e9f352ec c26c3c15 05a0e84b 16c5e89d cec8b1a3 24365d4e dcea88a2 92d8c2e6 8f0e9aee e83703bc e66418af aa9dceea 1129f669 cf069b87 edde4cf7 5e313212 80f44e04 d5b5e2db 9e7f26ae 9b8ef8ee 2e177702 18673b1a f125d3c8 d9ddf978 fb020301 0001>
So Your SecItemDelete code does not work as you expect it to. If you want to delete all the items in your keychain (for testing purposes, obviously), you should look at the code in -[Credentials resetCredentials] method in the AdvancedURLConnections sample code.
https://developer.apple.com/library/ios/#samplecode/AdvancedURLConnections/
You might also find the -dumpCredentials method handy during debugging.
So The problem with SecItemDelete means that SecKeyGeneratePair is generating a new set of keys each time you run the app. Each of these keys has the same application tag, making it indeterminate as to which key is returned by your SecItemCopyMatching call in -getPublicKeyBits:. In turns out that on current system software you're always getting back the first key, so you always get the same public key bits.
Public key will be having two components Exponent and Modulus.You can try this
after getting PublickeyBits method
- (NSData *)getPublicKeyExp
{
NSData* pk = [self getPublicKeyBits];
if (pk == NULL) return NULL;
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
iterator += mod_size;
iterator++; // TYPE - bit stream exp
int exp_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, exp_size)];
return pk;
}
- (NSData *)getPublicKeyMod
{
NSData* pk = [self getPublicKeyBits];
if (pk == NULL) return NULL;
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, mod_size)];
return pk;
NSLog(#"public size: %d",pk.length);
}
- (int)derEncodingGetSizeFrom:(NSData*)buf at:(int*)iterator
{
const uint8_t* data = [buf bytes];
int itr = *iterator;
int num_bytes = 1;
int ret = 0;
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80;
itr++;
}
for (int i = 0 ; i < num_bytes; i++)
ret = (ret * 0x100) + data[itr + i];
*iterator = itr + num_bytes;
return ret;
}

What is best available data encryption algorithm in IOS

i am trying to encrypt my data using before sending it to server, is there any highly secure two way encryption algorithm ? which one is best for this purpose.
Check ths once
Here, key is string variable, declare as a global variable.
add sequrity framework for your code and import
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCryptor.h>
- (void)viewDidLoad
{
[super viewDidLoad];
key=#"Your own key";
// encoding
NSString *encodingString=[[self encrypt:[#"Your String"
dataUsingEncoding:NSUTF8StringEncoding]
base64EncodedString];;
//decoding
NSData *data=[self decrypt:[NSData dataFromBase64String:encryptString]];
NSString *decodingString = [[NSString alloc] initWithBytes:[data bytes] length:
[data length] encoding: NSASCIIStringEncoding];
}
- (NSData *) encrypt:(NSData *) plainText {
return [self transform:kCCEncrypt data:plainText];
}
- (NSData *) decrypt:(NSData *) cipherText {
return [self transform:kCCDecrypt data:cipherText];
}
- (NSData *) transform:(CCOperation) encryptOrDecrypt data:(NSData *) inputData {
// kCCKeySizeAES128 = 16 bytes
// CC_MD5_DIGEST_LENGTH = 16 bytes
NSData* secretKey = [ChipperObject md5:Key];
CCCryptorRef cryptor = NULL;
CCCryptorStatus status = kCCSuccess;
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
status = CCCryptorCreate(encryptOrDecrypt,
kCCAlgorithmAES128,kCCOptionPKCS7Padding,
[secretKey bytes], kCCKeySizeAES128, iv, &cryptor);
if (status != kCCSuccess) {
return nil;
}
size_t bufsize = CCCryptorGetOutputLength(cryptor, (size_t)[inputData length],
true);
void * buf = malloc(bufsize * sizeof(uint8_t));
memset(buf, 0x0, bufsize);
size_t bufused = 0;
size_t bytesTotal = 0;
status = CCCryptorUpdate(cryptor, [inputData bytes], (size_t)[inputData length],
buf, bufsize, &bufused);
if (status != kCCSuccess) {
free(buf);
CCCryptorRelease(cryptor);
return nil;
}
bytesTotal += bufused;
status = CCCryptorFinal(cryptor, buf + bufused, bufsize - bufused, &bufused);
if (status != kCCSuccess) {
free(buf);
CCCryptorRelease(cryptor);
return nil;
}
bytesTotal += bufused;
CCCryptorRelease(cryptor);
return [NSData dataWithBytesNoCopy:buf length:bytesTotal];
}
Here is my code using 3des CCCrypt Method,Find GTMBase64.h from googlecode, https://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMBase64.h?r=87
#import <CommonCrypto/CommonCryptor.h>
#import "GTMBase64.h"
- (NSData*)TripleDES:(NSData*)plainData encryptOrDecrypt:(CCOperation)encryptOrDecrypt key:(NSString*)key {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt)
{
NSData *EncryptData = [GTMBase64 decodeData:plainData];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else
{
plainTextBufferSize = [plainData length];
vplainText = (const void *)[plainData bytes];
}
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t ivkCCBlockSize3DES;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));
// NSString *key = #"123456789012345678901234";
NSString *initVec = #"init Vec";
const void *vkey = (const void *) [key UTF8String];
const void *vinitVec = (const void *) [initVec UTF8String];
ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionPKCS7Padding,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
vinitVec, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else if (ccStatus == kCC ParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED"; */
NSData *result;
if (encryptOrDecrypt == kCCDecrypt)
{
result = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
}
else
{
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [GTMBase64 encodeData:myData];
}
return result;
}
Usage
NSString *inputString = #"good";
//encode
NSData *inputData = [inputString dataUsingEncoding:NSUTF8StringEncoding];
NSData *encriptdata = [self TripleDES:inputData encryptOrDecrypt:kCCEncrypt key:#"ff68f8e82961489a8b14b345"];
NSString *encodeString = [GTMBase64 stringByEncodingData:encriptdata];
NSLog(#"encodeString : %#" ,encodeString);
//decode
NSData *encodeData = [GTMBase64 decodeString:encodeString];
NSData *decodeData = [self TripleDES:encodeData encryptOrDecrypt:kCCDecrypt key:#"ff68f8e82961489a8b14b345"];
NSString *decodeString = [[NSString alloc] initWithBytes:[decodeData bytes] length:[decodeData length] encoding:NSUTF8StringEncoding];
NSLog(#"decodeString : %#" ,decodeString);
Public Key Infrastructure (PKI) offers you a trustworthy way to encrypt data between 2 machines. You can give it a try.
You can use HTTPS, or you can also use RC6 to encrypt your data.

iPhone SDK CCCrypt 3DES and ECB mode always returns PARAM ERROR

I've seen quite a lot of posts about CCCrypt and 3DES on the iPhone at various places around the Net, but there does not seem to be a working example of using it with ECB mode, always with PKCS7Padding.
Does anyone have any working code to encrypt and decrypt a passed string using 3DES and ECB mode using the CCCrypt function?
Currently my code (which I admit came from a site somewhere, I think it was Apple's own developer forums) is as follows:
+ (NSString*)doCipher:(NSString*)plainText action:(CCOperation)encryptOrDecrypt {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt) {
NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else {
//plainTextBufferSize = [plainText length];
//vplainText = (const void *)[plainText UTF8String];
NSData *plainTextData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
plainTextBufferSize = [plainTextData length];
vplainText = [plainTextData bytes];
}
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t ivkCCBlockSize3DES;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));
NSString *key = #"123456789012345678901234";
NSString *initVec = #"init Vec";
const void *vkey = (const void *)[key UTF8String];
const void *vinitVec = (const void *)[initVec UTF8String];
ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionECBMode,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
nil, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else*/ if (ccStatus == kCCParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED";
NSString *result;
if (encryptOrDecrypt == kCCDecrypt) {
result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
}
else {
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64EncodingWithLineLength:movedBytes];
}
return result; }
The above ALWAYS fails with PARAM ERROR.
- (NSData *) encrypt:(NSString *) dataToEncrypt{
NSUInteger data_length= [dataToEncrypt length];
uint8_t input_raw_data[data_length];
//The [dataToEncrypt length] gives the number of chars present in the string.So say there are 10 chars.
//Now,the getBytes needs to get the raw bytes from this i.e. binary NSData.But suppose the encoding was
//full 16 bit encoding then the number of bytes needed wd have been double- 20.But as we are using the
//NSUTF8StringEncoding,the number of byes needed is 1 per char as the chars(even if originally unicode are
//compressed into an 8 bit UTF8 encoding.)
[dataToEncrypt getBytes:&input_raw_data maxLength:data_length usedLength:NULL encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0,data_length) remainingRange:NULL];
//According to the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_encrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL,
input_raw_data, data_length,
buffer, buffer_size,
&num_bytes_encrypted);
NSLog(#"~~num bytes encrypted: %d",num_bytes_encrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data encoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_encrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *) decrypt:(NSData *) dataToDecrypt{
NSUInteger data_length= [dataToDecrypt length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_decrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[dataToDecrypt bytes], data_length, /* input */
buffer, buffer_size, /* output */
&num_bytes_decrypted);
NSLog(#"~~num bytes decrypted: %d",num_bytes_decrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data decoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_decrypted];
}
free(buffer); //free the buffer;
return nil;
}
The above code worked for me, with some changes. The changes are i decelare the moveBytes and bufferPtf as instance variable and did following chandge.
if (encryptOrDecrypt == kCCDecrypt) {
plainTextBufferSize = movedBytes;
vplainText = bufferPtr;
}
else {
plainTextBufferSize = [plainText length];
vplainText = (const void *)[plainText UTF8String];
}
instead base64encoding use nsasciiencoding.

Converting Raw RSA Key value to SecKeyRef Object for Encryption

I have a RSa publicKey value in base64 , how do i convert to SecKeyRef Object without adding to Keychain
Can i add a RSA Raw value to Keychain which is not in X509 format ???
thanks in advance
The following code comes from Apple's CryptoExercise example, in SecKeyWrapper.m. It assumes the "publicKey" NSData object is the binary DER-encoded ASN.1 object, not base-64 encoded. So you'll have to get a base-64 decoder and apply it first. You might also want to read this post in the Apple Developer Forums.
- (SecKeyRef)addPeerPublicKey:(NSString *)peerName keyBits:(NSData *)publicKey {
OSStatus sanityCheck = noErr;
SecKeyRef peerKeyRef = NULL;
CFTypeRef persistPeer = NULL;
LOGGING_FACILITY( peerName != nil, #"Peer name parameter is nil." );
LOGGING_FACILITY( publicKey != nil, #"Public key parameter is nil." );
NSData * peerTag = [[NSData alloc] initWithBytes:(const void *)[peerName UTF8String] length:[peerName length]];
NSMutableDictionary * peerPublicKeyAttr = [[NSMutableDictionary alloc] init];
[peerPublicKeyAttr setObject:(id)kSecClassKey forKey:(id)kSecClass];
[peerPublicKeyAttr setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];
[peerPublicKeyAttr setObject:peerTag forKey:(id)kSecAttrApplicationTag];
[peerPublicKeyAttr setObject:publicKey forKey:(id)kSecValueData];
[peerPublicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnPersistentRef];
sanityCheck = SecItemAdd((CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *)&persistPeer);
// The nice thing about persistent references is that you can write their value out to disk and
// then use them later. I don't do that here but it certainly can make sense for other situations
// where you don't want to have to keep building up dictionaries of attributes to get a reference.
//
// Also take a look at SecKeyWrapper's methods (CFTypeRef)getPersistentKeyRefWithKeyRef:(SecKeyRef)key
// & (SecKeyRef)getKeyRefWithPersistentKeyRef:(CFTypeRef)persistentRef.
LOGGING_FACILITY1( sanityCheck == noErr || sanityCheck == errSecDuplicateItem, #"Problem adding the peer public key to the keychain, OSStatus == %d.", sanityCheck );
if (persistPeer) {
peerKeyRef = [self getKeyRefWithPersistentKeyRef:persistPeer];
} else {
[peerPublicKeyAttr removeObjectForKey:(id)kSecValueData];
[peerPublicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];
// Let's retry a different way.
sanityCheck = SecItemCopyMatching((CFDictionaryRef) peerPublicKeyAttr, (CFTypeRef *)&peerKeyRef);
}
LOGGING_FACILITY1( sanityCheck == noErr && peerKeyRef != NULL, #"Problem acquiring reference to the public key, OSStatus == %d.", sanityCheck );
[peerTag release];
[peerPublicKeyAttr release];
if (persistPeer) CFRelease(persistPeer);
return peerKeyRef;
}
In case someone comes across this question and is looking for the Cocoa answer:
NSData *privateKeyPEMData = [privateKeyPEM dataUsingEncoding:NSUTF8StringEncoding];
CFArrayRef imported = NULL;
SecKeychainRef importedKeychain = NULL;
OSStatus err = 0;
SecExternalFormat format = kSecFormatOpenSSL;
SecKeyRef privateKey = NULL;
[privateKeyString dataUsingEncoding:NSUTF8StringEncoding];
err = SecItemImport((__bridge CFDataRef)(privateKeyPEMData), (CFStringRef)#"pem", &format, NULL, kNilOptions, kNilOptions, importedKeychain, &imported);
NSLog(#"%# ERROR: %#", self.class, [NSError errorWithDomain:NSOSStatusErrorDomain code:err userInfo:nil]);
assert(err == errSecSuccess);
assert(CFArrayGetCount(imported) == 1);
privateKey = (SecKeyRef)CFArrayGetValueAtIndex(imported, 0);