謠言四起,大限將至忍些。各種謠言皆因蘋(píng)果開(kāi)發(fā)者大會(huì)開(kāi)始鲁猩,從那個(gè)時(shí)間開(kāi)始,都說(shuō)2017年1月1日為HPPTS即將開(kāi)始的日子罢坝。從此大航海時(shí)代就要開(kāi)始了廓握。從此就成了我揮之不去的心魔,嚇得本大少和服務(wù)器端調(diào)呀調(diào)∠度總算調(diào)好了男应。好吧,我們聊聊HTTPS娱仔。
一沐飘、HTTPS
HTTPS(全稱:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全為目標(biāo)的HTTP通道牲迫,簡(jiǎn)單講是HTTP的安全版耐朴。即HTTP下加入SSL層,HTTPS的安全基礎(chǔ)是SSL盹憎,因此加密的詳細(xì)內(nèi)容就需要SSL筛峭。 它是一個(gè)URI scheme(抽象標(biāo)識(shí)符體系),句法類同http:體系脚乡。用于安全的HTTP數(shù)據(jù)傳輸蜒滩。https:URL表明它使用了HTTP滨达,但HTTPS存在不同于HTTP的默認(rèn)端口及一個(gè)加密/身份驗(yàn)證層(在HTTP與TCP之間)奶稠。這個(gè)系統(tǒng)的最初研發(fā)由網(wǎng)景公司(Netscape)進(jìn)行,并內(nèi)置于其瀏覽器Netscape Navigator中捡遍,提供了身份驗(yàn)證與加密通訊方法锌订。(摘自百度百科)
PKI(公鑰基礎(chǔ)設(shè)施)技術(shù)是HTTPS的基礎(chǔ),PKI與非對(duì)稱密鑰加密技術(shù)密切相關(guān)画株,包括消息摘要辆飘、數(shù)字簽名和加密服務(wù),而數(shù)字證書(shū)以及證書(shū)機(jī)構(gòu)(CA – Certificate Authority)是PKI中的重要概念谓传。
二蜈项、Apple CSR CER P12 mobileprovition 到底是什么
CSR(Certificate Signing Request)鑰匙串文件 為生成證書(shū)做基礎(chǔ),要生成CER證書(shū)必須要有CSR私鑰续挟,此私鑰包含了用戶自己的一些信息紧卒。這個(gè)文件是保存在我們的mac的(keychain)里面的, 此文件包含了(公鑰和私鑰)
CER 包含了開(kāi)發(fā)者信息和公鑰
P12 它不僅包含CER的信息,還有私鑰信息诗祸,即: P12備份文件 = CER文件 + 私鑰跑芳;所以有了這個(gè)p12就再也不用擔(dān)心證書(shū)丟失了
mobileprovition 包含了上述所有內(nèi)容 Certificate && App ID && Device, 這個(gè)Provisioning Profile文件會(huì)在打包時(shí)嵌入到.ipa的包里。本人理解的是 可以真機(jī)調(diào)試的憑證直颅。
三博个、App Transport Security
iOS9中新增App Transport Security(簡(jiǎn)稱ATS)特性, 主要使到原來(lái)請(qǐng)求的時(shí)候用到的HTTP,都轉(zhuǎn)向TLS1.2協(xié)議進(jìn)行傳輸功偿。這也意味著所有的HTTP協(xié)議都強(qiáng)制使用了HTTPS協(xié)議進(jìn)行傳輸盆佣。
一般我們?nèi)绻€是使用的http,不更新的話,可通過(guò)在 Info.plist 中聲明,倒退回不安全的網(wǎng)絡(luò)請(qǐng)求
然后好像我說(shuō)這么多是不是一點(diǎn)屌用都沒(méi)用共耍?想知道這么改不投蝉?接下來(lái)我們繼續(xù)說(shuō)正事了。我這里簡(jiǎn)單說(shuō)下雙向認(rèn)證的自簽名HTTPS證書(shū)的使用征堪。放心瘩缆,不坑。
準(zhǔn)備證書(shū)
首先找后臺(tái)要一個(gè)證書(shū)(SSL證書(shū),一般你跟后臺(tái)說(shuō)要弄https佃蚜,然后讓他給你個(gè)證書(shū)庸娱,他就知道了),
我們需要的是.cer的證書(shū)谐算。但是后臺(tái)可能給我們的是.crt的證書(shū)熟尉。
我們需要轉(zhuǎn)換一下:打開(kāi)終端 -> cd到.crt證書(shū)路徑 -> 輸入openssl x509 -in 你的證書(shū).crt -out 你的證書(shū).cer -outform der
證書(shū)就準(zhǔn)備好了,拖入工程洲脂,記得選copy斤儿。一般叫做servicer.cer
--此段引用自大神vision_colion的文章,他文章里面有單向認(rèn)證的哦恐锦。
然后我們還得需要一個(gè)client.p12證書(shū).還是問(wèn)服務(wù)器端給往果。
//AFNetWoking3.0以上適用
- (void)testAFNetWorking{
NSString *certFilePath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:certFilePath];
NSSet *certSet = [NSSet setWithObject:certData];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:certSet];
policy.allowInvalidCertificates = YES;
policy.validatesDomainName = NO;
_manager = [AFHTTPSessionManager manager];
_manager.securityPolicy = policy;
_manager.requestSerializer = [AFHTTPRequestSerializer serializer];
_manager.responseSerializer = [AFHTTPResponseSerializer serializer];
_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
// [manager.securityPolicy setAllowInvalidCertificates:YES];
//關(guān)閉緩存避免干擾測(cè)試r
_manager.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[_manager setSessionDidBecomeInvalidBlock:^(NSURLSession * _Nonnull session, NSError * _Nonnull error) {
NSLog(@"setSessionDidBecomeInvalidBlock");
}];
__weak typeof(self)weakSelf = self;
[_manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession*session, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing*_credential) {
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__autoreleasing NSURLCredential *credential;
if([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if([weakSelf.manager.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
if(credential) {
disposition =NSURLSessionAuthChallengeUseCredential;
} else {
disposition =NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
} else {
// client authentication
SecIdentityRef identity = NULL;
SecTrustRef trust = NULL;
NSString *p12 = [[NSBundle mainBundle] pathForResource:@"client"ofType:@"p12"];
NSFileManager *fileManager =[NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:p12])
{
NSLog(@"client.p12:not exist");
}
else
{
NSData *PKCS12Data = [NSData dataWithContentsOfFile:p12];
if ([[weakSelf class]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;
}];
[_manager POST:@"https://192.168.0.51/dw-api-V2.0/user/login.p" parameters:@{@"yhzh":@"18639398700",@"infoMap":@"g+bc4UTf3wHjabyKW+RYqcervD+/HSJXFIRKdVCQYldN5j85x//6eVUUZsidGrUpE+MJCvHdo7/E4EjNT+hjvnYa5qJ9ep0maOWfvq6AkIinjjc9cQJ0cfEAsg2LnV17hJKi3hCRrjbQJfAqUB2C3IetHK9Gg0voOmcTK2IA1J/V+KRcCtb1XncXDxVnXiUT/qBIQKPEg3/dt5ISLHpdXQ=="} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *message = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@",message);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
}];
}
//驗(yàn)證你P12證書(shū)的
+ (BOOL)extractIdentity:(SecIdentityRef*)outIdentity andTrust:(SecTrustRef *)outTrust fromPKCS12Data:(NSData *)inPKCS12Data {
OSStatus securityError = errSecSuccess;
//client certificate password 你的p12密碼
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;
}