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

相关文章

安卓链接正常显示,ios#符被转义%23导致链接访问404

原因分析: url中含有特殊字符 中文未编码 都有可能导致URL转换失败,所以需要对url编码处理  如下: guard let allowUrl = webUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {return} 后面发现当url中有#号时,会被误伤转义为%23,导致链接无法访问

软考系统规划与管理师考试证书含金量高吗?

2024年软考系统规划与管理师考试报名时间节点: 报名时间:2024年上半年软考将于3月中旬陆续开始报名 考试时间:上半年5月25日到28日,下半年11月9日到12日 分数线:所有科目成绩均须达到45分以上(包括45分)方可通过考试 成绩查询:可在“中国计算机技术职业资格网”上查询软考成绩 出成绩时间:预计在11月左右 证书领取时间:一般在考试成绩公布后3~4个月,各地领取时间有所不同

【iOS】MVC模式

MVC模式 MVC模式MVC模式demo MVC模式 MVC模式全称为model(模型)view(视图)controller(控制器),他分为三个不同的层分别负责不同的职责。 View:该层用于存放视图,该层中我们可以对页面及控件进行布局。Model:模型一般都拥有很好的可复用性,在该层中,我们可以统一管理一些数据。Controlller:该层充当一个CPU的功能,即该应用程序

Solr 使用Facet分组过程中与分词的矛盾解决办法

对于一般查询而言  ,  分词和存储都是必要的  .  比如  CPU  类型  ”Intel  酷睿  2  双核  P7570”,  拆分成  ”Intel”,”  酷睿  ”,”P7570”  这样一些关键字并分别索引  ,  可能提供更好的搜索体验  .  但是如果将  CPU  作为 Facet  字段  ,  最好不进行分词  .  这样就造成了矛盾  ,  解决方法

消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法

消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法   消除安卓SDK更新时的“https://dl-ssl.google.com refused”异常的方法 [转载]原地址:http://blog.csdn.net/x605940745/article/details/17911115 消除SDK更新时的“

ORACLE 11g 创建数据库时 Enterprise Manager配置失败的解决办法 无法打开OEM的解决办法

在win7 64位系统下安装oracle11g,在使用Database configuration Assistant创建数据库时,在创建到85%的时候报错,错误如下: 解决办法: 在listener.ora中增加对BlueAeri-PC或ip地址的侦听,具体步骤如下: 1.启动Net Manager,在“监听程序”--Listener下添加一个地址,主机名写计

Anaconda 中遇到CondaHTTPError: HTTP 404 NOT FOUND for url的问题及解决办法

最近在跑一个开源项目遇到了以下问题,查了很多资料都大(抄)同(来)小(抄)异(去)的,解决不了根本问题,费了很大的劲终于得以解决,记录如下: 1、问题及过程: (myenv) D:\Workspace\python\XXXXX>conda install python=3.6.13 Solving environment: done.....Proceed ([y]/n)? yDownloa

Jenkins 插件 地址证书报错问题解决思路

问题提示摘要: SunCertPathBuilderException: unable to find valid certification path to requested target...... 网上很多的解决方式是更新站点的地址,我这里修改了一个日本的地址(清华镜像也好),其实发现是解决不了上述的报错问题的,其实,最终拉去插件的时候,会提示证书的问题,几经周折找到了其中一遍博文

Android逆向(反调,脱壳,过ssl证书脚本)

文章目录 总结 基础Android基础工具 定位关键代码页面activity定位数据包参数定位堆栈追踪 编写反调脱壳好用的脚本过ssl证书校验抓包反调的脚本打印堆栈bilibili反调的脚本 总结 暑假做了两个月的Android逆向,记录一下自己学到的东西。对于app渗透有了一些思路。 这两个月主要做的是代码分析,对于分析完后的持久化等没有学习。主要是如何反编译源码,如何找到

3.比 HTTP 更安全的 HTTPS(工作原理理解、非对称加密理解、证书理解)

所谓的协议 协议只是一种规则,你不按规则来就无法和目标方进行你的工作 协议说白了只是人定的规则,任何人都可以定协议 我们不需要太了解细节,这些制定和完善协议的人去做的,我们只需要知道协议的一个大概 HTTPS 协议 1、概述 HTTPS(Hypertext Transfer Protocol Secure)是一种安全的超文本传输协议,主要用于在客户端和服务器之间安全地传输数据