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

news/2024/11/8 12:00:33/

之前开发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

http://www.ppmy.cn/news/721823.html

相关文章

iOS推送证书显示“此证书不受信任”

配置推送证书的时候&#xff0c;一打开就变成不受信任&#xff0c;搜了很多解决版本。 第一种说是双击证书&#xff0c;打开之后在信任里面选择“始终信任” 这个选择信任之后&#xff0c;证书变成这样了,显示“此证书已标记为受此账户信任” 至于能不能用不清楚&#xff0c;因…

解决iOS 证书不受信任的问题

1.当我们在苹果开发者后台下载了一个cer证书或者p12证书后&#xff0c;双击会把证书安装到钥匙串里面 2.这个时候我们会发现该证书不受信任 原因&#xff1a;可能清理钥匙串证书时&#xff0c;不小心把AppleWWDRCA这个证书删除了。 3.解决方案 重新下载AppleWWDRCA并安装。即…

iOS打开应用提示未受信任的企业级开发者

安装ipa包时&#xff0c;成功安装好应用之后发现不能打开应用&#xff0c;提示“未受信任的企业级开发者”。 出现的问题&#xff1a; 解决的方法&#xff1a; 转载请注明出处&#xff1a;http://blog.csdn.net/chen_gp_x

解决iOS10.3打开APP提示未受信任的企业级开发者

非App store安装的程序&#xff0c;会提示&#xff1a;“未受信任的企业级开发者”&#xff0c;无法打开&#xff0c;而且也没有提示如何操作。 具体设设置方法如下&#xff1a; 设置 – 通用 – 设备管理 – 选择应用 – 信任

未受信任的发布者

同样是昨天遇到的问题&#xff0c;电脑由于出现问题&#xff0c;所以想尝试安装杀毒软件去查杀病毒&#xff0c;但是在安装软件的时候弹出如下对话框&#xff1a;&#xff08;图片来源于网络&#xff0c;当时自己没有截图&#xff09; 第一次如遇到这个问题的时候&#xff0c;…

数据库三范式是什么?

数据库三范式是什么&#xff1f; 数据库三范式&#xff08;Normalization&#xff09;是数据库设计中的一种规范标准&#xff0c;旨在减少数据冗余并建立结构合理的数据库&#xff0c;以提高数据存储和使用的性能。三范式是按照数据依赖性的程度来划分的&#xff0c;包括第一范…

MySql入门操作

一.前节回顾 1.web项目环境配置 2.通用增删改&#xff0c;通用查询方法 3.前台&#xff0c;后台代码显示效果 所有你都理解了吗&#xff1f; 二.Mysql数据库介绍 1.什么是MySQL&#xff1f; MySQL是一种开源的关系型数据库管理系统。它是目前最流行和广泛使用的数据库之一&…

rust不是steam好友_《Rust》开发者说,Steam玩家退款给他带来了400多万美元损失

原标题&#xff1a;《Rust》开发者说&#xff0c;Steam玩家退款给他带来了400多万美元损失 自2013年底推出抢先体验版以来&#xff0c;《Rust》在Steam上一直拥有较高的人气。在本作商店页面&#xff0c;仅玩家评测数就超过14万个。 虽然游戏卖得不错&#xff0c;本作的退款玩家…