iOS程序犭袁网络及安全iOS开发资料收集区

iOSHttps单双向认证

2016-12-15  本文已影响467人  IOS_龙

前言

一.单向认证

Https在建立Socket连接之前,需要进行握手。

二.双向认证

双向认证和单向认证原理基本差不多,只是除了客户端需要认证服务端以外,增加了服务端对客户端的认证。
下面以一个简单的例子说明:点此下载Demo
温馨提示:
证书需要提前准备好分别是.cer的 和 .p12 的,别的就很简单了。
示例代码如下:
在UIAHttps.h中
//
// UIAHttps.h
// UIADemo
//
// Created by zhangchao on 16/12/13.
// Copyright © 2016年 王龙. All rights reserved.
//

  #import <Foundation/Foundation.h>
  NS_ASSUME_NONNULL_BEGIN

  @interface UIAHttps : NSObject

  + (UIAHttps *)shared;

  - (void)POST:(NSString *)urlString
    Dictionary:(NSDictionary *)dic
      progress:(nullable void (^)(NSProgress   *uploadProgress))uploadProgress
       success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
       failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
  @end

  NS_ASSUME_NONNULL_END


   在UIAHttps.m中
  //
  //  UIAHttps.m
  //  UIADemo
  //
  //  Created by zhangchao on 16/12/13.
  //  Copyright © 2016年 王龙. All rights reserved.
  //

  #import "UIAHttps.h"
  #import <AFNetworking.h>

  @implementation UIAHttps
  static UIAHttps *https = nil;
  + (UIAHttps *)shared {
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          if(https == nil) {
              https = [[UIAHttps alloc] init];
          }        
      });
      return https;
  }

  - (void)POST:(NSString *)urlString
    Dictionary:(NSDictionary *)dic
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
 success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
 failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
  {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    设置超时时间
[manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 30.f;
[manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
[manager.requestSerializer setValue:@"Content-Type" forHTTPHeaderField:@"application/json; charset=utf-8"];
[manager setSecurityPolicy:[self customSecurityPolicy]];
[self checkCredential:manager];

NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];    
[manager POST:urlString parameters:jsonString progress:uploadProgress success:success failure:failure];
  }

  - (AFSecurityPolicy*)customSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//tomcat1(1)
NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:cerPath];
NSSet   *dataSet = [NSSet setWithArray:@[certData]];
[securityPolicy setAllowInvalidCertificates:YES];
[securityPolicy setPinnedCertificates:dataSet];
[securityPolicy setValidatesDomainName:YES];

return securityPolicy;
  }

  //校验证书
  - (void)checkCredential:(AFURLSessionManager *)manager
  {
[manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
}];
__weak typeof(manager)weakManager = manager;
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __autoreleasing NSURLCredential *credential =nil;
    NSLog(@"authenticationMethod=%@",challenge.protectionSpace.authenticationMethod);
    //判断是核验客户端证书还是服务器证书
    if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // 基于客户端的安全策略来决定是否信任该服务器,不信任的话,也就没必要响应挑战
        if([weakManager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
            // 创建挑战证书(注:挑战方式为UseCredential和PerformDefaultHandling都需要新建挑战证书)
            NSLog(@"serverTrust=%@",challenge.protectionSpace.serverTrust);
            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            // 确定挑战的方式
            if (credential) {
                //证书挑战  设计policy,none,则跑到这里
                disposition = NSURLSessionAuthChallengeUseCredential;
            } else {
                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            }
        } else {
            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
        }
    } else {
        // client authentication
        SecIdentityRef identity = NULL;
        SecTrustRef trust = NULL;
        NSString *p12 = [[NSBundle mainBundle] pathForResource:@"app"ofType:@"p12"];
        NSFileManager *fileManager =[NSFileManager defaultManager];
        
        if(![fileManager fileExistsAtPath:p12])
        {
            NSLog(@"client.p12:not exist");
        }
        else
        {
            NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
            
            if ([self extractIdentity:&identity andTrust:&trust fromPKCS12Data:PKCS12Data])
            {
                SecCertificateRef certificate = NULL;
                SecIdentityCopyCertificate(identity, &certificate);
                const void*certs[] = {certificate};
                CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
                credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
                disposition =NSURLSessionAuthChallengeUseCredential;
            }
        }
    }
    *_credential = credential;
    return disposition;
}];
  }

  //读取p12文件中的密码
  - (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError = errSecSuccess;
//client certificate password
NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObject:@"123456"
                                                             forKey:(__bridge id)kSecImportExportPassphrase];

CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import((__bridge CFDataRef)inPKCS12Data,(__bridge CFDictionaryRef)optionsDictionary,&items);

if(securityError == 0) {
    CFDictionaryRef myIdentityAndTrust =CFArrayGetValueAtIndex(items,0);
    const void*tempIdentity =NULL;
    tempIdentity= CFDictionaryGetValue (myIdentityAndTrust,kSecImportItemIdentity);
    *outIdentity = (SecIdentityRef)tempIdentity;
    const void*tempTrust =NULL;
    tempTrust = CFDictionaryGetValue(myIdentityAndTrust,kSecImportItemTrust);
    *outTrust = (SecTrustRef)tempTrust;
} else {
    NSLog(@"Failedwith error code %d",(int)securityError);
    return NO;
}
return YES;
  }
  @end








  在viewController.m中即可调用
   //
   //  ViewController.m
  //  HttpsDemo
  //
  //  Created by 王龙 on 16/12/15.
  //  Copyright © 2016年 王龙. All rights reserved.
  //

  #import "ViewController.h"
  #import "UIAHttps.h"

  @interface ViewController ()

  @end

  @implementation ViewController

  - (void)viewDidLoad {
      [super viewDidLoad];
      NSDictionary *dic = @{
                      @"cardno":@"411321199311083311",
                      @"mobile":@"15726618328",
                      @"msgtype":@"0002",
                      @"name":@"小张",
                      @"password":@"FCE98C9B0907B94978AF97358F9FA442",
                  @"signature":@"B1E0507EA0C356719E0D5F900AAB9B0D85D3C62F2881C89777A0F7894C57DE5FB1C6B4D87E452D0053A9B0C69F87F4FA91B7B6ECE3ABAE816CF7EEADBBE5722C8F1BB01406C61073D9941E985CED39B01E95D141D3E81FBD285A410E52806601B9C0C8D470932FD71CA3C660CCEF14C57DCF089B877B7213B5DF2D7BA18488BA5B3743",
                      @"username":@"1001100112"
                      };
  //此字典格式为我们公司 服务器需要的格式,只需按照自己的需求改动即可
      [[UIAHttps shared]POST:@"https://172.16.40.71:15025" Dictionary:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"发送成功");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"发送失败");
}];
  }

  - (void)didReceiveMemoryWarning {
      [super didReceiveMemoryWarning];
      // Dispose of any resources that can be recreated.
  }

  @end
上一篇下一篇

猜你喜欢

热点阅读