3

canAuthenticateAgainstProtectionSpace我被要求根据(的委托回调NSURLConnection)中的已知值检查公钥

这是我到目前为止所拥有的:

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

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

如何将公钥与已知值进行比较?

NSLog 产生:<SecKeyRef: 0x687c000>这没什么用。

4

2 回答 2

5

万一有人关心,解决方案是使用保存在捆绑包中的证书逐字节检查证书。

- (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;
}
于 2011-09-09T13:05:48.137 回答
4

请注意,SecCertificateCopyData 以“DER”形式返回证书,可分辨编码规则。因此,您需要以该形式将证书合并到您的应用程序中,而不是作为 pem 或任何格式。要使用 openssl 将证书转换为 DER,请使用以下命令: openssl x509 -in server.crt -out server.der -outform DER

于 2012-09-14T16:38:39.617 回答