DTLS-PSK連接建立(基于Network框架)

<Network/Network.h>庫是iOS12以后蘋果才公開的,部分接口iOS13才可用。下面的代碼是DTLS連接,基于純PSK建立的。具體的算法集可以根據需要切換。

  1. DTLSNetworkManager.h文件
//
//  DTLSNetworkManager.h
//  SSDPDemo
//
//  Created by yuchern on 2019/11/15.
//  Copyright ? 2019 yuchern. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <Network/Network.h>

NS_ASSUME_NONNULL_BEGIN

#ifdef __IPHONE_13_0

typedef void (^DTLSMessageHandle)(NSData *_Nullable data, NSError *_Nullable error);

typedef void (^DTLSSessionCompletedHandle)(NSError *_Nullable error);

/*
 nw_connection_state_invalid = 0,
 @const nw_connection_state_waiting The connection is waiting for a usable network before re-attempting
 nw_connection_state_waiting = 1,
 @const nw_connection_state_preparing The connection is in the process of establishing
 nw_connection_state_preparing = 2,
 @const nw_connection_state_ready The connection is established and ready to send and receive data upon
 nw_connection_state_ready = 3,
 @const nw_connection_state_failed The connection has irrecoverably closed or failed
 nw_connection_state_failed = 4,
 @const nw_connection_state_cancelled The connection has been cancelled by the caller
 nw_connection_state_cancelled = 5,
 */
typedef void (^DTLSConnectStateHandle)(nw_connection_state_t state, NSError  *_Nullable error);

@interface DTLSNetworkManager : NSObject

/// Config nw_parameters which include pskId, psk, ciphersuite
/// @param pskId pskId
/// @param psk psk
/// @param ciphersuite ciphersuite
- (void)setDTLSParamWithPskId:(NSString *)pskId
                          psk:(NSString *)psk
                  ciphersuite:(tls_ciphersuite_t)ciphersuite;

/// Connect to host
/// @param host IP
/// @param port port
/// @param queue queue
/// @param stateHandle callback
- (void)connectDTLSToHost:(NSString *)host
                     port:(NSString *)port
                    queue:(dispatch_queue_t)queue
              stateHandle:(DTLSConnectStateHandle)stateHandle;

/// Cancel nw_connection and set nil
- (void)closeDTLSConnect;

/// Send message
/// @param message message
/// @param complete complete
- (void)sendDTLSMessage:(NSData *)message
               complete:(DTLSSessionCompletedHandle)complete;

/// Receive message
/// @param receiveMessageHandle callback
- (void)receiveDTLSMessage:(DTLSMessageHandle)receiveMessageHandle;

@end
#endif

NS_ASSUME_NONNULL_END
  1. DTLSNetworkManager.m文件。
    代碼中包含了組包,如果你所做的項目數據頭不一樣,需要根據具體修改。
//
//  DTLSNetworkManager.m
//  SSDPDemo
//
//  Created by yuchern on 2019/11/15.
//  Copyright ? 2019 yuchern. All rights reserved.
//

#import "DTLSNetworkManager.h"


#ifdef __IPHONE_13_0

NSErrorDomain const DTLSConnectErrorDomain = @"com.home.DTLS.Network.connectHost.error";
NSErrorDomain const DTLSReceiveMessageErrorDomain = @"com..home.DTLS.Network.receiveMessage.error";
NSErrorDomain const DTLSSendMessageErrorDomain = @"com.home.DTLS.Network.sendMessage.error";

@interface DTLSNetworkManager()
@property (nonatomic, strong) nw_parameters_t params;
@property (nonatomic, strong) nw_connection_t connection;
@property (nonatomic, strong) dispatch_queue_t connectQueue;
@property (nonatomic, copy) DTLSMessageHandle receiveMessage;
@property (nonatomic, strong) NSMutableData *readBuf;
@end

@implementation DTLSNetworkManager

#pragma mark - Public

/// Config nw_parameters which include pskId, psk, ciphersuite
/// @param pskId pskId
/// @param psk psk
/// @param ciphersuite ciphersuite
- (void)setDTLSParamWithPskId:(NSString *)pskId
                          psk:(NSString *)psk
                  ciphersuite:(tls_ciphersuite_t)ciphersuite API_AVAILABLE(ios(13.0)){
    if (pskId == nil || [pskId isEqualToString:@""]) {
        return;
    }
    if (psk == nil || [psk isEqualToString:@""]) {
        return;
    }
    self.params = nw_parameters_create_secure_udp(^(nw_protocol_options_t  _Nonnull options) {
        sec_protocol_options_t option = nw_tls_copy_sec_protocol_options(options);
        dispatch_data_t pskIdData = [self dispatchDataFromNsdata:[pskId dataUsingEncoding:NSUTF8StringEncoding]];
        dispatch_data_t pskData = [self dispatchDataFromNsdata:[psk dataUsingEncoding:NSUTF8StringEncoding]];
        if (pskIdData == nil || pskData == nil) {
            return;
        }
        sec_protocol_options_add_pre_shared_key(option, pskData, pskIdData);
        sec_protocol_options_append_tls_ciphersuite(option, ciphersuite);
        sec_protocol_options_set_min_tls_protocol_version(option, tls_protocol_version_DTLSv12);
    }, ^(nw_protocol_options_t  _Nonnull options) {
        NW_PARAMETERS_DEFAULT_CONFIGURATION;
    });
}

