iOS HTTPS证书不受信任解决办法

2024-06-24 13:32

本文主要是介绍iOS HTTPS证书不受信任解决办法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

之前开发App的时候服务端使用的是自签名的证书,导致iOS开发过程中调用HTTPS接口时,证书不被信任

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{/*方法一*/if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];if(completionHandler)completionHandler(NSURLSessionAuthChallengeUseCredential,credential);}/*方法二*/
//    SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
//    SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
//    NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"证书名称" ofType:@"cer"];NSLog(@"证书 : %@",path);
//    NSData *localCertiData = [NSData dataWithContentsOfFile:path];
//    if ([certidata isEqualToData:localCertiData]) {
//        NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
//        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
//        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);NSLog(@"服务端证书认证通过");
//    }else {
//        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
//        NSLog(@"服务端认证失败");
//    }}

这里有两个方法,第一个是信任所有证书,第二个是把服务端自签名的证书放到本地,类似白名单的样子去加载

源码

HttpRequest.h

//
//  HttpRequest.h
//
//  Created by Michael Zhan on 2017/5/17.
//  Copyright © 2017年 Michael Zhan. All rights reserved.
//#import <Foundation/Foundation.h>static NSString * const baseUrl = @"http://";typedef void (^SuccessBlock)(NSString * data);
typedef void (^FailureBlock)(NSError * error);@interface HttpRequest : NSObject <NSURLSessionTaskDelegate>- (void)getWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)getWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;- (void)postWithDict2String:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock;@end

HttpRequest.m

//
//  HttpRequest.m
//
//  Created by Michael Zhan on 2017/5/17.
//  Copyright © 2017年 Michael Zhan. All rights reserved.
//#import "HttpRequest.h"@implementation HttpRequest- (void)getWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSMutableString * mutableStringUrl = [[NSMutableString alloc] initWithString:paramUrl];[mutableStringUrl appendString:[HttpRequest convertToJsonData:paramDicet]];NSLog(@"url %@",mutableStringUrl);NSURL * url = [NSURL URLWithString:[mutableStringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);} else {NSString * result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];successBlock(result);}}];[dataTask resume];}- (void)postWithDict:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";NSString * jsonStr = [HttpRequest convertToJsonData:paramDicet];request.HTTPBody = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}- (void)postWithDict2String:(NSString *)paramUrl NSDictionary:(NSDictionary *)paramDicet success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";NSString * jsonStr = [NSString stringWithFormat:@"%@",paramDicet];request.HTTPBody = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];request.timeoutInterval = 10;request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}- (void)getWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSMutableString * mutableStringUrl = [[NSMutableString alloc] initWithString:paramUrl];[mutableStringUrl appendString:paramString];NSLog(@"url %@",mutableStringUrl);NSURL * url =[NSURL URLWithString:[mutableStringUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];NSURLRequest * request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];}- (void)postWithString:(NSString *)paramUrl NSString:(NSString *)paramString success:(SuccessBlock)successBlock failure:(FailureBlock)failureBlock{NSURL * url = [NSURL URLWithString:paramUrl];NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:100];request.HTTPMethod = @"POST";request.HTTPBody = [paramString dataUsingEncoding:NSUTF8StringEncoding];request.timeoutInterval = 10;request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;//2程序自动安装证书的方式NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {if (error) {failureBlock(error);[session finishTasksAndInvalidate];} else {NSString * result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];successBlock(result);[session finishTasksAndInvalidate];}}];[dataTask resume];
}+ (NSString *)convertToJsonData:(NSDictionary *)dict{NSError *error;NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];NSString *jsonString;if (!jsonData) {NSLog(@"%@",error);}else{jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];}NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];NSRange range = {0,jsonString.length};//去掉字符串中的空格[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];NSRange range2 = {0,mutStr.length};//去掉字符串中的换行符[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];return mutStr;
}- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler{/*方法一*/if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]){NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];if(completionHandler)completionHandler(NSURLSessionAuthChallengeUseCredential,credential);}/*方法二*/
//    SecTrustRef servertrust = challenge.protectionSpace.serverTrust;
//    SecCertificateRef certi= SecTrustGetCertificateAtIndex(servertrust, 0);
//    NSData *certidata = CFBridgingRelease(CFBridgingRetain(CFBridgingRelease(SecCertificateCopyData(certi))));
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"zwp" ofType:@"cer"];NSLog(@"证书 : %@",path);
//    NSData *localCertiData = [NSData dataWithContentsOfFile:path];
//    if ([certidata isEqualToData:localCertiData]) {
//        NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:servertrust];
//        [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
//        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);NSLog(@"服务端证书认证通过");
//    }else {
//        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
//        NSLog(@"服务端认证失败");
//    }}@end

