iOS 开发随笔程序员iOS学习笔记

iOS 移动端接口加密流程(包含单点登录和失效时间)

2017-12-09  本文已影响199人  Alger_梁

iOS 移动端接口加密流程(包含单点登录和失效时间)

最近换了工作,新公司的一套面试题是关于移动端接口加密流程,当时根据面试题画出了大概的 UML 类图,但是还有很多考虑不周的情况。接触到代码后仔细研究看了一下数据请求逻辑,感觉还是有必要总结一下加深理解。

上送参数

中文说明 上送项 取值
平台 plat android 或者 iOS
版本号 ver 1.0
字段名称 中文含义 说明
timestamp 用户端时间戳 前后台约定好时间格式就行
rand 随机数 16位随机数,包含数字和字母
app_id 应用 id 后台分配的给每个版本使用的,尽量每个版本更新时更换一下,后面说明用处
sign 数据签名 MD5(除sign 以外的所有文字上送项+ private_key+app_id+rand+timestamp+plat+ver 按照参数名的字母顺序排序,按参数名=值&拼接,结尾没有&)

如:iOS 端

app_id=170ib799dd511e7b66000163e033322   
  private_key = 170ib799dd511e7b66000163e033322
app_id=170ib799dd511e7b66000163e033322&phoneNo=123456&password=123456&plat=iOS&rand=12dwfhdy487rSelsd&timestamp=2017-12-9-13:39:39:01&ver=1.0
app_id=170ib799dd511e7b66000163e033322&phoneNo=123456&password=123456&private_key=170ib799dd511e7b66000163e033322&plat=iOS&rand=12dwfhdy487rSelsd&timestamp=2017-12-9-13:39:39:01&ver=1.0

最终上送data + sign 如:

app_id=170ib799dd511e7b66000163e033322&phoneNo=123456&password=123456&plat=iOS&rand=12dwfhdy487rSelsd&timestamp=2017-12-9-13:39:39:01&ver=1.0&sign= 8357heukf384r83gh3fi3dwks42i993

这是签名管理类.h代码

#import <Foundation/Foundation.h>

@interface TPBaseRequest : NSObject

@property (nonatomic, strong) NSString *plat;
@property (nonatomic, strong) NSString *ver;

- (NSDictionary *)baseParameters;
- (NSDictionary *)finalParametersFrom:(NSDictionary *)dic;

@end

这是签名管理类.m代码

#import "TPBaseRequest.h"
#import <CommonCrypto/CommonDigest.h>

@interface TPBaseRequest()

@property (nonatomic, strong)NSString *rand;

@property (nonatomic, copy) NSString *timeStr;

@end

@implementation TPBaseRequest

