将 SecKeyRef 设备生成的公钥/私钥对保存在磁盘上 [英] Saving SecKeyRef device generated public/private key pair on disk
问题描述
我在设备上使用 SecKeyGeneratePair()
在设备上生成了一个 RSA 对称密钥对.我有每个键的 SecKeyRef
结构指针.那么,如何将 SecKeyRef
保存到磁盘?甚至传输它(我也想正确编码也有问题)?Apple 的证书、密钥和信任服务"指南说明
I've generated an RSA symmetric key pair on a device using SecKeyGeneratePair()
on a device. I have SecKeyRef
struct pointers for each key. So, how do I save a SecKeyRef
to disk? Or even transmit it (I also imagine there are issues with correct encoding too)? Apple's 'Certificate, Key, and Trust Services' Guide notes
您可以将您的公钥发送给任何人,然后谁可以使用它来加密数据.
You can send your public key to anyone, who can then use it to encrypt data.
我特别想保存私钥;所以我可以在部署的设备上使用它来解密用公钥加密的数据.
I'd like to save the private key especially; so I can use it on deployed devices to decrypt data encrypted with the public key.
附:我不介意每个键的结果数据是 DER 编码的 ASN.1 还是 base-64;我只需要弄清楚如何从 SecKeyRef
中取出密钥.我也很清楚 OS X 的 SecKeychainItemExport()
不存在.
P.S. I don't mind if the resulting data for each key is DER-encoded ASN.1 or base-64; I just need to figure out how to pull the key out of a SecKeyRef
. I'm also well-aware of the non-existence of OS X's SecKeychainItemExport()
.
推荐答案
啊,自己找到答案了;您可以使用 SecItemCopyMatching()
获取公钥的字节.
Ah, found the answer myself; you can get the bytes for a public key using 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;
}
以上内容来自 Apple 的 CryptoExercise.不确定它是否适用于私钥.
The above is from Apple's CryptoExercise. Not sure if it works for private keys though.
这篇关于将 SecKeyRef 设备生成的公钥/私钥对保存在磁盘上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!