手机端向后台发送请求, 有时候会让你传一个签名后的参数 ,除了当前的参数的其他参数正序排列后用"&"符号拼接后的字符串md5字符串, 下面是排序 及md5,sha1 方法,
//排序
NSDictionary * dic = @{@"a":@"123",
@"c":@"12",
@"b":@"123"
};
NSArray*keyArray = [dicallKeys];
NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSMutableArray *valueArray = [NSMutableArray array];
for(NSString*sortStringinsortArray) {
[valueArrayaddObject:[dicobjectForKey:sortString]];
}
NSMutableArray *signArray = [NSMutableArray array];
for(inti =0; i < sortArray.count; i++) {
NSString*keyValueStr = [NSStringstringWithFormat:@"%@=%@",sortArray[i],valueArray[i]];
[signArrayaddObject:keyValueStr];
}
NSString *sign = [signArray componentsJoinedByString:@"&"];
NSString* signMD5 = [selfmd5:sign];
#import <CommonCrypto/CommonDigest.h>
//sha1
-(NSString*)sha1:(NSData*)certData {
unsigned char sha1Buffer[CC_SHA1_DIGEST_LENGTH];
CC_SHA1(certData.bytes, certData.length, sha1Buffer);
NSMutableString *fingerprint = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 3];
for(inti =0; i
[fingerprintappendFormat:@"%02x ",sha1Buffer[i]];
return [fingerprint stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
//md5
- (NSString*) md5 : (NSString*) str {
// 判断传入的字符串是否为空
if(! str)returnnil;
// 转成utf-8字符串
constchar*cStr = str.UTF8String;
// 设置一个接收数组
unsigned char result[CC_MD5_DIGEST_LENGTH];
// 对密码进行加密
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
NSMutableString *md5Str = [NSMutableString string];
// 转成32字节的16进制
for(inti =0; i
[md5StrappendFormat:@"%02x", result[i]];
}
returnmd5Str;
}
网友评论