简体   繁体   English

将公钥(在 iPhone 中生成为 seckeyref)发送到服务器(在 Java 中)

[英]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.我需要发送由 SecKeyGeneratePair 生成的公钥作为 SecKeyRef object。现在,要发送这个,我需要这个 KeyRef object 为字符串格式。

How do i convert the SecKeyRef object to nsstring object?如何将 SecKeyRef object 转换为 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. 然后使用此NSData类别将带有base64的NSData对象编码为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.然后,将数据转换为 base64 字符串。

it works fine when I run this code as part of an iOS app.当我将此代码作为 iOS 应用程序的一部分运行时,它工作正常。

see iOS SecKeyRef to NSData参见iOS SecKeyRef 到 NSData

see more https://developer.apple.com/library/archive/samplecode/CryptoExercise/Introduction/Intro.html查看更多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 将SecKeyRef设备生成的公用/专用密钥对保存在磁盘上

Shows how to create an NSData object. 显示如何创建NSData对象。 As I'm no iOS developer, I'll leave the conversion to a string (eg using base 64 encoding) as an excercise. 由于我不是iOS开发人员,因此将练习留给字符串(例如,使用base 64编码)转换。

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

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