//最终上送为data(base + dic)+sign
- (NSDictionary *)finalParametersFrom:(NSDictionary *)dic
{
    self.rand = [self gainRand];
    NSMutableDictionary *finalDic = [NSMutableDictionary dictionaryWithDictionary:[self baseParameters]];
    [finalDic removeObjectForKey:@"private_key"];
    [finalDic addEntriesFromDictionary:dic];
    [finalDic setObject:[self gainSign:dic] forKey:@"sign"];
    [finalDic setObject:_timeStr forKey:@"timestamp"];
    return finalDic;
}
//基础参数
- (NSDictionary *)baseParameters
{
    //基础参数赋值
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:kApp_id forKey:@"app_id"];
    [para setObject:kPrivate_key forKey:@"private_key"];
    [para setObject:@"ios" forKey:@"plat"];
    [para setObject:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] forKey:@"ver"];
    [para setObject:self.rand forKey:@"rand"];
    [para setObject:[self gainTimestamp] forKey:@"timestamp"];
    
    if([MDAccountStore isLogined]){
        if(![MDAccountManager sharedInstance].currentAccount){
            [MDAccountManager sharedInstance].currentAccount = [[MDAccountStore sharedInstance] readTheAccount];
        }
    }
    //判断是否有用户登录 如果有携带上 userId
    if ([MDAccountManager sharedInstance].currentAccount.userId) {
        long userId = [MDAccountManager sharedInstance].currentAccount.userId;
        [para setObject:[NSNumber numberWithLong:userId] forKey:@"userId"];
    }
    //判断本地存储是否有 token
    if ([MDAccountManager sharedInstance].currentAccount.token) {
        [para setObject:[MDAccountManager sharedInstance].currentAccount.token forKey:@"token"];
    }
    
    return [NSDictionary dictionaryWithDictionary:para];
}
//获取随机数
- (NSString *)gainRand
{
    NSString *str = [NSString string];
    //16位
    for (int i = 0; i < 16; i++)
    {
        //随机出现字母、数字
        switch(arc4random() % 3) {
            case 0:
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%d", arc4random() % 10]];
                break;
            case 1:
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%c",  (arc4random() % 26) + 97]];
                break;
            case 2:
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%c", (arc4random() % 26) + 65]];
                break;
        }
    }
    return str;
}
//获取时间字符串
- (NSString *)gainTimestamp
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd-HH:mm:ss";
    NSString *timeStr = [dateFormatter stringFromDate:[NSDate date]];
    //    NSString *stamp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    return timeStr;
}
//获取sign sign=md5(data+private_key)
- (NSString *)gainSign:(NSDictionary *)dic
{
    NSString *sign = [self getMd5_32Bit_String:[self gainData:dic]];
    return sign;
}
//获取data+private_key (private_key包含在base中)
- (NSString *)gainData:(NSDictionary *)dic
{
    //data = base + dic
    NSMutableDictionary *basePara = [NSMutableDictionary dictionaryWithDictionary:[self baseParameters]];
    _timeStr = [self gainTimestamp];
    [basePara addEntriesFromDictionary:dic];
    
    NSArray *arr = [basePara allKeys];
    arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
        NSComparisonResult result = [obj1 compare:obj2];
        return result == NSOrderedDescending;
    }];
    
    NSString *dataStr = [NSString string];
    for (int i = 0; i < arr.count; i++) {
        dataStr = [dataStr stringByAppendingString:arr[i]];
        dataStr = [dataStr stringByAppendingString:@"="];
        dataStr = [dataStr stringByAppendingString:[NSString stringWithFormat:@"%@",[basePara objectOrNilForKey:arr[i]]]];
        dataStr = [dataStr stringByAppendingString:@"&"];
    }
    dataStr = [dataStr substringToIndex:dataStr.length - 1];
    return dataStr;
}
//md5加密
- (NSString *)getMd5_32Bit_String:(NSString *)srcString
{
    const char *cStr = [srcString UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest );
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    
    return result;
}
@end

后台在接收到数据后首先会做验签操作,验证签名是否正确和签名是否失效。

{
  "err":{
      "code":-100,
      "msg": 登录已过期,请重新登录,
      "eventId":"xxx-xxx-xxx-xxx-xxx"
  }
}
+ (void)postRequestWihtUrl:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))successInfo failure:(TPErrorInfo)errorInfo {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"text/html", @"application/json", @"application/x-www-form-urlencoded"]];
    
    /**
     数据请求
     获取基础上送参数
     [[[TPBaseRequest alloc] init] finalParametersFrom:params]
     */
    [manager POST:url parameters:[[[TPBaseRequest alloc] init] finalParametersFrom:params] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        TPErrorHandle *err = [[TPErrorHandle alloc] initWithDic:[responseObject objectForKey:@"err"]];
        if (err.isError) {
            errorInfo(err);
            return;
        }
        successInfo(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败信息:%@",error);
        NSDictionary *errDic=error.userInfo;
        NSHTTPURLResponse *response=[errDic objectForKey:@"com.alamofire.serialization.response.error.response"];
        NSInteger errCode=response.statusCode;
        MDErrorInfo *err = [[MDErrorInfo alloc] initWithDefault];
        err.code = errCode;
        if (error.code == -1009) {
            err.msg = @"网络超时";
        }
        else if (err.code == 404){
            err.msg = @"网络页面不存在";
        }
   //我发出通知处理错误的方法在TPErrorHandle 文件里
        errorInfo([[TPErrorHandle alloc] initWithMDErrorInfo:err]);
    }];
}

{
  "err":{
      "code":-99,
      "msg": "有新版本,请及时更新",
      "eventId":"返回的更新链接"
  }
}

根视图上添加的更新通知监听就会pop 出更新页面,这样极大地提高了新版本的更新率。

上一篇下一篇

猜你喜欢

热点阅读