iOS 项目中将 http 改成 https 后需要改动的地方(密钥验证)

这种是不验证证书的密钥

AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];

policy.allowInvalidCertificates = YES;

policy.validatesDomainName = NO;

manager.securityPolicy = policy;

//manager.securityPolicy = [self customSecurityPolicy];

/**** SSL Pinning ****///验证证书,单项验证。(需要后台给证书,并且改为 cer 格式的,最好找安卓转一下,他们比较方便一点)

- (AFSecurityPolicy*)customSecurityPolicy {

NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"ios118" ofType:@"cer"];

NSData *certData = [NSData dataWithContentsOfFile:cerPath];

AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];

[securityPolicy setAllowInvalidCertificates:YES];

[securityPolicy setPinnedCertificates:@[certData]];

securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];

//[securityPolicy setSSLPinningMode:AFSSLPinningModeCertificate];

return securityPolicy;

}

//这个是验证证书,双向验证。

if(challenge.previousFailureCount < 5) {

self.serverTrust = challenge.protectionSpace.serverTrust;

SecTrustResultType result;

SecTrustEvaluate(self.serverTrust, &result);

if(result == kSecTrustResultProceed ||

result == kSecTrustResultUnspecified //The cert is valid, but user has not explicitly accepted/denied. Ok to proceed (Ch 15: iOS PTL :Pg 269)

) {

CFIndex certificateCount = SecTrustGetCertificateCount(self.serverTrust);

NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];

for (CFIndex i = 0; i < certificateCount; i++) {

SecCertificateRef certificate = SecTrustGetCertificateAtIndex(self.serverTrust, i);

[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];

}

NSBundle *bundle = [NSBundle mainBundle];

NSArray *paths = [bundle pathsForResourcesOfType:@"der" inDirectory:@"."];

NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];

for (NSString *path in paths) {

NSData *certificateData = [NSData dataWithContentsOfFile:path];

[certificates addObject:certificateData];

}

NSArray *_defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];

NSUInteger trustedCertificateCount = 0;

for (NSData *trustChainCertificate in trustChain) {

if ([_defaultPinnedCertificates containsObject:trustChainCertificate]) {

trustedCertificateCount++;

}

}

if (trustedCertificateCount > 0) {

[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

}else {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该请求不是可信的" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

[alert show];

[challenge.sender cancelAuthenticationChallenge:challenge];

}

[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

你可能感兴趣的:(iOS 项目中将 http 改成 https 后需要改动的地方(密钥验证))