0

我正在尝试使用 RSA 在我必须传递给 Web 服务的 HTTP 标头中签署一个令牌 - 要求是我应该使用我自己的私钥进行加密并将我的公钥提供给他们。这纯粹是为了验证消息是由我发送的。

我知道关于 SO 的许多类似问题,但今天早上到目前为止我已经进行了许多尝试,但仍然没有接近我认为微不足道的事情。

我可以找到许多使用 RSA 和使用公钥加密的示例,但我的要求是使用私钥签名。

看起来(从最初的尝试)苹果示例安全代码和从中借用的大多数其他示例总是使用钥匙串生成私钥/公钥对 - 我更喜欢使用 OpenSSL 生成我的密钥,以便我可以将公钥分发给我的客户.

我已经设法生成了一些密钥,看起来我可以使用这段代码加载私钥(抱歉,我不记得源代码了,因为我已经混合了几个小时的实现):

-(SecKeyRef) getPrivateKeyRef {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaPrivate" ofType:@"p12"];
    NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath];

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

    SecKeyRef privateKeyRef = NULL;

    //change to the actual password you used here
    [options setObject:@"xxxx" forKey:(__bridge id)kSecImportExportPassphrase];

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);

    OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data,
                                         (__bridge CFDictionaryRef)options, &items);

    if (securityError == noErr && CFArrayGetCount(items) > 0) {
        CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
        SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict,
                                         kSecImportItemIdentity);

        securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
        if (securityError != noErr) {
            privateKeyRef = NULL;
        }
    }

    CFRelease(items);
    return privateKeyRef;
}

这似乎返回给我一个有效SecKeyRef但我不知道如何使用它来签署一个NSString.

似乎有很多方法可以解决这个问题(构建 OpenSSL 并链接到它,使用 Apple 的钥匙串方法,在 GitHub 上使用部分完整的库)但我一直走到死胡同 - 获得一个适当的、完整的解决这个问题。

类似于以下内容:

NSString* signedString = [rsaHelper signString: @"Hello, World!" WithPrivateKey:@"rsaPrivate.p12"];

并给出一个用公钥加密的字符串:

NSString* decryptedString = [rsaHelper decryptString: @"DK5tkgkfjkJJft=" WithPrivateKey:@"rsaPrivate.p12"];

会很有价值!请注意,我不害怕以任何方式自己编写这段代码,但希望能朝着正确的方向轻推:-)

4

0 回答 0