/// Connect to host
/// @param host IP
/// @param port port
/// @param queue queue
/// @param stateHandle callback
- (void)connectDTLSToHost:(NSString *)host
                     port:(NSString *)port
                    queue:(dispatch_queue_t)queue
              stateHandle:(DTLSConnectStateHandle)stateHandle API_AVAILABLE(ios(13.0)) {
    if (host == nil || [host isEqualToString:@""]) {
        return;
    }
    if (port == nil || [port isEqualToString:@""]) {
        return;
    }
    nw_endpoint_t endpoint = nw_endpoint_create_host([host UTF8String], [port UTF8String]);
    self.connection = nw_connection_create(endpoint, self.params);
    nw_connection_set_queue(self.connection, queue);
    nw_connection_start(self.connection);
    nw_connection_set_state_changed_handler(self.connection, ^(nw_connection_state_t state, nw_error_t  _Nullable error) {
        NSError *nserror;
        if (error != nil) {
            nserror = [[NSError alloc] initWithDomain:DTLSConnectErrorDomain code:nw_error_get_error_code(error) userInfo:@{@"nw_connection_set_state_changed_handler: nw_error_get_error_domain": @(nw_error_get_error_domain(error))}];
        }
        if (stateHandle) {
            stateHandle(state, nserror);
        }
    });
    
    [self receiveMsg];
}

/// Cancel nw_connection and set nil
- (void)closeDTLSConnect API_AVAILABLE(ios(13.0)){
    nw_connection_cancel(self.connection);
    //    self.connection = nil;//置nil會報錯
    //    self.params = nil;
}

/// Send message
/// @param message message
/// @param complete complete
- (void)sendDTLSMessage:(NSData *)message
               complete:(DTLSSessionCompletedHandle)complete API_AVAILABLE(ios(13.0)) {
    NSData *sendMessage = [self sendMessagePack:message];
    dispatch_data_t data = [self dispatchDataFromNsdata:sendMessage];
    nw_connection_send(self.connection, data, NW_CONNECTION_FINAL_MESSAGE_CONTEXT, true, ^(nw_error_t  _Nullable error) {
        NSError *nserror;
        if (error != nil) {
            nserror = [[NSError alloc] initWithDomain:DTLSSendMessageErrorDomain code:nw_error_get_error_code(error) userInfo:@{@"nw_connection_send: nw_error_get_error_domain": @(nw_error_get_error_domain(error))}];
        }
        DEVELOPER_LOG_FORMAT(@"DTLS發送數據:%@",sendMessage);
        DDLogDebug(@"DTLS發送數據:%@",sendMessage);
        if (complete) {
            complete(nserror);
        }
    });
}

- (void)receiveDTLSMessage:(DTLSMessageHandle)receiveMessageHandle {
    self.receiveMessage = receiveMessageHandle;
}


#pragma mark - Private
/// Receive message
- (void)receiveMsg API_AVAILABLE(ios(13.0)) {
    __weak typeof (self)weakSelf = self;
    nw_connection_receive_message(self.connection, ^(dispatch_data_t  _Nullable content, nw_content_context_t  _Nullable context, bool is_complete, nw_error_t  _Nullable error) {
        DEVELOPER_LOG_FORMAT(@"DTLS接收數據:content=%@, context=%@, is_complete=%d, error=%@",content, context, is_complete, error);
        DDLogDebug(@"DTLS接收數據:content=%@, context=%@, is_complete=%d, error=%@",content, context, is_complete, error);
        __strong typeof (weakSelf)strongSelf = weakSelf;
        if (error == nil && content != nil) {
            NSData *data = [strongSelf nsdataFromDispatchData:content];
            if (data != nil) {
                [self receiveMessagePack:data];
            } else {
                NSError *nserror = [[NSError alloc] initWithDomain:DTLSReceiveMessageErrorDomain code:nw_error_get_error_code(error) userInfo:@{@"nw_connection_receive_message: nw_error_get_error_domain": @(nw_error_get_error_domain(error))}];
                if (strongSelf.receiveMessage) {
                    strongSelf.receiveMessage(nil, nserror);
                }
            }
            //nw_connection_receive_message函數只讀取一次消息,讀取完需要再次調用繼續讀取
        }else{
            NSError *nserror = [[NSError alloc] initWithDomain:DTLSReceiveMessageErrorDomain code:nw_error_get_error_code(error) userInfo:@{@"nw_connection_receive_message: nw_error_get_error_domain": @(nw_error_get_error_domain(error))}];
            if (strongSelf.receiveMessage) {
                strongSelf.receiveMessage(nil, nserror);
            }
        }
    });
}

