gpt4 book ai didi

iphone - 在 iOS 中,如何使用服务器上带有自签名证书的 https 连接到服务器?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:20:21 28 4
gpt4 key购买 nike

我正在为 iOS 5 开发并且真的不想使用非 ARCed 代码所以我选择自己实现它而不是使用 AFNetworking。这也可能是一个大问题,所以我将其分成两个较小的部分。

1) 在 iOS 5 中使用 https 连接到服务器。我在这里使用从“iOS 5 Programming Pushing the Limits”中提取的代码。因为我正在为 iOS 5 开发,所以我没有在我的项目中使用已弃用的方法。 “RNSecTrustEvaluateAsX509”是一种将证书重新评估为简单 X.509 证书而不是作为 SSL 握手的一部分的方法。

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

NSURLProtectionSpace *protSpace = challenge.protectionSpace;
SecTrustRef trust = protSpace.serverTrust;
SecTrustResultType result = kSecTrustResultFatalTrustFailure;

OSStatus status = SecTrustEvaluate(trust, &result);

if (status == errSecSuccess && result == kSecTrustResultRecoverableTrustFailure) {
SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, 0);
CFStringRef subject = SecCertificateCopySubjectSummary(cert);

NSLog(@"Trying to access %@. Got %@.", protSpace.host,
(__bridge id)subject);
CFRange range = CFStringFind(subject, CFSTR("192.168.1.100"), kCFCompareAnchored|kCFCompareBackwards);
if (range.location != kCFNotFound) {
NSLog(@"Creating new trust certificate.Ignoring the hostname.");
status = RNSecTrustEvaluateAsX509(trust, &result);
}
CFRelease(subject);
}

if (status == errSecSuccess) {
switch (result) {
case kSecTrustResultInvalid:
case kSecTrustResultDeny:
case kSecTrustResultFatalTrustFailure:
case kSecTrustResultOtherError:
case kSecTrustResultRecoverableTrustFailure: {
NSLog(@"Failing due to result: %lu", result);
[challenge.sender cancelAuthenticationChallenge:challenge];
}

break;
case kSecTrustResultProceed:
case kSecTrustResultUnspecified: {
NSLog(@"Successing with result: %lu", result);
NSURLCredential *cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
}
break;
default:
NSAssert(NO,@"Unexpected result from trust evaluation: %d", result);
break;
}
}
else {
// Something was broken
NSLog(@"Complete failure with code: %lu", status);
[challenge.sender cancelAuthenticationChallenge:challenge];
}

}

它连接到服务器,但我总是收到一条错误消息“操作无法完成(NSURLErrorDomain 错误 -1012)”。并且控制台显示“由于结果 5 而失败”,这意味着我得到了kSecTrustResultRecoverableTrustFailure。我怀疑这是因为我在服务器上使用自签名证书。这就导致了下面的第二个问题。

2) 自签名证书导致问题。所以我添加了这些行

// Self-signed certificates need to be validated manually.
NSArray *anchors = [self serverAnchors];

SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)anchors);
SecTrustSetAnchorCertificatesOnly(trust, YES);

就在

OSStatus status = SecTrustEvaluate(trust, &result);

在上面的 willSendRequestForAuthenticationChallenge 方法中。我还创建了一个方法:

- (NSArray *)serverAnchors
{
static NSArray *anchors = nil;
if (!anchors) {
NSData *caData = [CA_CERTS dataUsingEncoding:NSUTF8StringEncoding];
SecCertificateRef caRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef) caData);

anchors = [NSArray arrayWithObjects:(__bridge id)caRef, nil];

if (caRef) {
CFRelease(caRef);
}
}

return anchors;
}

我将CA_CERTS定义为“der”格式的证书数据,它是我通过SecCertificateCopyData从服务器获取的一个NSString。但我仍然不断收到 kSecTrustResultRecoverableTrustFailure。我真的不知道我在这里做的是否正确。如何使用自己的数据从服务器手动验证自签名证书?更具体地说,如何从 iOS 获取其数据?

最佳答案

我建议将 OpenSSL 合并到您的项目中以处理证书和授权挑战!然后在“NSURLConnectionDelegate”协议(protocol)的“connection:didReceiveAuthenticationChallenge:”方法中执行如下操作:

- (void) connection:(NSURLConnection*) connection didReceiveAuthenticationChallenge: (NSURLAuthenticationChallenge*) challenge {
if ([[[challenge protectionSpace] authenticationMethod] isEqualToString: NSURLAuthenticationMethodServerTrust]) {
SecTrustRef trust = [[challenge protectionSpace] serverTrust];

NSMutableArray* certificates = [NSMutableArray array];

NSData* certificate2Data = // your certificate data
NSData* certificate3Data = // even more certificate data if needed
SecCertificateRef certificate2 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate2Data);
SecCertificateRef certificate3 = SecCertificateCreateWithData(NULL, (CFDataRef) certificate3Data);
[certificates addObject: (id) certificate2];
[certificates addObject: (id) certificate3];
CFRelease(certificate2);
CFRelease(certificate3);

SecTrustSetAnchorCertificates(trust, (CFArrayRef) certificates);
SecTrustSetAnchorCertificatesOnly(trust, true);

SecTrustResultType trust_result;
SecTrustEvaluate(trust, &trust_result);
if (trust_result == kSecTrustResultUnspecified) {
if (SecTrustGetCertificateCount(trust) > 0) {
SecCertificateRef leafCertificate = SecTrustGetCertificateAtIndex(trust, 0);

NSData* leafCertificateData = (NSData*) SecCertificateCopyData(leafCertificate);

const unsigned char* certificateDataBytes = (const unsigned char *)[leafCertificateData bytes];
X509* certificateX509 = d2i_X509(NULL, &certificateDataBytes, [leafCertificateData length]);

CFRelease(leafCertificateData);

X509_NAME *issuerX509Name = X509_get_issuer_name(certificateX509);
X509_NAME *subjectX509Name = X509_get_subject_name(certificateX509);

/*
with issuerX509Name and subjectX509Name you could check some properties of the certificate and cancel the
authentication challenge f.e.!

if ([[self valueWithKey: @"CN" inName: subjectX509Name cert: certificateX509] isEqualToString: @"xxxx"] == NO) {
[[challenge sender] cancelAuthenticationChallenge: challenge];
return;
}


*/

NSURLCredential* credential = [NSURLCredential credentialForTrust: trust];
[[challenge sender] useCredential: credential forAuthenticationChallenge: challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge: challenge];
}
} else {
[[challenge sender] cancelAuthenticationChallenge: challenge];
}
}}

关于iphone - 在 iOS 中,如何使用服务器上带有自签名证书的 https 连接到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12049508/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com