iOS-HTTPS双向认证以及证书操作

敲的是代码,写的是情怀

待完善

双向认证

  • 双向认证代理处理
    简单的请求
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://192.168.31.63:443"]];
    // 2.创建一个网络请求
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    // 3.获得会话对象
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    // 4.根据会话对象,创建一个Task任务:
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"从服务器获取到数据");
        /*
         对从服务器获取到的数据data进行相应的处理:
         */
        NSLog(@"data = %@",data);
    }];
    // 5.最后一步,执行任务(resume也是继续执行):
    [sessionDataTask resume];
    return;

NSURLSessionTaskDelegate或 NSURLSessionDelegate代理处理双向认证

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
    NSLog(@"证书认证");
    //NSURLAuthenticationMethodClientCertificate
    //NSURLAuthenticationMethodServerTrust
    if ([[[challenge protectionSpace] authenticationMethod]isEqualToString:@"NSURLAuthenticationMethodServerTrust"])
    {
        OSStatus err;
        SecTrustRef trust ;
        SecCertificateRef serverCert;
        SecTrustResultType      trustResult;
        BOOL trusted;
        trust = [[challenge protectionSpace] serverTrust];
        if (SecTrustGetCertificateCount(trust) > 0) {
            serverCert = SecTrustGetCertificateAtIndex(trust, 0);
        }
        
        NSArray *anchors = [NSArray array];
        SecTrustSetAnchorCertificates(trust, (CFArrayRef)anchors);
        err = SecTrustEvaluate(trust,&trustResult);
        trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
        
        NSURLCredential* newCredential = [NSURLCredential credentialForTrust:trust];
        completionHandler(NSURLSessionAuthChallengeUseCredential, newCredential);

    } else {
        if ([[[challenge protectionSpace] authenticationMethod]isEqualToString:@"NSURLAuthenticationMethodClientCertificate"])
        {
            SecIdentityRef identity = NULL;
            SecTrustRef trust = NULL;
            NSURLCredential* credential;
            
            NSData * cerData ;
            NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"samp" ofType:@"p12"];//自签名证书
            cerData = [NSData dataWithContentsOfFile:cerPath];
            
            SecCertificateRef certificate = NULL;
            if ([self extractIdentity:&identity andTrust:&trust fromPKCS12Data:cerData])
            {
                SecIdentityCopyCertificate(identity, &certificate);
                const void*certs[] = {certificate};
                CFArrayRef certArray =CFArrayCreate(kCFAllocatorDefault, certs,1,NULL);
                credential =[NSURLCredential credentialWithIdentity:identity certificates:(__bridge  NSArray*)certArray persistence:NSURLCredentialPersistencePermanent];
            }            
            //关键回传NSURLCredential 证书凭证
            //NSURLCredential * getCredential = [NSURLCredential credentialWithIdentity:(SecIdentityRef)identity certificates:nil persistence:NSURLCredentialPersistenceForSession];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        }
    }
//读取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;
}

获取证书

  • 获取keychain中的证书

获取证书内部信息

证书获得的公钥(CertificatePublicKey),序列号(CertificateSerialNumber) 的 NSData 为十六进制字符串.
iOS-NSData和十六进制字符串之间的相互转换
iOS-获取SecKeyRef的公钥 转NSData
Examining a Certificate苹果文档:获取公钥等的API

  • 获取Certificate的Base64,证书中的公钥,序列号
CFArrayRef          certificateRef;
int                 identityID;
//SecCertificateRef certificate//证书对象
- (NSString *)getCertificatePublicKey {
    // samli 获取公钥
    NSString *publicKey;
    SecKeyRef derKey  =SecCertificateCopyPublicKey((SecCertificateRef)CFArrayGetValueAtIndex(certificateRef, identityID));
    NSData *data = [self getPublicKeyBitsFromKey:derKey];
    publicKey = [self convertDataToHexStr:data];
    
    return publicKey ;
}
- (NSString *)getCertificateSerialNumber {
    // samli 获取序列号
    CFErrorRef  * error;
    CFDataRef  derData;
    if (@available(iOS 11.0, *)) {
        // CFDataRef SecCertificateCopySerialNumberData(SecCertificateRef certificate, CFErrorRef *error)
        derData = SecCertificateCopySerialNumberData((SecCertificateRef)CFArrayGetValueAtIndex(certificateRef, identityID),error);
    } else {
        // Fallback on earlier versions
        // CFDataRef SecCertificateCopySerialNumber(SecCertificateRef certificate)
        derData = SecCertificateCopySerialNumber((SecCertificateRef)CFArrayGetValueAtIndex(certificateRef, identityID));
    }
    NSData *data = (__bridge NSData *)derData;
    NSString * SerialNumber  = [self convertDataToHexStr:data];
    
    return SerialNumber ;
}
- (NSString*)getCertificateBase64
{
    // samli 获取证书的base64
    CFDataRef    derData  = SecCertificateCopyData((SecCertificateRef)CFArrayGetValueAtIndex(certificateRef, identityID));
    
    NSData *data = (__bridge NSData *)derData;
    unsigned char *pb64 = base64([data bytes],[data length]);
    NSString *certBase64 = [[NSString alloc]initWithBytes:pb64 length:strlen(pb64) encoding:NSUTF8StringEncoding];
    free(pb64);
    
    return certBase64;
}
  • 上面获取Certificate信息用到方法
- (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}
- (NSData *)getPublicKeyBitsFromKey:(SecKeyRef)givenKey {
    
    static const uint8_t publicKeyIdentifier[] = "com.your.company.publickey";
    NSData *publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
    
    OSStatus sanityCheck = noErr;
    NSData * publicKeyBits = nil;
    
    NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
    [queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
    [queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
    [queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
    
    // Temporarily add key to the Keychain, return as data:
    NSMutableDictionary * attributes = [queryPublicKey mutableCopy];
    [attributes setObject:(__bridge id)givenKey forKey:(__bridge id)kSecValueRef];
    [attributes setObject:@YES forKey:(__bridge id)kSecReturnData];
    CFTypeRef result;
    sanityCheck = SecItemAdd((__bridge CFDictionaryRef) attributes, &result);
    if (sanityCheck == errSecSuccess) {
        publicKeyBits = CFBridgingRelease(result);
        
        // Remove from Keychain again:
        (void)SecItemDelete((__bridge CFDictionaryRef) queryPublicKey);
    }
    
    return publicKeyBits;
}
/*  samli 此方法使用的 openssl.fremework  */
unsigned char *base64(const void *input, int length)
{
    BIO *bmem, *b64;
    BUF_MEM *bptr;
    
    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_write(b64, input, length);
    BIO_flush(b64);
    BIO_get_mem_ptr(b64, &bptr);
    
    unsigned char *buff = (unsigned char *)malloc(bptr->length);
    memcpy(buff, bptr->data, bptr->length-1);
    buff[bptr->length-1] = 0;
    
    BIO_free_all(b64);
    return buff;
}

End

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容