iOS接口安全认证

签名和加密流程:

  • 1.将请求参数按照a-z排序后,用key=value&key=value拼接,得到待签名字符串;
  • 2.使用自己的私钥,将待签名字符串进行RSA签名,得到签名参数sign;
  • 3.将所有参数转化为json字符串,得到所有参数json字符串明文info;
  • 4.随机生成16位的AES密钥key,用AES加密明文info,得到密文data参数;
  • 将AES密钥key,使用别人的公钥RSA加密,得到密文dataKey参数;

示例:

  • 1.原始请求:www.baidu.com?bbb=222&aaa=111;
  • 2.参数排序后:aaa=111&bbb=222
  • 3.RSA签名得到sign=OCr1gGGlPi9jDOUhTmIRdgQuWgHPZcokhuIDs
  • 4.参数json字符串:{"sign":"OCr1gGGlPi9jDOUhTmIRdgQuWgHPZcokhuIDs","aaa":111,"bbb":"222"}
  • 5.data=C8BkH63OOEVy
  • 6.dataKey=IF4z2fxeGLOgtd

ObjC实现

1.参数排序

为NSDictionary添加一个进行排序的分类如下:

//  NSDictionary+SortedString.h
#import 
@interface NSDictionary(SortedString)
/**
*  排序时默认不忽略大小写
*  @param type 排序方式:升序或者降序
*/
- (NSString *)sortedStringByComparisontype: (NSComparisonResult)type;
@end

//  NSDictionary+SortedString.m
#import "NSDictionary+SortedString.h"
@implementation NSDictionary(SortedString)
- (NSString *)sortedStringByComparisontype: (NSComparisonResult)type
{
    NSArray *keyArray = self.allKeys;
    NSArray *sortedKeyArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
    NSAssert([obj1 isKindOfClass:[NSString class]], @"必须使用NSString类型的参数名");
    NSAssert([obj2 isKindOfClass:[NSString class]], @"必须使用NSString类型的参数名");
    if (type == NSOrderedAscending) {
        return [obj1 compare:obj2]; // options:NSCaseInsensitiveSearch
    }else{
        return [obj2 compare:obj1];
    }
}];
//    NSLog(@"array === %@",sortedKeyArray);

    NSMutableString *sortedString = [NSMutableString string];
    for (int i = 0; i < sortedKeyArray.count; i++) {
        NSString *key = sortedKeyArray[i];
        NSString *temp = [NSString stringWithFormat:@"%@=%@&",key,self[key]];
        [sortedString appendString:temp];
}
    [sortedString deleteCharactersInRange:NSMakeRange(sortedString.length - 1, 1)];
    return sortedString;
}
@end

示例参数:

self.param = [NSMutableDictionary dictionaryWithDictionary:@{@"userName":@"[email protected]",@"nickName":@"Jack",@"exp":@"99999"}];

排序后生成的字符串为:[email protected]

2.RSA签名

为便于测试,提供一个在线生成RSA密钥对的链接:在线生成RSA密钥对.

签名使用的第三方库链接:iOSRSAHandler.

我测试所用的密钥如下:

