阿里短信iOS端发送API 签名加密处理

阿里云短信发送API 公共参数签名示例有Java端代码,安卓开发方便,但iOS比较苦逼
阿里签名生成文档

需要使用到的加密库:

pod 'LBXDataHandler', '~> 1.0.3' #加密方式

iOS OC实现直接看代码

- (void)sendMsgWithcurLocation:(NSString *)curPositionCode {
    YYAcitveAreaModel *model = [YYAcitveAreaModel getActiveModel];
    if (model.isOpenArea == NO || model.contackPhone.length <= 0) {
        return;
    }
    
    NSString *url = [self creataliSendMsgUrl:curPositionCode activeModel:model];
    __weak typeof(model) weakModel = model;
    [self.network getAppendingString:url withPara:nil cookie:NO netType:NetTypeAliMsg result:^(id info, NSError *error) {
        if (info) {
            NSString *code = [info objectForKey:@"Code"];
            if ([code.uppercaseString isEqualToString:@"OK"]) {
                // 成功
                weakModel.sendMsgTime = [[NSDate date] timeIntervalSince1970];
                [weakModel saveOrUpdateActiveModel];
            }else {
                NSString *msg = [info objectForKey:@"Message"];
                NSLog(@"阿里短信发送失败:%@",msg);
            }
        }else{
            NSLog(@"阿里短信发送失败:%@",error.localizedDescription);
        }
    }];
}

