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

Ala*_*ino 17 security iphone cryptography ios

我在设备上使用SecKeyGeneratePair()设备生成了RSA对称密钥对.我SecKeyRef为每个键都有结构指针.那么,如何保存SecKeyRef到磁盘?甚至传输它(我也想象有正确编码的问题)?Apple的"证书,密钥和信任服务"指南说明

您可以将您的公钥发送给任何人,然后可以使用它来加密数据.

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

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

Ala*_*ino 10

啊,我自己找到了答案; 您可以使用获取公钥的字节数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;
}
Run Code Online (Sandbox Code Playgroud)

以上内容来自Apple的CryptoExercise.不确定它是否适用于私钥.

  • 在上面的代码中,什么是`publicTag`?当我使用我的`SecKeyRef`代替`publicTag`时,我收到"属性列表格式无效:200(属性列表不能包含'SecKey'类型的对象)"`SecKeyRef`是不透明的RSA公钥(Apple )格式. (2认同)