将SecKeyRef设备生成的公钥/私钥对保存在磁盘上

我在设备上使用SecKeyGeneratePair()在设备上生成一个RSA对称密钥对。 我有每个键的SecKeyRef结构指针。 那么,如何将SecKeyRef保存到磁盘? 甚至传输它(我也想象也有正确的编码问题)? 苹果的“证书,密钥和信任服务”指南注释

您可以将您的公钥发送给任何可以用来encryption数据的人。

我想特别保存私钥。 所以我可以在部署的设备上使用它来解密用公钥encryption的数据。

PS我不介意每个键的结果数据是DER编码的ASN.1还是base-64; 我只需要弄清楚如何从SecKeyRef取出密钥。 我也很清楚OS X的SecKeychainItemExport()不存在。

啊,我自己find了答案。 您可以使用SecItemCopyMatching()获取公钥的字节。

 - (NSData *)getPublicKeyBits { OSStatus sanityCheck = noErr; NSData * publicKeyBits = nil; NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init]; // Set the public key query dictionary. [queryPublicKey setObject:(id)kSecClassKey forKey:(id)kSecClass]; [queryPublicKey setObject:publicTag forKey:(id)kSecAttrApplicationTag]; [queryPublicKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType]; [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnData]; // Get the key bits. sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyBits); if (sanityCheck != noErr) { publicKeyBits = nil; } [queryPublicKey release]; return publicKeyBits; } 

以上是来自苹果的CryptoExercise。 不知道它是否适用于私钥。

请参阅“证书,密钥和信任服务编程指南”中的“ encryption和解密数据”部分,其中包含用于生成,保存和使用公钥/私钥对的代码示例。