- (NSString *)creataliSendMsgUrl:(NSString *)curPositionCode activeModel:(YYAcitveAreaModel *)model {
    
    NSString *accesskey = @"LTAI5tDsjxeEzpMc****";
    NSString *secret = @"2i8mFIzygdy6qyXuWJ2O****";
    NSString *templateCode = @"SMS_219752717"; // 模板Id
    
    CLLocationCoordinate2D coor = self.currentLocation.coordinate;
    NSString *latStr = [NSString stringWithFormat:@"%.6f",coor.latitude];
    NSString *longStr = [NSString stringWithFormat:@"%.6f",coor.longitude];
    
    NSDictionary *templateParam =  @{@"name":@"【慧心】",@"position":model.thoroughfare,@"direction":@(model.radius),@"lng":longStr,@"lat":latStr};
    NSString *templateParamJson = [self dictionaryToJson:templateParam];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
    formater.locale = [NSLocale autoupdatingCurrentLocale];
    formater.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    NSString *timeS = [formater stringFromDate:[NSDate date]];
    NSLog(@"%@",timeS);
    
    NSString *uuidString = [NSUUID UUID].UUIDString;
    NSDictionary *dict = @{@"AccessKeyId":accesskey,
                           @"SignatureVersion":@"1.0",
                           @"SignatureNonce":uuidString,
                           @"SignatureMethod":@"HMAC-SHA1",
                           @"RegionId":@"cn-hangzhou",
                           @"Action":@"SendSms",
                           @"Format":@"JSON",
                           @"Timestamp":timeS,
                           @"Version":@"2017-05-25",
    };
    NSMutableDictionary *signatureParam = [NSMutableDictionary dictionaryWithDictionary:dict];
    [signatureParam setObject:templateParamJson forKey:@"TemplateParam"];
    [signatureParam setObject:model.contackPhone forKey:@"PhoneNumbers"];
    [signatureParam setObject:templateCode forKey:@"TemplateCode"];
    [signatureParam setObject:@"123" forKey:@"OutId"];
    [signatureParam setObject:@"慧心" forKey:@"SignName"];
    
    if ([signatureParam.allKeys containsObject:@"Signature"]) {
        [signatureParam removeObjectForKey:@"Signature"];
    }
    
    //按字母顺序排序
    NSArray *keys = signatureParam.allKeys;
    keys = [keys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    NSMutableString *argumentStr = [NSMutableString string];
    for (NSString *key in keys) {
        [dictM setObject:[signatureParam objectForKey:key] forKey:key];
        [argumentStr appendFormat:@"&%@=%@",[self specialUrlEncode:key],[self specialUrlEncode:[signatureParam objectForKey:key]]];
    }
    signatureParam = dictM;
    [argumentStr deleteCharactersInRange:NSMakeRange(0, 1)];
    NSMutableString *stringToSign = [NSMutableString string];
    [stringToSign appendFormat:@"GET&"];
    [stringToSign appendString:[self specialUrlEncode:@"/"]];
    [stringToSign appendString:@"&"];
    [stringToSign appendString:[self specialUrlEncode:argumentStr]];
    // cpNO3Oe4DoiEML50AVXAjQDrNxU=
    NSString *sign = [self signWithSecret:[NSString stringWithFormat:@"%@&",secret] stringToSign:stringToSign];
    //NSLog(@"签名:%@",sign);
    
    NSString *lastUrl = [NSString stringWithFormat:@"http://dysmsapi.aliyuncs.com/?Signature=%@&%@", [self specialUrlEncode:sign],argumentStr];
    NSLog(@"lasturl:%@",lastUrl);
    
    return lastUrl;
}

- (NSString *)specialUrlEncode:(NSString *)value {
    NSString *str = [[value encodeURLString] unicodeToUtf8];
    [str stringByReplacingOccurrencesOfString:@"+" withString:@"%20"];
    [str stringByReplacingOccurrencesOfString:@"*" withString:@"%2A"];
    [str stringByReplacingOccurrencesOfString:@"~" withString:@"%7E"];
    return str;
}

- (NSString *)signWithSecret:(NSString *)secret stringToSign:(NSString *)stringToSign {
    NSData *data = [[stringToSign utf8Data] hmacWithKey:[secret utf8Data] algorithm:(LBXHmacAlgSHA1)];
    NSString *sign = [data encodeBase64WithOptions:0];
    return  sign;
}
- (NSString*)dictionaryToJson:(id)dic {
    if (dic) {
        NSError *parseError = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else {
        return nil;
    }
}

结果对比

// 阿里的
 //    GET&%2F&AccessKeyId%3DtestId%26
 //    Action%3DSendSms%26
 //    Format%3DXML%26
 //    OutId%3D123%26
 //    PhoneNumbers%3D15300000001%26
 //    RegionId%3Dcn-hangzhou%26
 //   SignName%3D%25E9%2598%25BF%25E9%2587%258C%25E4%25BA%2591%25E7%259F%25AD%25E4%25BF%25A1%25E6%25B5%258B%25E8%25AF%2595%25E4%25B8%2593%25E7%2594%25A8%26
 //    SignatureMethod%3DHMAC-SHA1%26
 //    SignatureNonce%3D45e25e9b-0a6f-4070-8c85-2956eda1b466%26
 //    SignatureVersion%3D1.0%26
 //    TemplateCode%3DSMS_71390007%26
 //    TemplateParam%3D%257B%2522customer%2522%253A%2522test%2522%257D%26
 //    Timestamp%3D2017-07-12T02%253A42%253A19Z%26
 //    Version%3D2017-05-25
     
 // 自己的
 GET&%2F&AccessKeyId%3DLTAI5tDsjxeEzpMc9WUkWpwz%26
 Action%3DSendSms%26
 Format%3DJSON%26
 OutId%3D123%26
 PhoneNumbers%3D185****5206%26
 RegionId%3Dcn-hangzhou%26
 SignName%3D%25E6%2585%25A7%25E5%25BF%2583%26
 SignatureMethod%3DHMAC-SHA1%26
 SignatureNonce%3D500A7C8F-6D5B-472D-8A23-4FFCD77E3EE8%26
 SignatureVersion%3D1.0%26
 TemplateCode%3DSMS_218547214%26
 TemplateParam%3D%257B%2522curPositionCode%2522%253A%2522%25E5%2588%259B%25E4%25B8%259A%25E4%25BA%258C%25E8%25B7%25AF377-379%25E8%25B7%25AF%2522%252C%2522name%2522%253A%2522%25E3%2580%2590%25E6%2585%25A7%25E5%25BF%2583%25E3%2580%2591%2522%252C%2522position%2522%253A%2522%25E5%2588%259B%25E4%25B8%259A%25E4%25BA%258C%25E8%25B7%25AF377-379%25E8%25B7%25AF%2522%252C%2522direction%2522%253A5%257D%26
 Timestamp%3D2021-07-16T10%253A23%253A16Z%26
 Version%3D2017-05-25
 

 
 // 阿里文档
 http://dysmsapi.aliyuncs.com/?Signature=zJDF%2BLrzhj%2FThnlvIToysFRq6t4%3D&
 AccessKeyId=testId&
 Action=SendSms&
 Format=XML&
 OutId=123&
 PhoneNumbers=15300000001&
 RegionId=cn-hangzhou&
 SignName=%E9%98%BF%E9%87%8C%E4%BA%91%E7%9F%AD%E4%BF%A1%E6%B5%8B%E8%AF%95%E4%B8%93%E7%94%A8&
 SignatureMethod=HMAC-SHA1&
 SignatureNonce=45e25e9b-0a6f-4070-8c85-2956eda1b466&
 SignatureVersion=1.0&
 TemplateCode=SMS_71390007&
 TemplateParam=%7B%22customer%22%3A%22test%22%7D&
 Timestamp=2017-07-12T02%3A42%3A19Z&
 Version=2017-05-25

 // iOS端
 http://dysmsapi.aliyuncs.com/?Signature=hQPvO8bGI7bWZhyChfEuh13ZWUs%3DAccessKeyId=LTAI5tDsjxeEzpMc9WUkWpwz&Action=SendSms&Format=XML&OutId=123&PhoneNumbers=185****5206&RegionId=cn-hangzhou&SignName=%E6%85%A7%E5%BF%83&SignatureMethod=HMAC-SHA1&SignatureNonce=1CF52A07-875C-44A6-945B-D458C2D4E2EC&SignatureVersion=1.0&TemplateCode=SMS_218547214&TemplateParam=%7B%22curPositionCode%22%3A%22%E5%88%9B%E4%B8%9A%E4%BA%8C%E8%B7%AF377-379%E8%B7%AF%22%2C%22name%22%3A%22%E3%80%90%E6%85%A7%E5%BF%83%E3%80%91%22%2C%22position%22%3A%22%E5%88%9B%E4%B8%9A%E4%BA%8C%E8%B7%AF377-379%E8%B7%AF%22%2C%22direction%22%3A5%7D&Timestamp=2021-07-16T10%3A35%3A46Z&Version=2017-05-25
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容