保存SecKeyRef设备生成的公/私钥对在磁盘上 [英] Saving SecKeyRef device generated public/private key pair on disk

查看:282
本文介绍了保存SecKeyRef设备生成的公/私钥对在磁盘上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设备上使用 SecKeyGeneratePair()在设备上生成了RSA对称密钥对。我有 SecKeyRef 每个键的struct指针。那么,如何保存 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