iOS RSA解密

时间:2015-07-13 08:02:15

标签: ios objective-c rsa

我正在使用此网站生成公钥和私钥 http://travistidwell.com/jsencrypt/demo/我试图弄清楚如何从私钥创建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(没关系。)

1 个答案:

答案 0 :(得分:0)