开发者

Checking a Public Key in canAuthenticateAgainstProtectionSpace

I have been asked to check the public key against a known value in canAuthenticateAgainstProtectionSpace ( a delegate ca开发者_如何学JAVAllback of NSURLConnection )

This is what I have so far:

- (BOOL)connection:(NSURLConnection *)connection 
        canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
    {
        SecKeyRef publicKey = SecTrustCopyPublicKey([protectionSpace serverTrust]);

        NSLog(@"%@",SecTrustCopyPublicKey([protectionSpace serverTrust])); 
        return YES;
}

How can I compare the public key against a known value?

The NSLog produces: <SecKeyRef: 0x687c000> which isn't vary useful.


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;
}


Note that SecCertificateCopyData returns the certificate in it's "DER" form, Distinguished Encoding Rules. So you need to incorporate the certificate in your App in that form, and not as a pem or whatever format. To convert a certificate to DER with openssl use the command: openssl x509 -in server.crt -out server.der -outform DER

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