Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

iphone - Saving SecKeyRef device generated public/private key pair on disk

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.

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().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

The above is from Apple's CryptoExercise. Not sure if it works for private keys though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...