2011-04-15 7 views
3

公共密鑰我被要求覈對已知值在canAuthenticateAgainstProtectionSpace公鑰(的NSURLConnection委託回調)檢查在canAuthenticateAgainstProtectionSpace

這是我到目前爲止有:

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

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

如何將公鑰與已知值進行比較?

NSLog產生:<SecKeyRef: 0x687c000>這不是有用的。

回答

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

不錯!你如何存儲要比較的證書?或者你只比較散列值? – joshis 2012-03-07 16:20:05

+0

@joshis它作爲一個.cer文件存儲在捆綁包中。我用NSData的dataWithContentsOfFile :. '[MyClass getCertificate]'是一個以NSData形式返回證書的連接方法。 – Robert 2012-03-07 18:01:57

+0

...你是對的 - 忘記我們在這裏談論公鑰,並且沒有必要掩蓋關鍵... – joshis 2012-03-08 08:38:49

4

請注意,SecCertificateCopyData以「DER」形式返回證書,區分編碼規則。因此,您需要將該證書以該形式併入您的應用程序中,而不是以pem或任何格式。要使用openssl將證書轉換爲DER,請使用以下命令:openssl x509 -in server.crt -out server.der -outform DER

+0

只是我需要的信息 - 謝謝! – dreyln 2013-02-07 20:50:45