简体   繁体   中英

Send Public key(generated as seckeyref in iPhone) to server(in Java)

I need to send my public key that has been generated by SecKeyGeneratePair as a SecKeyRef object. Now, to send this, i need this KeyRef object to be in a string format.

How do i convert the SecKeyRef object to nsstring object?

// you have SecKeyRef keyref from somewhere 
size_t keySize = SecKeyGetBlockSize(keyref);
NSData* keyData = [NSData dataWithBytes:keyref length:keySize];

Then use this NSData category to encode the NSData object with base64 to a NSString.

NSString *keyStringB64 = [keyData base64EncodedString];
+ (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey {

    static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey";
    NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];

    OSStatus sanityCheck = noErr;
    NSData * publicKeyBits = nil;

    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
    [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
    [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
    [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];

    // Temporarily add key to the Keychain, return as data:
    NSMutableDictionary * attributes = [queryPublicKey mutableCopy];
    [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef];
    [attributes setObject:@YES forKey:(__bridge id)kSecReturnData];
    CFTypeRef result;
    sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &result);
    if (sanityCheck == errSecSuccess) {
        publicKeyBits = CFBridgingRelease(result);

        // Remove from Keychain again:
        (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey);
    }

    return publicKeyBits;
}

then, conver the data to base64 string.

it works fine when I run this code as part of an iOS app.

see iOS SecKeyRef to NSData

see more https://developer.apple.com/library/archive/samplecode/CryptoExercise/Introduction/Intro.html

[Cleanup of old question]

Saving SecKeyRef device generated public/private key pair on disk

Shows how to create an NSData object. As I'm no iOS developer, I'll leave the conversion to a string (eg using base 64 encoding) as an excercise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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