2012-10-30 35 views
0

我正在開發一個iOS應用程序,並努力從.p12證書中提取標識。我對objective-c仍然陌生,所以我確定缺少重要的東西。下面的代碼:iOS提取證書標識:EXC_BAD_ACCESS

@implementation P12Extractor 

-(SecIdentityRef)getIdentity{ 
NSString *path = [[NSBundle mainBundle] pathForResource:@"ServerCert" ofType:@"p12"]; 
NSData *p12data = [NSData dataWithContentsOfFile:path]; 
CFDataRef inP12Data = (__bridge CFDataRef)p12data; 
SecIdentityRef myIdentity; 

OSStatus status = extractIdentity(inP12Data, &myIdentity); 

if (status != 0) { 
    NSLog(@"%@",status); 
} 
return myIdentity; 

} 

OSStatus extractIdentity(CFDataRef inP12Data, SecIdentityRef *identity){ 
OSStatus securityError = errSecSuccess; 

CFStringRef password = CFSTR("password"); 
const void *keys[] = { kSecImportExportPassphrase }; 
const void *values[] = { password }; 

CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); 

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 
securityError = SecPKCS12Import(inP12Data, options, &items); 

if (securityError == 0) { 
    CFDictionaryRef ident = CFArrayGetValueAtIndex(items,0); // <<<at this point i get an EXC_BAD_ACCESS(code=2,adress=0x0) error 
    const void *tempIdentity = NULL; 
    tempIdentity = CFDictionaryGetValue(ident, kSecImportItemIdentity); 
    *identity = (SecIdentityRef)tempIdentity; 
} 

if (options) { 
    CFRelease(options); 
} 

return securityError; 
} 

@end 

我已標記錯誤的帶有註釋的地步,我真的不知道爲什麼我一直得到這一點。該代碼應該是Apple dev站點的認可解決方案。

回答

0

你的陣列仍然是空的,當你試圖獲得其第一個元素...

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 
securityError = SecPKCS12Import(inP12Data, options, &items); 

if (securityError == 0) { 
    CFDictionaryRef ident = CFArrayGetValueAtIndex(items,0); // <<<at this point i get an EXC_BAD_ACCESS(code=2,adress=0x0) error 

我認爲問題可能與證書或與你通過選項奠定。

+0

謝謝,生病看看它... – Casper522

+0

你能解釋你如何解決它嗎?同樣的問題在這裏,你接受但沒有說這是如何解決你的問題 –

+0

這不是正確的答案 - 同樣的問題在這裏 - 我做一個事先檢查:guard CFArrayGetCount(items)> 0 else {return nil} – lupinglade