/// 發送消息前進行組包,拼接包頭,0xfefe + 包長2字節。4個字節
/// @param data 數據
- (NSData *)sendMessagePack:(NSData *)data {
    NSInteger length = data.length;
    Byte byte[4] = {0xfe, 0xfe, length >> 8, length & 0x00ff};
    NSMutableData *mulData = [[NSMutableData alloc] init];
    [mulData appendData:[NSData dataWithBytes:byte length:sizeof(byte)]];
    [mulData appendData:data];
    return mulData;
}

/// 接收數據的拼包,解決粘包問題
/// @param data 數據
- (void)receiveMessagePack:(NSData *)data API_AVAILABLE(ios(13.0)) {
    //將數據存入緩存區
    [self.readBuf appendData:data];
    //包頭4個字節,2個字節fefe,2個字節包總長度
    while (self.readBuf.length > 4) {
        //將消息轉化成byte,計算總長度 = 數據的內容長度 + 前面4個字節的頭長度
        Byte *bytes = (Byte *)[self.readBuf bytes];
        if ((bytes[0]<<8) + bytes[1] == 0xfefe) {
            NSUInteger allLength = (bytes[2]<<8) + bytes[3] + 4;
            //緩存區的長度大于總長度,證明有完整的數據包在緩存區,然后進行處理
            if (self.readBuf.length >= allLength) {
                //提取出前面4個字節的頭內容,之所以提取出來,是因為在處理數據問題的時候,比如data轉json的時候,
                //頭內容里面包含非法字符,會導致轉化出來的json內容為空,所以要先去掉再處理數據問題
                NSMutableData *msgData = [[self.readBuf subdataWithRange:NSMakeRange(0, allLength)] mutableCopy];
                [msgData replaceBytesInRange:NSMakeRange(0, 4) withBytes:NULL length:0];
                
                if (self.receiveMessage) {
                    self.receiveMessage(msgData, nil);
                }
                //處理完數據后將處理過的數據移出緩存區
                self.readBuf = [NSMutableData dataWithData:[self.readBuf subdataWithRange:NSMakeRange(allLength, self.readBuf.length - allLength)]];
            }else{
                //緩存區內數據包不是完整的,再次從服務器獲取數據,中斷while循環
                [self receiveMsg];
                break;
            }
        } else {
            //如果包頭不符合要求則丟棄
            self.readBuf = nil;
            DDLogDebug(@"DTLS拼包數據錯誤:%@",self.readBuf);
            break;
        }
    }
    //讀取到服務端數據值后,能再次讀取
    [self receiveMsg];
}


#pragma mark - 轉換方法
/// Convert NSData to dispatch_data_t
/// @param nsdata NSData
- (dispatch_data_t)dispatchDataFromNsdata:(NSData *)nsdata API_AVAILABLE(ios(13.0)) {
    if (nsdata == nil) {
        return nil;
    }
    Byte byte[nsdata.length];
    [nsdata getBytes:byte length:nsdata.length];
    dispatch_data_t data = dispatch_data_create(byte, nsdata.length, nil, DISPATCH_DATA_DESTRUCTOR_DEFAULT);
    return data;
}

/// Convert dispatch_data_t to NSData
/// @param dispatchData dispatch_data_t
- (NSData *)nsdataFromDispatchData:(dispatch_data_t)dispatchData API_AVAILABLE(ios(13.0)) {
    if (dispatchData == nil) {
        return nil;
    }
    const void *buffer = NULL;
    size_t size = 0;
    dispatch_data_t new_data_file = dispatch_data_create_map(dispatchData, &buffer, &size);
    if(new_data_file) {/* to avoid warning really - since dispatch_data_create_map demands we
                        care about the return arg */}
    NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];
    return nsdata;
}

#pragma mark - 懶加載
- (NSMutableData *)readBuf {
    if (_readBuf == nil) {
        _readBuf = [[NSMutableData alloc] init];
    }
    return _readBuf;
}

@end
#endif
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 2,719評論 0 3
  • 在C語言中,五種基本數據類型存儲空間長度的排列順序是: A)char B)char=int<=float C)ch...
    夏天再來閱讀 3,391評論 0 2
  • ## 可重入函數 ### 可重入性的理解 若一個程序或子程序可以安全的被并行執行,則稱其為可重入的;即當該子程序正...
    夏至亦韻閱讀 725評論 0 0
  • 原文地址:https://github.com/JuanitoFatas/slime-user-manual#24...
    四月不見閱讀 3,186評論 0 2
  • 青春是一生中最美好的時光,穿著寬大的校服,背著書包,無憂無慮,和朋友們聊著八卦,女生們聊著哪個班有帥哥,哪個人長的...
    念lych閱讀 242評論 3 0