//客户端私钥
NSString *const private_key_string = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAM7TTLDADuD8wJNPEi1vrq4Xu/hO+DPHjeRtSGANaD0RH/MxhL6I+G18c3ie8adqe7vbiDqXWF+bTGvaS5f7cKSxatUklI8/Ap8ul++6WYUTfiFjzrUWnHOplPnTEpwf5uppWdo++eOAMxR4mvYwJsAMZtOX7ZmhW+zoqI7r9Ax1AgMBAAECgYBqbMoqrTk6xnRlmKt22+AbzzS3KhOHuWinISC75Eo+GiDBqDpxPNPwqrhUWh1pE18GJInt9FDSKXxihxqc4xJrj6tw+nHKo/8Ih0uKoonmC410y5/XXvtjkhTtC8f2x+let5QN23G0onYi4ADc45UaP/gr/Ja+TUMZGBc7s7aU5QJBAO+O7C+kv3PHUKrQljhYHsihmMA6Ft61s1nREqP1WijaxoJZ1o0v96B3NK7HIGFatkJLdqBRSaCblkRpQP1s3CsCQQDdBUEw2zdJf+HUBn6HoGTghPFzbKKKBJDDkt7CjTeFORNiWDTUNAgJSFcbUlYz9UxJ0arksAkR9xtOj/C6CEnfAkB5sGVj8lFas9XTX2/foUvJ6OSaSSfS7AP2TREl/n1VIYUTNCWbxNEKT2OQoRBew+CvnnvdBk3baw2TJNBhq8nPAkBixARbtrpAB/t8aeKE7PHnOsFC2RrRHjUqkCknOz/CMr0sx0nkQdQNgdwbA3IuCcGrgxwg0WFcO9ZiBwSFvUp1AkBtJZ5SHSCdVj6jCHRQ/MInwVs1XPB2XSPZFki1WvsfutCYhSgysCL12gMsXM44zL8pWJ1xPN8zyZ+9o/wVzSKZ";

//客户端公钥
NSString *const public_key_string = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO00ywwA7g/MCTTxItb66uF7v4Tvgzx43kbUhgDWg9ER/zMYS+iPhtfHN4nvGnanu724g6l1hfm0xr2kuX+3CksWrVJJSPPwKfLpfvulmFE34hY861FpxzqZT50xKcH+bqaVnaPvnjgDMUeJr2MCbADGbTl+2ZoVvs6KiO6/QMdQIDAQAB";

//服务器公钥
NSString *const server_public_key_string = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0WcydkWlrgcRhsBq8Li+ZohY3tZnE6JKuI88YWYwadNL0NWNZ4oDzZmm7kAg+3ZYkz8dx6uUU6elIWJw2C6Bp2pHYiRFOwCUtvuCGiW0pJDEsLcpNymvJw2vuA0FKJXcc4W9oMLsuzv8wh05N12Nljy+kDrABpUi6q9Otg/y+DwIDAQAB";

然后使用HBRSAHandler签名:

HBRSAHandler* handler = [HBRSAHandler new];
[handler importKeyWithType:KeyTypePrivate andkeyString:private_key_string];
[handler importKeyWithType:KeyTypePublic andkeyString:public_key_string];
NSString *sign = [handler signString:signString];
//将sign添加到参数列表中
[self.param setObject:sign forKey:@"sign"];

这一步中RSA签名使用的签名算法是SHA1,具体可参见相关工具类里的说明.
我得到的sign=bBK5EXqxyFmxTf5c6uN/g+btpFmtotYd1e+yqSxzvpHUV+ImZLth493WQzDlkeBvX7ejXGed36APs1YEURM9HIdE3PsqQKzvT+0PgdjN+PMch3EmBUwVFN+ce/B7HkUpEZz5HNH2FZZP5Rm/fP2Hru/412IiBuz5r09O258G8gk=

此时,参数列表为:

{
exp = 99999;
nickName = Jack;
sign = "bBK5EXqxyFmxTf5c6uN/g+btpFmtotYd1e+yqSxzvpHUV+ImZLth493WQzDlkeBvX7ejXGed36APs1YEURM9HIdE3PsqQKzvT+0PgdjN+PMch3EmBUwVFN+ce/B7HkUpEZz5HNH2FZZP5Rm/fP2Hru/412IiBuz5r09O258G8gk=";
userName = "[email protected]";
}

3.将所有参数转换为JsonString

    NSData *jsondata = [NSJSONSerialization dataWithJSONObject:self.param options:0 error:nil];
    NSString *jsonString = [[NSString alloc]initWithData:jsondata encoding:NSUTF8StringEncoding];

这一步我得到的jsonString是{"exp":"99999","sign":"bBK5EXqxyFmxTf5c6uN/g+btpFmtotYd1e+yqSxzvpHUV+ImZLth493WQzDlkeBvX7ejXGed36APs1YEURM9HIdE3PsqQKzvT+0PgdjN+PMch3EmBUwVFN+ce/B7HkUpEZz5HNH2FZZP5Rm/fP2Hru/412IiBuz5r09O258G8gk=","nickName":"Jack","userName":"[email protected]"}

