'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?
Solution 1:[1]
// 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];
Solution 2:[2]
[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 (e.g. using base 64 encoding) as an excercise.
Solution 3:[3]
+ (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 more https://developer.apple.com/library/archive/samplecode/CryptoExercise/Introduction/Intro.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Or Arbel |
Solution 2 | Community |
Solution 3 | CoderSeven |