NSString到SecKeyRef

我正在使用此代码: https : //stackoverflow.com/a/19221754/849616 ,但不是一切都清楚。

我想使用公钥NSString *pubKey = "1111"来encryptionNSString *msg = "0000" NSString *pubKey = "1111" 。 因此,我正在更新常量:

 static const UInt8 publicKeyIdentifier[] = 1111; // i want to encrypt only, so private key doesn't matter and I'm not posting it here 

在函数testAsymmetricEncryptionAndDecryption我已经更新:

 const char inputString[] = 0000 

但结果是错误的。 是publicKeyIdentifier一个正确的地方把我的关键string..? 我应该怎么做,如果我的做法是错误的..?

那么问题是错的。 我甚至不应该尝试将其转换为NSString。 你应该把两个键都放到你的项目中,并使用如下的东西:

 - (SecKeyRef)getPrivateKeyRef { NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaPrivate" ofType:@"p12"]; NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath]; NSMutableDictionary *options = [[NSMutableDictionary alloc] init]; SecKeyRef privateKeyRef = NULL; //change to the actual password you used here [options setObject:@"!@#EWQ" forKey:(__bridge id)kSecImportExportPassphrase]; CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); OSStatus securityError = SecPKCS12Import((__bridge CFDataRef)p12Data, (__bridge CFDictionaryRef)options, &items); if (securityError == noErr && CFArrayGetCount(items) > 0) { CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0); SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity); securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef); if (securityError != noErr) { privateKeyRef = NULL; } } CFRelease(items); return privateKeyRef; } - (SecKeyRef)getPublicKeyRef { NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaCert" ofType:@"der"]; NSData *certData = [NSData dataWithContentsOfFile:resourcePath]; SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData); SecKeyRef key = NULL; SecTrustRef trust = NULL; SecPolicyRef policy = NULL; if (cert != NULL) { policy = SecPolicyCreateBasicX509(); if (policy) { if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) { SecTrustResultType result; if (SecTrustEvaluate(trust, &result) == noErr) { key = SecTrustCopyPublicKey(trust); } } } } if (policy) CFRelease(policy); if (trust) CFRelease(trust); if (cert) CFRelease(cert); return key; } 

我没有把它全部写出来(只是修改),它大部分是复制的,但是我真的不知道从哪里开始 – 一些开源社区。 不过,非常感谢写这个的人。