问题描述
||
我被要求对照
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