检查canAuthenticateAgainstProtectionSpace中的公钥

时间:2011-04-15 11:10:32

标签: iphone ios cryptography public-key

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

这是我到目前为止所做的:

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

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

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

NSLog产生:<SecKeyRef: 0x687c000>,它没有用处。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:4)

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