正在检查canAuthenticateAgainstProtectionSpace中的公钥

问题描述

|| 我被要求对照
canAuthenticateAgainstProtectionSpace
(委托回调check1ѭ)中的已知值检查公钥。 这是我到目前为止所拥有的:
- (BOOL)connection:(NSURLConnection *)connection 
        canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace 
    {
        SecKeyRef publicKey = SecTrustCopyPublicKey([protectionSpace serverTrust]);

        NSLog(@\"%@\",SecTrustCopyPublicKey([protectionSpace serverTrust])); 
        return YES;
}
如何将公钥与已知值进行比较? NSLog产生:
<SecKeyRef: 0x687c000>
,它没有什么用。     

解决方法

万一有人在乎,解决方案是检查证书字节是否与保存在捆绑包中的证书相对应。
- (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;
}
    ,请注意,SecCertificateCopyData以其“ DER \”形式(可分辨编码规则)返回证书。因此,您需要以那种形式(而不是以pem或任何格式)将证书合并到您的应用中。要使用openssl将证书转换为DER,请使用以下命令:openssl x509 -in server.crt -out server.der -outform DER     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...