繁体   English   中英

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

[英]Saving SecKeyRef device generated public/private key pair on disk

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

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

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

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

啊,我自己找到了答案; 您可以使用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。 不确定它是否适用于私钥。

您可以使用iOS的最新加密API,您可以将密钥保存为NSData并从NSData检索密钥

SecKeyRef key = <# a key #>;
CFErrorRef error = NULL;
NSData* keyData = (NSData*)CFBridgingRelease(  // ARC takes ownership
                       SecKeyCopyExternalRepresentation(key, &error)
                   );
if (!keyData) {
    NSError *err = CFBridgingRelease(error);  // ARC takes ownership
    // Handle the error. . .
}

https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_as_data?language=objc

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM