如何在RESTful Web服务中使用DER编码的证书和相互身份验证?

mid*_*ori 6 https openssl ssl-certificate ios mutual-authentication

目前我正在开发一个使用相互身份验证的应用程序,以便与REST接口进行通信.因为我对这个主题很陌生,所以我研究了几个例子 - 现在我有一些问题.我希望我能够将所有知识片段放在一起,以便更好地了解整个过程.

该过程应如下所示:

  1. 我获得了导出的服务器证书,其中包含服务器的公钥,并将其添加到应用程序包(稍后用于SSL固定).
  2. 代表2路认证开始的第一个Request是一个Post Request,它还包含一个证书签名请求,用于获取客户端证书(需要与REST接口的安全部分通信).CSR通过openSSL lib在代码中动态生成.
  3. 服务器的响应返回用于客户端身份验证的签名证书.此证书采用DER格式和Base64编码.

我用于为第一个请求执行SSL固定的代码如下所示,SSL Pinning按预期工作.

- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"server-cert" ofType:@"cer"];
    SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
    SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);

    NSData *remoteCertificateData =   CFBridgingRelease(SecCertificateCopyData(certificate));
    NSData *localCertificateData = [NSData dataWithContentsOfFile:cerPath];


    if ([remoteCertificateData isEqualToData:localCertificateData]) {

        NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
        [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];

        [[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential forProtectionSpace:[challenge protectionSpace]];

        NSLog(@"Certificate Pinning Succeeded");

    } else {

        [[challenge sender] cancelAuthenticationChallenge:challenge];

        NSLog(@"Certificate Pinning Failed");

    }
}
Run Code Online (Sandbox Code Playgroud)

但是如何处理来自服务器的返回证书?据我所知,我必须使用以下NSURLConnection委托方法 - 并以某种方式向服务器提供此证书(用于进一步的请求).

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:   (NSURLProtectionSpace *)protectionSpace
{
    if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) {

        NSLog(@"Wants to Authenticate Server Trust");

        return YES;
    }

    if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate]) {

        NSLog(@"Wants to Authenticate Client Certificate");

        return YES;
    }

    return NO;
}
Run Code Online (Sandbox Code Playgroud)

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
Run Code Online (Sandbox Code Playgroud)

现在我的问题.我看到几个使用PKCS12格式(需要私钥和证书颁发机构)而不是DER编码证书的示例,以针对服务器验证自身.但是如何在`didReceiveAuthenticationChallenge中使用我签名的DER格式证书来获取更多请求?还有一个Android应用程序使用相同的进程进行相互身份验证,并且它不需要PKCS12证书.

一些提示会很高兴.谢谢.