这篇关于iOS HTTPS证书不受信任解决办法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1090282

相关文章

Go标准库常见错误分析和解决办法

《Go标准库常见错误分析和解决办法》Go语言的标准库为开发者提供了丰富且高效的工具,涵盖了从网络编程到文件操作等各个方面,然而,标准库虽好,使用不当却可能适得其反,正所谓工欲善其事,必先利其器,本文将... 目录1. 使用了错误的time.Duration2. time.After导致的内存泄漏3. jsO

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

MySQL错误代码2058和2059的解决办法

《MySQL错误代码2058和2059的解决办法》:本文主要介绍MySQL错误代码2058和2059的解决办法,2058和2059的错误码核心都是你用的客户端工具和mysql版本的密码插件不匹配,... 目录1. 前置理解2.报错现象3.解决办法(敲重点!!!)1. php前置理解2058和2059的错误

Docker镜像pull失败两种解决办法小结

《Docker镜像pull失败两种解决办法小结》有时候我们在拉取Docker镜像的过程中会遇到一些问题,:本文主要介绍Docker镜像pull失败两种解决办法的相关资料,文中通过代码介绍的非常详细... 目录docker 镜像 pull 失败解决办法1DrQwWCocker 镜像 pull 失败解决方法2总

关于Docker Desktop的WSL报错问题解决办法

《关于DockerDesktop的WSL报错问题解决办法》:本文主要介绍关于DockerDesktop的WSL报错问题解决办法的相关资料,排查发现是因清理%temp%文件夹误删关键WSL文件,... 目录发现问题排查过程:解决方法其实很简单:重装之后再看就能够查到了:最后分享几个排查这类问题的小www.cp

Python如何获取域名的SSL证书信息和到期时间

《Python如何获取域名的SSL证书信息和到期时间》在当今互联网时代,SSL证书的重要性不言而喻,它不仅为用户提供了安全的连接,还能提高网站的搜索引擎排名,那我们怎么才能通过Python获取域名的S... 目录了解SSL证书的基本概念使用python库来抓取SSL证书信息安装必要的库编写获取SSL证书信息

电脑开机提示krpt.dll丢失怎么解决? krpt.dll文件缺失的多种解决办法

《电脑开机提示krpt.dll丢失怎么解决?krpt.dll文件缺失的多种解决办法》krpt.dll是Windows操作系统中的一个动态链接库文件,它对于系统的正常运行起着重要的作用,本文将详细介绍... 在使用 Windows 操作系统的过程中,用户有时会遇到各种错误提示,其中“找不到 krpt.dll”

Pycharm安装报错:Cannot detect a launch configuration解决办法

《Pycharm安装报错:Cannotdetectalaunchconfiguration解决办法》本文主要介绍了Pycharm安装报错:Cannotdetectalaunchconfigur... 本文主要介绍了Pycharm安装报错:Cannot detect a launch configuratio

nginx生成自签名SSL证书配置HTTPS的实现

《nginx生成自签名SSL证书配置HTTPS的实现》本文主要介绍在Nginx中生成自签名SSL证书并配置HTTPS,包括安装Nginx、创建证书、配置证书以及测试访问,具有一定的参考价值,感兴趣的可... 目录一、安装nginx二、创建证书三、配置证书并验证四、测试一、安装nginxnginx必须有"-

nginx部署https网站的实现步骤(亲测)

《nginx部署https网站的实现步骤(亲测)》本文详细介绍了使用Nginx在保持与http服务兼容的情况下部署HTTPS,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录步骤 1:安装 Nginx步骤 2:获取 SSL 证书步骤 3:手动配置 Nginx步骤 4:测