reading certificate from a smart card in Xcode using objective-C - iphone

I'm new to Objective-C coding and for smart card programming as well. I'm developing application for iPhone. I found a difficulty reading a file from a smart card using iSmartSDK it returns NULL, though the selection of Applet is successful.
Does anyone faced such problem or know about this ? thanks
t0Command.classByte = 0;
t0Command.instructionByte = 0xCB;
t0Command.parameter1Byte = 0x3F;
t0Command.parameter2Byte = 0xFF;
t0Command.dataBytes = nil;
t0Command.lengthByte = t0Command.dataBytes.length;
t0Command.expectedResponseLengthByte = 0x7F;
t0Command.dataBytes = [self hexStringToBytes:#"5C035FC105"];
t0Command.commandId = READ_WRITE_CPU_CARD_COMMAND_ID;
resultCommand = [iSmartInstance sendCommandToCPUCard:t0Command];
if (resultCommand == nil) {
[self displayMessage:#"Read Binary Failed"];
}
else{
[self displayMessage:[NSString stringWithFormat:#"Read Status: %02x%02x", ((T0Command*)resultCommand).status1Byte, ((T0Command*)resultCommand).status2Byte]];
[self displayMessage:[NSString stringWithFormat:#"Response Length: %d", ((T0Command*)resultCommand).dataBytes.length]];
NSString *readBytes = [[[NSString alloc] initWithBytes:((T0Command*)resultCommand).dataBytes.bytes
length:((T0Command*)resultCommand).dataBytes.length
encoding:NSASCIIStringEncoding] autorelease];
[self displayMessage:[NSString stringWithFormat:#"Read Value: %# \n Bytes: %#", readBytes, ((T0Command*)resultCommand).dataBytes.bytes]];
}

Related

Works on iOS Simulator but not on iOS device?

EDIT: It works but it takes amazingly long to complete.
Is this normal, or is there a way to optimize it?
Thanks
I am using DDUnitConverter in my project to convert currencies.
Everything works perfectly fine on the iOS Simulator but hangs when I try to convert the currencies on my iOS Device (iPhone 4 iOSv5.1). I looked around to find a fix to this issue but could not find anything. Here is the code that I use to exchange the currencies. The code within the DDUnitConverter is available here: https://github.com/davedelong/DDUnitConverter/downloads
if ([Number.text isEqualToString:#""] || [picklable.text isEqualToString:#"no selection"] || [picklable2.text isEqualToString:#"no selection"]) {
return;
}
if ([Number.text isEqualToString:#"0"]) {
Result.text = #"0";
return;
}
int fromType;
int toType;
fromType = [list indexOfObject:picklable.text];
toType = [list indexOfObject:picklable2.text];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * from = [[f numberFromString:Number.text] retain];
[f release];
NSNumber *to = [[[DDUnitConverter currencyUnitConverter] convertNumber:from fromUnit:fromType toUnit:toType] retain];
float toto = [to floatValue];
Result.text = [NSString stringWithFormat:#"%.4f %#", toto, picklable2.text];
if ((toto == 0 || toto == [Number.text floatValue]) && picklable.text != picklable2.text ) {
Result.text = #"No Internet Connection or Previous Data";
}
[from release];
[to release];
[Result flashScrollIndicators];
Hopefully someone can help me out,
Thanks
Your code seems OK to me, but you are using DDUnitConverter. I've never used it, but I suppose it needs internet connection to load data from the internet. If the server take long time to answer, your app could hang on connection.
You can try to connect to the server asynchronously using dispatch_async, this lets your app download data in background.
Anything taking amazingly long to do should be dispatched. Like this:
dispatch_async(dispatch_get_global_queue(), ^(void) {
[self doReallyAmazinglyComplicatedProcessing];
});

Stuck/leak when allocating data for NSData?

I'm stuck at this method and I don't know why!
Can anyone point me to some source code?
Thank you so much!
This is my source code:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
.......
readData = [readFileHandle readDataOfLength:defaultLen]
NSData *decryptedData = nil;
//check is last buffer of file
NSUInteger exLen = [readData length] % 16;
NSUInteger decryptionLen = [readData length] - exLen;
NSData *dataForDecryption = nil;
if(exLen != 0)
{
stuck at here-> [readData getBytes:dataForDecryption length:decryptionLen];
//
decryptedData = [dataForDecryption AES256DecryptWithKey:KEY];
self.isEndOfFile = YES;
}
else
decryptedData = [readData AES256DecryptWithKey:KEY];
[readFileHandle closeFile];
.......
[pool drain];
I've used some functions such as:
NSData *dataForDecryption = [[[NSData alloc] initWithBytes:readData length:decryptionLen]autorelease];
NSData *dataForDecryption = [NSData dataWithBytes:readData length:decryptionLen];
But I get the same error.
When i'm using
dataForDecryption = [readFileHandle readDataOfLength:decryptionLen];
it's stuck at pos above and the size read is 0, although it's not EOF.
Thanks
stuck at here-> [readData getBytes:dataForDecryption length:decryptionLen];
You're passing dataForDecryption, which is a NSData*, but the parameter is supposed to be a buffer, i.e. void*. If you want a NSData*, you should instead use a method like subdataWithRange:.
dataForEncryption = [readData subdataWithRange:NSRangeMake(0, decryptionLen)];

How to get information about free memory and running processes in an App Store approved app? (Yes, there is one!)

There is an app called "Activity Monitor Touch" in the App Store, which displays background processes as well as free memory.
So there MUST be an public API to access this information. The evidence:
I'm already searching for days but can't find any good starting point. How can this app figure all this stuff out without any jailbreaking / hacking / etc.?
Until recently I was sure that something like this is absolutely impossible on iOS.
I've found this code snippet:
- (NSArray *)runningProcesses {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t miblen = 4;
size_t size;
int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
free(process);
}
return nil;
}
process = newprocess;
st = sysctl(mib, miblen, process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0){
if (size % sizeof(struct kinfo_proc) == 0){
int nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (int i = nprocess - 1; i >= 0; i--){
NSString * processID = [[NSString alloc] initWithFormat:#"%d", process[i].kp_proc.p_pid];
NSString * processName = [[NSString alloc] initWithFormat:#"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:#"ProcessID", #"ProcessName", nil]];
[processID release];
[processName release];
[array addObject:dict];
[dict release];
}
free(process);
return [array autorelease];
}
}
}
return nil;
}
But I can't make it run on the iPhone. Xcode doesn't know these symbols:
CTL_KERN, KERN_PROC, KERN_PROC_ALL
So of course I must import a header file or library. Does anyone know where these belong to, and how the headers must be imported to make this work?
Works like a charm:
#import <sys/sysctl.h>
sysctl is no longer accessible to sandboxed iOS 9 apps.
From WWDC 2015 session 703 Privacy and Your App:
In iOS 9, the sandbox now prevents a process from accessing the
kern.proc, kern.procargs, and kern.procargs2 values for other
processes
and
iOS apps are not permitted to see what other apps are running
So even if you find a way, you are likely to get rejected from the App Store.
https://developer.apple.com/videos/play/wwdc2015-703/

Memory leaks in iphone application

Hi, guys! i'm newbie in iphone development. I have problems with the memory leak. I have such code.
do {
int s = sqlite3_step(statement);
switch (s) {
case SQLITE_ROW:{
Article *a = [[[Article alloc] init] autorelease];
for (int i = 0; i < columnCount; i++) {
const char *columnName = sqlite3_column_name(statement, i);
if(strncmp(columnName, "title", strlen("title")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if(colStr != NULL)
a.title = [[[NSString alloc] initWithCString: colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
if(strncmp(columnName, "author", strlen("author")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if(colStr != NULL)
a.author = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
if(strncmp(columnName, "description", strlen("description")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if(colStr != NULL)
a.description = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
if(strncmp(columnName, "link", strlen("link")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if (colStr)
a.link = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
if(strncmp(columnName, "imageUrl", strlen("imageUrl")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if (colStr)
a.imageUrl = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
if(strncmp(columnName, "pubDate", strlen("pubDate")) == 0){
const char* colStr = (char*)sqlite3_column_text(statement, i);
if(colStr)
a.pubDate = [[[NSString alloc] initWithCString:colStr encoding:NSUTF8StringEncoding] autorelease];
continue;
}
}
[array insertObject:a atIndex:0];
}
break;
case SQLITE_DONE:
sqlite3_finalize(statement);
dataForReadingAvailable = NO;
break;
default:{
NSLog(#"getArticlesForFeed:sqlite3_step failed.Error:%s",sqlErrMsg);
return nil;
}
break;
}
}while(dataForReadingAvailable);
Tools from Xcode shows that i have leak memory when i a'm allocated object and when i initialized it properties. But why it's happens. All objects is autorealeased, so i think that will not to be such situation.
Thanks.
I think perhaps you overwrite the allocated memory with the new pointer somewhere.
I would replace
Article *a = [[[Article alloc] init] autorelease];
with
Article *a = [[Article alloc] init];
//some code
[a release]; //when you don't need it anymore
This is not a good practice to use autorelease much. It can even slow down your app btw in case of many objects.
And the strings like
a.title = [[[NSString alloc] initWithCString: colStr encoding:NSUTF8StringEncoding] autorelease];
I would replace with
a.title = [NSString stringWithCString:colStr encoding:NSUTF8StringEncoding];
In this case you also rely on autorelease pool, but it's much simpler.
EDIT:
Indeed, your 'Article' allocation is in the do-while loop.
In string [array insertObject:a atIndex:0]; your aray retains object and you don't need it anymore, but you rely on autorelease. Analyzer (or what tool you're using) sees, that you placed allocation in the cycle's body without releasing it after each iteration. This way, on the second iteration of the loop, you overwrite your "a" object, loosing the old pointer and leaking memory this way (pool won't find this pointer, since "a" overwritten). Even if you pass your loop only once, the analyzer does not care and gives you a warning.

Debug build works beautifully, ad hoc build crashes hard

I'm working with the EXIF library at http://code.google.com/p/iphone-exif/ and I have come across a real head scratcher of a bug. When I implement the library in a debug build everything works beautifully, but when I compile for ad hoc beta testing the app crashes hard.
I'm getting the following error:
Exception Type: EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x00000000
Crashed Thread: 5
With Thread 5:
0 Gaia GPS 0x000494e4 -[EXFJpeg scanImageData:] (EXFJpeg.m:372)
1 Gaia GPS 0x0000524c -[MyAppDelegate saveImage:] (MyAppDelegate.m:935)
2 Foundation 0x317fef32 0x317ad000 + 335666
3 Foundation 0x317ae09a 0x317ad000 + 4250
4 libSystem.B.dylib 0x329c892a 0x329a4000 + 149802
It is my suspicion that there is something different about the way the debug build handles memory vs. the way the ad-hoc build handles memory. It seems to me from the error that this code is trying to write to memory blocks it does not have access to, and when it does the Ad-hoc iPhone OS shuts the process down.
What would cause this behavior in the ad hoc distribution, but not in the debug build? The debug build works fine even when the phone is disconnected and the debugger off.
Many thanks in advance.
The code:
My Code to implement the library (Line 935 is the first line of this block, the alloc statment)
:
EXFJpeg* jpegScanner = [[EXFJpeg alloc] init];
[jpegScanner scanImageData:imgData];
CLLocation *location = self.gps.lastReading ? self.gps.lastReading : [self.gps.locationManager location];
[location retain];
NSMutableArray* locArray = [self createLocArray:location.coordinate.latitude];
EXFGPSLoc* gpsLoc = [[EXFGPSLoc alloc] init];
[self populateGPS: gpsLoc :locArray];
[jpegScanner.exifMetaData addTagValue:gpsLoc forKey:[NSNumber numberWithInt:EXIF_GPSLatitude];
[gpsLoc release];
locArray = [self createLocArray:location.coordinate.longitude];
gpsLoc = [[EXFGPSLoc alloc] init];
[self populateGPS: gpsLoc :locArray];
[locArray release];
[jpegScanner.exifMetaData addTagValue:gpsLoc forKey:[NSNumber numberWithInt:EXIF_GPSLongitude];
[gpsLoc release];
NSString *ref = (location.coordinate.latitude <0.0)?ref = #"S": #"N";
[jpegScanner.exifMetaData addTagValue: ref forKey:[NSNumber numberWithInt:EXIF_GPSLatitudeRef] ];
ref = (location.coordinate.longitude <0.0)? #"W": #"E";
[jpegScanner.exifMetaData addTagValue: ref forKey:[NSNumber numberWithInt:EXIF_GPSLongitudeRef]];
[jpegScanner.exifMetaData addTagValue: #"Apple" forKey:[NSNumber numberWithInt:EXIF_Make];
[jpegScanner.exifMetaData addTagValue: #"iPhone" forKey:NSNumber numberWithInt:EXIF_Model];
[jpegScanner.exifMetaData addTagValue:[NSNumber numberWithInt:0] forKey:[NSNumber numberWithInt:EXIF_GPSAltitudeRef] ];
NSArray *arr = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:0], NSNumber numberWithInt:0], [NSNumber numberWithInt:2], [NSNumber numberWithInt:2], nil];
[jpegScanner.exifMetaData addTagValue: arr forKey:[NSNumber numberWithInt:EXIF_GPSVersion] ];
[arr release];
long numDenumArray[2];
long* arrPtr = numDenumArray;
[EXFUtils convertRationalToFraction:&arrPtr: [NSNumber numberWithDouble:location.altitude]];
EXFraction *fract = [[EXFraction alloc] initWith:numDenumArray[0] :numDenumArray[1]];
[jpegScanner.exifMetaData addTagValue:fract forKey:[NSNumber
numberWithInt:EXIF_GPSAltitude] ];
NSMutableData *newData = [[NSMutableData alloc] init];
[jpegScanner populateImageData:newData];
[jpegScanner release];
And last but not lest the function from the library itself:
-(void) scanImageData: (NSData*) jpegData {
Debug(#"Starting scan headers");
// pointer to the end of the EXIF Data and the start of the rest of the image
ByteArray* endOfEXFPtr;
imageLength = CFDataGetLength((CFDataRef)jpegData);
// CFRetain(&imageLength);
Debug(#"Length of image %i", imageLength);
imageBytePtr = (UInt8 *) CFDataGetBytePtr((CFDataRef)jpegData);
imageStartPtr = imageBytePtr;
// check if a valid jpeg file
UInt8 val = [self readNextbyte];
if (val != M_BEG){
Debug(#"Not a valid JPEG File");
return;
}
val = [self readNextbyte];
if (val != M_SOI){
Debug(#"Not a valid start of image JPEG File");
return;
}
// increment this to position after second byte
BOOL finished =FALSE;
while(!finished){
// increment the marker
val = [self nextMarker];
Debug(#"Got next marker %x at byte count %i", val, (imageBytePtr - imageStartPtr));
switch(val){
case M_SOF0: /* Baseline */
case M_SOF1: /* Extended sequential, Huffman */
case M_SOF2: /* Progressive, Huffman */
case M_SOF3: /* Lossless, Huffman */
case M_SOF5: /* Differential sequential, Huffman */
case M_SOF6: /* Differential progressive, Huffman */
case M_SOF7: /* Differential lossless, Huffman */
case M_SOF9: /* Extended sequential, arithmetic */
case M_SOF10: /* Progressive, arithmetic */
case M_SOF11: /* Lossless, arithmetic */
case M_SOF13: /* Differential sequential, arithmetic */
case M_SOF14: /* Differential progressive, arithmetic */
case M_SOF15: /* Differential lossless, arithmetic */
// Remember the kind of compression we saw
{
int compression = *imageBytePtr; // <-----------LINE 372
self.exifMetaData.compression = compression;
// Get the intrinsic properties fo the image
[self readImageInfo];
}
break;
case M_SOS: /* stop before hitting compressed data */
Debug(#"Found SOS at %i", imageBytePtr - imageStartPtr);
// [self skipVariable];
// Update the EXIF
// updateExif();
finished = TRUE;
break;
case M_EOI: /* in case it's a tables-only JPEG stream */
Debug(#"End of Image reached at %i ", imageBytePtr - imageStartPtr);
finished =TRUE;
break;
case M_COM:
Debug(#"Got com at %i",imageBytePtr - imageStartPtr);
break;
case M_APP0:
case M_APP1:
case M_APP2:
case M_APP3:
case M_APP4:
case M_APP5:
case M_APP6:
case M_APP7:
case M_APP8:
case M_APP9:
case M_APP10:
case M_APP11:
case M_APP12:
case M_APP13:
case M_APP14:
case M_APP15:
// Some digital camera makers put useful textual
// information into APP1 and APP12 markers, so we print
// those out too when in -verbose mode.
{
Debug(#"Found app %x at %i", val, imageBytePtr - imageStartPtr);
NSData* commentData = [self processComment];
NSNumber* key = [[NSNumber alloc]initWithInt:val];
// add comments to dictionary
[self.keyedHeaders setObject:commentData forKey:key];
[key release];
// will always mark the end of the app_x block
endOfEXFPtr = imageBytePtr;
// we pass a pointer to the NSData pointer here
if (val == M_APP0){
Debug(#"Parsing JFIF APP_0 at %i", imageBytePtr - imageStartPtr);
[self parseJfif:(CFDataRef*)&commentData];
} else if (val == M_APP1){
[self parseExif:(CFDataRef*)&commentData];
Debug(#"Finished App1 at %i", endOfEXFPtr - imageStartPtr);
} else if (val == M_APP2){
Debug(#"Finished APP2 at %i", imageBytePtr - imageStartPtr);
}else{
Debug(#"Finished App &x at %i", val, imageBytePtr - imageStartPtr);
}
}
break;
case M_SOI:
Debug(#"SOI encountered at %i",imageBytePtr - imageStartPtr);
break;
default: // Anything else just gets skipped
Debug(#"NOt handled %x skipping at %i",val, imageBytePtr - imageStartPtr);
[self skipVariable]; // we assume it has a parameter count...
break;
}
}
// add in the bytes after the exf block
NSData* theRemainingdata = [[NSData alloc] initWithBytes:endOfEXFPtr length:imageLength - (endOfEXFPtr - imageStartPtr)];
self.remainingData = theRemainingdata;
[theRemainingdata release];
endOfEXFPtr = NULL;
imageStartPtr = NULL;
imageBytePtr = NULL;
}
I got this same problem a while ago, and found 2 solutions (or workarounds):
Use the precompiled library from http://code.google.com/p/iphone-exif/downloads/list instead of compiling from the source
Change line 1270 of EXFMetaData.m to:
CFDataGetBytes(*exifData, CFRangeMake(6,2), order);
as suggested here: http://code.google.com/p/iphone-exif/issues/detail?id=4&can=1
Patched IT :
Write this code in te file EXFJpeg.m at row 330
if (!imageBytePtr)
return;
Just before
UInt8 val = [self readNextbyte];
THAT'S ALL !!!!