7

我已经使用SecKeyGeneratePair. 我现在想将公钥传递给服务器,但我不确定如何继续。

我有一个函数getPublicKeyBits(取自 Apple 的CryptoExercise),但我真的不知道如何处理原始 NSData。这是功能:

- (NSData *)getPublicKeyBits {
    OSStatus sanityCheck = noErr;
    NSData* publicKeyBits = nil;
    NSData* publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
    CFDataRef cfresult = NULL;


    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];

    // Set the public key query dictionary.
    [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];
    [queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnData];

    // Get the key bits.
    sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef*)&cfresult); 


    if (sanityCheck != noErr)
    {
        publicKeyBits = nil;
    }
    else 
    {
        publicKeyBits = (__bridge_transfer NSData *)cfresult;
    }

    return publicKeyBits;
}

如何获取这些原始字节数据并将其转换PEM为加密库可以理解的类似格式或其他格式?我应该对它进行base64编码吗?我还需要做其他事情吗?

如果有帮助,我正在尝试将公钥与M2Crypto可用于 Python 的库一起使用。

4

2 回答 2

2

我想你会想看看http://www.openssl.org/docs/crypto/pem.html# 也许:

int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
                                    unsigned char *kstr, int klen,
                                    pem_password_cb *cb, void *u);
于 2012-04-18T05:01:01.167 回答
1

这个页面有一些很棒的技巧和示例代码,用于将您拥有的数据打包成 PEM 格式,以便您可以将其发送到服务器:

http://blog.wingsofhermes.org/?p=42

您不需要从源代码编译并静态链接的整个 openssl 库来执行此操作。我正在使用这种技术,将 base 64 密钥包装在“-----BEGIN PUBLIC KEY-----”中,Rails 应用程序可以使用标准的 ruby​​ openssl 类读取和使用它。

于 2012-12-09T13:24:41.630 回答