iOS一步步实现Https安全

步骤: 1.创建私钥与证书
2.搭建https-Node服务器
3.创建iOS-https项目
4.使用Charles工具抓包验证
私钥、证书
打开终端

//进入桌面 $ cd ~/Desktop/ //生产私钥 $ openssl genrsa 2048 > rsa_private_key.pem //由私钥生产证书请求(签名) $ openssl req -new -key rsa_private_key.pem -out certificate_request.csr //通过私钥文件和CSR证书签名生成证书文件(服务器证书) $ openssl x509 -req -days 365 -in certificate_request.csr -signkey rsa_private_key.pem -out cert.pem //转换证书(iOS端证书) $ openssl x509 -in cert.pem -out cert_ios.cer -outform der

//此时桌面上得到了我们需要的三个文件 rsa_private_key.pem(私钥) cert.pem(证书用于服务器端) cert_ios.cer(证书用于iOS端)

Node服务器
iOS一步步实现Https安全
文章图片
node目录.png
//index.js代码 var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('./rsa_private_key.pem'), cert: fs.readFileSync('./cert.pem') }; var params = { hi : 'Hello World!', hello : 'Hello Node!' }var server = https.createServer(options ,function(req, res){ res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(params)); }).listen(3000);

//命令行进入server目录 $ cd server //启动服务 $ node index.js

打开浏览器输入https://127.0.0.1:3000查看是否服务器已启动
iOS一步步实现Https安全
文章图片
https服务启动成功.png iOS-Https工程
Xcode创建iOS-Https工程,使用Cocoapods安装AFNetworking库,将cert_ios.cer证书拖至项目中(勾选copy)。
iOS一步步实现Https安全
文章图片
cert_ios.cer.png 【运行项目,有以下情景】
情景1.不安全(使用Charles的Https抓取可以解析所有信息)
客户端不验证服务器端证书真伪
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.securityPolicy.allowInvalidCertificates = YES; manager.securityPolicy.validatesDomainName = NO; NSString *url = @"https://192.168.1.106:3000"; //局域网真机调试 //NSString *url = @"https://127.0.0.1:3000"; //模拟器调试[manager GET:url parameters:@{@"name":@"ZZZ", @"age":@32} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id_Nullable responseObject) { NSLog(@"%@",responseObject); //2017-06-21 07:19:50.880 Https[3169:138713] { //hello = "Hello Node!"; //hi = "Hello World!"; //} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];

情景2:安全(Charles的Https只能抓取到ip和端口信息)
客户端验证服务器端证书真伪
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; //加载项目中的所有.cer文件 NSSet *certificates = [AFSecurityPolicy certificatesInBundle:[NSBundle mainBundle]]; //AFSSLPinningModePublicKey:公钥验证 //AFSSLPinningModeCertificate:证书验证 manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey withPinnedCertificates:certificates]; manager.securityPolicy.allowInvalidCertificates = YES; manager.securityPolicy.validatesDomainName = NO; NSString *url = @"https://192.168.1.106:3000"; //局域网真机调试 //NSString *url = @"https://127.0.0.1:3000"; //模拟器调试[manager GET:url parameters:@{@"name":@"ZZZ", @"age":@32} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id_Nullable responseObject) { NSLog(@"%@",responseObject); //2017-06-21 07:19:50.880 Https[3169:138713] { //hello = "Hello Node!"; //hi = "Hello World!"; //} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { }];


【iOS一步步实现Https安全】Charles-https抓包教程

    推荐阅读