4.生成16位随机串

为NSString类添加一个生成随机字符串的分类如下:

//  NSString+RandomString.h
#import 
@interface NSString(RandomString)
/**
 *  @param length 要生成的随机字符串的长度
 */
+ (NSString *)randomStringWithLength:(NSInteger)length;
@end

//  NSString+RandomString.m
#import "NSString+RandomString.h"
@implementation NSString(RandomString)
+ (NSString *)randomStringWithLength:(NSInteger)length
{
    char data[length];

    for (int x=0;x

调用获取随机16位字符串作为AES加密key:

NSString *randomKey = [NSString randomStringWithLength:16];
//为了便于调试,这里写死
randomKey = @"TEWLMGQWYXPQNAST";

5.AES加密参数字符串

这里提供一个AES在线加密解密网站

加解密使用的是我一个同事提供的工具类:GBEncodeTool.

加密使用的是AES128位ECB模式加密,代码如下:

    NSString *data = [GBEncodeTool AES128Encrypt:jsonString WithKey:randomKey];

这里我得到的data是t4eBJnDCJjzabOteDXfDQzPZDKxM2ugI7Yf0vIzFZ1So7xwxuQ78vXg998fU0aFDrFEmAdRqHYJbM22gSTyKYCTYy8fN2mApyFTMH74JIiUonbqAyWueuaIlwL2TOuZS8Ps/tpq+8KgGUT9urhUOc6/iu/97dSJlbgHakb5fV4KN0yGP+jb0UXAGvrC7VMs6WaDnAiQ9UTB6jOTZh0E08o74RrSnSZjbjqhW92UP+c3BRfJNg87Q2aTB5vFrYS+JtPxNDRJ4IXsU5MiSpjDNxl1lC0F5TuLBl2S/tvO2R8kqM8whu8LUQMdWOTXpJVO6FvV5O3LSqysJ8gp62KEY4g==

6.RSA加密AES的key

    NSString *dataKey = [GBEncodeTool rsaEncryptString:randomKey publicKey:server_public_key_string];

这里我得到的dataKey是K5FIL3+j5u8vB8M8Kiz+SKB++tezzg38Z647jrCYYoC8CoGVqk9z6QRbsao+uoCezgFu8dgSaqw8+mW6OXflp+7IhG5Rp1Dq2uPzuWshNmrHA38T0eqXOjPU+qblKi5+pH8LLI+q7TjizW4d65EMV10oMWBGwVc3iPn1kFLcK38=

7.最终传给服务器的参数

{
data = "t4eBJnDCJjzabOteDXfDQzPZDKxM2ugI7Yf0vIzFZ1So7xwxuQ78vXg998fU0aFDrFEmAdRqHYJbM22gSTyKYCTYy8fN2mApyFTMH74JIiUonbqAyWueuaIlwL2TOuZS8Ps/tpq+8KgGUT9urhUOc6/iu/97dSJlbgHakb5fV4KN0yGP+jb0UXAGvrC7VMs6WaDnAiQ9UTB6jOTZh0E08o74RrSnSZjbjqhW92UP+c3BRfJNg87Q2aTB5vFrYS+JtPxNDRJ4IXsU5MiSpjDNxl1lC0F5TuLBl2S/tvO2R8kqM8whu8LUQMdWOTXpJVO6FvV5O3LSqysJ8gp62KEY4g==";

dataKey = "K5FIL3+j5u8vB8M8Kiz+SKB++tezzg38Z647jrCYYoC8CoGVqk9z6QRbsao+uoCezgFu8dgSaqw8+mW6OXflp+7IhG5Rp1Dq2uPzuWshNmrHA38T0eqXOjPU+qblKi5+pH8LLI+q7TjizW4d65EMV10oMWBGwVc3iPn1kFLcK38=";
}

8.解密服务器的返回信息

使用客户端RSA私钥解密即可.

9.完整代码下载

http://pan.baidu.com/s/1dEuuVbb

你可能感兴趣的:(iOS接口安全认证)