iOS开发基础109-网络安全
在iOS开发中,保障应用的网络安全是一个非常重要的环节。以下是一些常见的网络安全措施及对应的示例代码:
Swift版
1. 使用HTTPS
确保所有的网络请求使用HTTPS协议,以加密数据传输,防止中间人攻击。
示例代码:
在Info.plist中配置App Transport Security (ATS):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
2. SSL Pinning
通过SSL Pinning可以确保应用程序只信任指定的服务器证书,防止被劫持到伪造的服务器。
示例代码:
import Foundation
class URLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if let serverTrust = challenge.protectionSpace.serverTrust,
SecTrustEvaluate(serverTrust, nil) == errSecSuccess,
let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let localCertificateData = try? Data(contentsOf: Bundle.main.url(forResource: "your_cert", withExtension: "cer")!)
let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data
if localCertificateData == serverCertificateData {
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
return
}
}
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
// Usage
let url = URL(string: "https://yoursecurewebsite.com")!
let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(), delegateQueue: nil)
let task = session.dataTask(with: url) { data, response, error in
// Handle response
}
task.resume()
3. 防止SQL注入
在处理用户输入时,使用参数化查询来防止SQL注入攻击。
示例代码:
import SQLite3
func queryDatabase(userInput: String) {
var db: OpaquePointer?
// Open database (assuming dbPath is the path to your database)
sqlite3_open(dbPath, &db)
var queryStatement: OpaquePointer?
let query = "SELECT * FROM users WHERE username = ?"
if sqlite3_prepare_v2(db, query, -1, &queryStatement, nil) == SQLITE_OK {
sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)
while sqlite3_step(queryStatement) == SQLITE_ROW {
// Process results
}
}
sqlite3_finalize(queryStatement)
sqlite3_close(db)
}
4. Data Encryption
在存储敏感数据时,使用iOS的加密库来加密数据,比如使用Keychain。
示例代码:
import Security
func saveToKeychain(key: String, data: Data) -> OSStatus {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data
]
SecItemDelete(query as CFDictionary) // Delete any existing item
return SecItemAdd(query as CFDictionary, nil) // Add new item
}
func loadFromKeychain(key: String) -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue!,
kSecMatchLimit as String: kSecMatchLimitOne
]
var dataTypeRef: AnyObject?
let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == noErr {
return dataTypeRef as? Data
} else {
return nil
}
}
5. 输入验证与清理
对用户输入进行验证和清理,防止XSS(跨站脚本攻击)和其他注入攻击。
示例代码:
func sanitize(userInput: String) -> String {
// Remove any script tags or other potentially dangerous content
return userInput.replacingOccurrences(of: "<script>", with: "", options: .caseInsensitive)
.replacingOccurrences(of: "</script>", with: "", options: .caseInsensitive)
}
// Usage
let userInput = "<script>alert('xss')</script>"
let sanitizedInput = sanitize(userInput: userInput)
print(sanitizedInput) // Outputs: alert('xss')
OC版
1. 使用HTTPS
确保所有的网络请求都使用HTTPS协议,以加密数据传输,防止中间人攻击。
示例代码:
在Info.plist中配置App Transport Security (ATS):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
2. SSL Pinning
通过SSL Pinning可以确保应用程序只信任指定的服务器证书,防止被劫持到伪造的服务器。
示例代码:
#import <Foundation/Foundation.h>
@interface URLSessionPinningDelegate : NSObject <NSURLSessionDelegate>
@end
@implementation URLSessionPinningDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
NSString *certPath = [[NSBundle mainBundle] pathForResource:@"your_cert" ofType:@"cer"];
NSData *localCertData = [NSData dataWithContentsOfFile:certPath];
NSData *serverCertData = (__bridge NSData *)(SecCertificateCopyData(serverCertificate));
if ([localCertData isEqualToData:serverCertData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
return;
}
}
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
@end
// Usage
NSURL *url = [NSURL URLWithString:@"https://yoursecurewebsite.com"];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
URLSessionPinningDelegate *pinningDelegate = [[URLSessionPinningDelegate alloc] init];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:pinningDelegate delegateQueue:nil];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Handle response
}
}];
[task resume];
3. 防止SQL注入
在处理用户输入时,使用参数化查询来防止SQL注入攻击。
示例代码:
#import <sqlite3.h>
- (void)queryDatabase:(NSString *)userInput {
sqlite3 *db;
// Open database (assuming dbPath is the path to your database)
if (sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
sqlite3_stmt *statement;
const char *query = "SELECT * FROM users WHERE username = ?";
if (sqlite3_prepare_v2(db, query, -1, &statement, NULL) == SQLITE_OK) {
sqlite3_bind_text(statement, 1, [userInput UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) == SQLITE_ROW) {
// Process results
}
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
4. Data Encryption
在存储敏感数据时,使用iOS的加密库来加密数据,比如使用Keychain。
示例代码:
#import <Security/Security.h>
- (OSStatus)saveToKeychainWithKey:(NSString *)key data:(NSData *)data {
NSDictionary *query = @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccount: key,
(__bridge id)kSecValueData: data};
SecItemDelete((__bridge CFDictionaryRef)query); // Delete any existing item
return SecItemAdd((__bridge CFDictionaryRef)query, NULL); // Add new item
}
- (NSData *)loadFromKeychainWithKey:(NSString *)key {
NSDictionary *query = @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccount: key,
(__bridge id)kSecReturnData: (__bridge id)kCFBooleanTrue,
(__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne};
CFTypeRef dataTypeRef = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataTypeRef);
if (status == noErr) {
return (__bridge_transfer NSData *)dataTypeRef;
} else {
return nil;
}
}
5. 输入验证与清理
对用户输入进行验证和清理,防止XSS(跨站脚本攻击)和其他注入攻击。
示例代码:
- (NSString *)sanitize:(NSString *)userInput {
// Remove any script tags or other potentially dangerous content
NSString *sanitizedInput = [userInput stringByReplacingOccurrencesOfString:@"<script>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, userInput.length)];
sanitizedInput = [sanitizedInput stringByReplacingOccurrencesOfString:@"</script>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sanitizedInput.length)];
return sanitizedInput;
}
// Usage
NSString *userInput = @"<script>alert('xss')</script>";
NSString *sanitizedInput = [self sanitize:userInput];
NSLog(@"%@", sanitizedInput); // Outputs: alert('xss')
通过这些措施,你可以显著提升iOS应用的网络安全性。根据项目需求,灵活运用这些技术以确保用户数据的安全。
iOS开发基础109-网络安全的更多相关文章
- IOS开发基础知识碎片-导航
1:IOS开发基础知识--碎片1 a:NSString与NSInteger的互换 b:Objective-c中集合里面不能存放基础类型,比如int string float等,只能把它们转化成对象才可 ...
- iOS开发——总结篇&IOS开发基础知识
IOS开发基础知识 1:Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id) 对象在运行时获取其类型的能力称为内省.内省可以有多种方法实现. 判断 ...
- IOS开发基础环境搭建
一.目的 本文的目的是windows下IOS开发基础环境搭建做了对应的介绍,大家可根据文档步骤进行mac环境部署: 二.安装虚拟机 下载虚拟机安装文件绿色版,点击如下文件安装 获取安装包: ...
- iOS开发基础-九宫格坐标(6)
继续对iOS开发基础-九宫格坐标(5)中的代码进行优化. 优化思路:把字典转模型部分的数据处理操作也拿到模型类中去实现,即将 ViewController 类实现中 apps 方法搬到 WJQAppI ...
- iOS开发基础-九宫格坐标(5)
继续在iOS开发基础-九宫格坐标(4)的基础上进行优化. 一.改进思路 1)iOS开发基础-九宫格坐标(4)中 viewDidLoad 方法中的第21.22行对控件属性的设置能否拿到视图类 WJQAp ...
- iOS开发基础-九宫格坐标(4)
对iOS开发基础-九宫格坐标(3)的代码进行进一步优化. 新建一个 UIView 的子类,并命名为 WJQAppView ,将 appxib.xib 中的 UIView 对象与新建的视图类进行关联. ...
- iOS开发基础-九宫格坐标(3)之Xib
延续iOS开发基础-九宫格坐标(2)的内容,对其进行部分修改. 本部分采用 Xib 文件来创建用于显示图片的 UIView 对象. 一.简单介绍 Xib 和 storyboard 的比较: 1) X ...
- iOS开发基础-九宫格坐标(2)之模型
在iOS开发基础-九宫格(1)中,属性变量 apps 是从plist文件中加载数据的,在 viewDidLoad 方法中的第20行.26行中,直接通过字典的键名来获取相应的信息,使得 ViewCont ...
- iOS开发基础-图片切换(4)之懒加载
延续:iOS开发基础-图片切换(3),对(3)里面的代码用懒加载进行改善. 一.懒加载基本内容 懒加载(延迟加载):即在需要的时候才加载,修改属性的 getter 方法. 注意:懒加载时一定要先判断该 ...
- iOS开发基础-图片切换(3)之属性列表
延续:iOS开发基础-图片切换(2),对(2)里面的代码用属性列表plist进行改善. 新建 Property List 命名为 Data 获得一个后缀为 .plist 的文件. 按如图修改刚创建的文 ...
随机推荐
- NumPy 正态分布与 Seaborn 可视化指南
正态分布(高斯分布) 简介 正态分布(也称为高斯分布)是一种非常重要的概率分布,它描述了许多自然和人为现象的数据分布情况.正态分布的形状呈钟形,其峰值位于平均值处,两侧对称下降. 特征 正态分布可以用 ...
- C#开发的应用升级更新服务器端工具 - 开源研究系列文章 - 个人小作品
笔者开发过一些小应用,然后这些应用就需要有升级更新的功能,但是如果每个都集成进去也行,但是就是得写死更新的代码了.于是就想写一个应用升级更新的管理器,以前看到过Github上有一个AutoUpdate ...
- C# WinForm控件及其子控件转成图片(支持带滚动条的长截图)
概述(Overview) 参考了网上的分析,感觉都不太理想:1.一个控件内如果包含多个子控件时没有考虑顺序问题:2.超出控件可显示区域时不能长截图,有滚动条会多余截取了滚动条.这个随笔旨在解决这个问题 ...
- Rainbond 5.5 发布,支持Istio和扩展第三方Service Mesh框架
Rainbond 5.5 版本主要优化扩展性.服务治理模式可以扩展第三方 ServiceMesh 架构,兼容kubernetes 管理命令和第三方管理平台. 主要功能点解读: 1. 支持 Istio, ...
- IOS Video Tool Box后台解码失败
---恢复内容开始--- 1.VideoToolBox硬件解码H264流的过程中,如果App从前台按Home键进入后台,会立马产生一个-12903的错误 如果这个时候重置解码器,继续解码,会遇到 - ...
- Linux驱动--IOCTL实现
参考:[Linux]实现设备驱动的ioctl函数_哔哩哔哩_bilibili.<Linux设备驱动程序(中文第三版).pdf> 1 用户空间ioctl 用户空间的ioctl函数原型,参数是 ...
- ETL工具-nifi干货系列 第十二讲 nifi处理器UpdateRecord使用教程
1.上一节课我们讲解了nifi处理器UpdateAttribute,专门用来更新flowFile的属性字段.本节课我们一起来学习UpdateRecord,该处理器用来更新flowFile的流文件内容数 ...
- 使用 OpenTelemetry 构建可观测性 02 - 埋点
这是讲解 OpenTelemetry 系列博客的第二篇.在上一篇博客中,我们介绍了 OpenTelemetry 是什么以及由什么组成.现在我们将讨论如何使用 OTel 准确收集遥测数据和链路追踪数据. ...
- 什么Java注释
定义:用于解释说明程序的文字分类: 单行注释:格式: // 注释文字多行注释:格式: /* 注释文字 */ 文档注释:格式:/** 注释文字 */ 作用:在程序中,尤其是复杂的程序中,适当地加入注释可 ...
- Springboot - log4j2
log4j2 springboot中默认的日志框架是logback,如果要使用log4j2,需要先去除默认的日志框架 <!-- 去除系统默认的logback日志框架,使用自己配置的框架 --&g ...