2015-07-13 95 views
0

我使用這個網站來生成公鑰和私鑰 http://travistidwell.com/jsencrypt/demo/和我試圖弄明白如何從私有密鑰的iOS RSA解密

創建SecKeyRef我發現這個project看起來很很有前途,但對我不起作用。

這裏是我的代碼,嘗試創建SecKeyRef

NSString* publicKey = @"MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHKzKc/6vphvntLiP1r/YvxjSLolPeDeOCy48ao5ymwNU2Nqbfeir/qHqbqSAhclAO8TGq8QIpE5ObAKNp2j01pu8Cu9AqwdtZ6EZa/NYahfITKS8iYGs6cHzk2LGw8AqFOEJqHrW/xR8MOS1J765KeZOBCSrWZ5Ag/lpb5jxiDlAgMBAAE="; 
    [[RSA sharedInstance] setPublicKey:publicKey]; 

- (BOOL)setPublicKey: (NSString *)keyAsBase64 { 

    NSData *extractedKey = 
       [[NSData alloc] initWithBase64EncodedString:keyAsBase64 options:0]; 

    /* Load as a key ref */ 
    OSStatus error = noErr; 
    CFTypeRef persistPeer = NULL; 

    NSData * refTag = [self.serverPublicIdentifier dataUsingEncoding:NSUTF8StringEncoding]; 

    NSMutableDictionary * keyAttr = [[NSMutableDictionary alloc] init]; 

    [keyAttr setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; 
    [keyAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; 
    [keyAttr setObject:refTag forKey:(__bridge id)kSecAttrApplicationTag]; 

    /* First we delete any current keys */ 
    error = SecItemDelete((__bridge CFDictionaryRef) keyAttr); 

    [keyAttr setObject:extractedKey forKey:(__bridge id)kSecValueData]; 
    [keyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef]; 

    error = SecItemAdd((__bridge CFDictionaryRef) keyAttr, (CFTypeRef *)&persistPeer); 

    if (persistPeer == nil || (error != noErr && error != errSecDuplicateItem)) { 
     NSLog(@"Problem adding public key to keychain"); 
     return FALSE; 
    } 

    CFRelease(persistPeer); 

    serverPublicRef = nil; 

    /* Now we extract the real ref */ 
    [keyAttr removeAllObjects]; 
    /* 
    [keyAttr setObject:(id)persistPeer forKey:(id)kSecValuePersistentRef]; 
    [keyAttr setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef]; 
    */ 
    [keyAttr setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass]; 
    [keyAttr setObject:refTag forKey:(__bridge id)kSecAttrApplicationTag]; 
    [keyAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType]; 
    [keyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef]; 

    // Get the persistent key reference. 
    error = SecItemCopyMatching((__bridge CFDictionaryRef)keyAttr, (CFTypeRef *)&serverPublicRef); 

    if (serverPublicRef == nil || (error != noErr && error != errSecDuplicateItem)) { 
     NSLog(@"Error retrieving public key reference from chain"); 
     return FALSE; 
    } 

    return TRUE; 
} 

我越來越serverPublicRef == nil但誤差爲0(這是確定的。)

回答

0

kSecClassKey沒有kSecValueData字段。你應該看看使用SecPKCS12Import()

一些相關的問題:

+0

謝謝你的提示,可以請你解釋多一點上我需要用這種方法做什麼和怎麼樣? – ibm123

+0

我不確定你需要多少信息。所以我添加了一些關於SecPKCS12Import其他問題的鏈接。 – Mats

+0

我看不到這個鏈接如何幫助我... – ibm123