Checking a Public Key in canAuthenticateAgainstProtectionSpace

前端 未结 2 1849
南旧
南旧 2021-02-06 18:02

I have been asked to check the public key against a known value in canAuthenticateAgainstProtectionSpace ( a delegate callback of NSURLConnection )

This is

2条回答
  •  别跟我提以往
    2021-02-06 18:38

    Incase anyone cares, the solution was to check the certificatie byte for byte with a certificate saved on the bundle.

    - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
    {
        SecTrustRef trust = [protectionSpace serverTrust];
    
        SecCertificateRef certificate = SecTrustGetCertificateAtIndex(trust, 0);
    
        NSData* ServerCertificateData = (NSData*) SecCertificateCopyData(certificate);
    
        // Check if the certificate returned from the server is identical to the saved certificate in
        // the main bundle
        BOOL areCertificatesEqual = ([ServerCertificateData 
                                      isEqualToData:[MyClass getCertificate]]);
    
        [ServerCertificateData release];
    
        if (!areCertificatesEqual) 
        {    
            NSLog(@"Bad Certificate, canceling request");
            [connection cancel];
        }
    
        // If the certificates are not equal we should not talk to the server;
        return areCertificatesEqual;
    }
    

提交回复
热议问题