objective-c實現authCode 解決php與ios通訊加密的問題

來源:互聯網
上載者:User
最近項目中要加密與伺服器的通訊內容,主要是為了防止惡意的抓包利用,本來這樣的加密直接在網上就可以找到的,但是無奈關於OC的幾乎都來自同一個模版,加密出來的字元竄無法被PHP後端解析,並且也沒有有效時間的參數,所以只能對照PHP的加密代碼寫一個OC版的,其中PHP的很多方法,在OC當中遠遠沒有一句話那麼簡單(::>_<::),其中也發現了很多的問題,由於特別急,所以也沒有繼續深入,有時間的話,會繼續最佳化這個加密~

#import #define STRING_SPLICE(a,b)     ([NSString stringWithFormat:@"%@%@",(NSString *)(a),(NSString *)(b)])//字串拼接
+ (NSString *)md5:(NSString *)str {    const char *cStr = [str UTF8String];    unsigned char result[16];    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call        return [NSString stringWithFormat:            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",            result[0], result[1], result[2], result[3],            result[4], result[5], result[6], result[7],            result[8], result[9], result[10], result[11],            result[12], result[13], result[14], result[15]            ];}
// param: 要加密的字串// operation: 傳入@"ENCODE" 為加密,解密沒有寫,所以只要不傳"DECODE"就OK了// expiry: 有效時間,單位是秒,預設時0,就是沒有時效,如果設定後超出有效時間,將無法被解密+ (NSString *)encryption:(NSString *)param operation:(NSString *)operation expiry:(int)expiry{    NSString *key = @"1992326qa";   // 加密的密鑰    NSString *DECODE = @"DECODE";    param = [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    operation = operation ? operation : DECODE;    expiry = expiry ? expiry : 0;    int keyLength = 4;    key = [self md5:key];    NSString *keya = [self md5:[key substringToIndex:16]];    NSString *keyb = [self md5:[key substringFromIndex:16]];    NSString *time = [self microtime];    NSString *keyc = keyLength ? ([operation isEqualToString:DECODE] ? [param substringToIndex:keyLength] : [[self md5:time] substringFromIndex:[self md5:time].length - keyLength]) : @"";    NSString *cryptkey = STRING_SPLICE(keya, [self md5:STRING_SPLICE(keya, keyc)]);    keyLength = cryptkey.length;    param = [NSString stringWithFormat:@"%@%@%@",([NSString stringWithFormat:@"%010d",expiry ? expiry + (int)[[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] : expiry]),[[self md5: STRING_SPLICE(param,keyb)] substringToIndex:16],param];    int paramLength = param.length;    NSString *result = @"";    NSMutableArray *box = [NSMutableArray arrayWithCapacity:UnicodeCount];    for (int i = 0; i <= UnicodeCount; i++) {        [box addObject:@(i)];    }    NSMutableArray *rndkey = [NSMutableArray array];    for (int i = 0; i <= UnicodeCount; i++) {        const char rndkeyItem = [cryptkey characterAtIndex:i % keyLength];        NSString *asciiStr = [NSString stringWithCString:&rndkeyItem encoding:NSASCIIStringEncoding];        int asciiCode = [asciiStr characterAtIndex:0];        [rndkey addObject:@(asciiCode)];    }    for (int i=0,j = 0; i <= UnicodeCount; i++) {        j = (j + [box[i] intValue] + [rndkey[i] intValue]) % (UnicodeCount + 1);        int tmp = [box[i] intValue];        box[i] = box[j];        box[j] = @(tmp);    }    for (int a = 0,j = 0,i = 0; i < paramLength; i ++) {        a = (a + 1) % (UnicodeCount + 1);        j = (j + [box[a] intValue]) % (UnicodeCount + 1);        int tmp = [box[a] intValue];        box[a] = box[j];        box[j] = @(tmp);        int s1 = [self ord:param index:i];        int s2 = [box[([box[a] intValue] + [box[j] intValue]) % (UnicodeCount + 1)] intValue];        int s3 = s1 ^ s2;        NSString *add = [self strChr:s3];        result = STRING_SPLICE(result, add);    }    return [NSString stringWithFormat:@"%@%@",keyc,[[self base64:result] stringByReplacingOccurrencesOfString:@"=" withString:@""]];}
+ (NSString *)microtime // 計算時間串{    NSDate *currentDate = [NSDate dateWithTimeIntervalSinceNow:0];    NSTimeInterval interval = [currentDate timeIntervalSince1970];    NSString *intervalStr = [NSString stringWithFormat:@"%f00",interval];    NSString *pre = [intervalStr substringWithRange:NSMakeRange(intervalStr.length - 8, 8)];    NSString *suf = [intervalStr substringToIndex:intervalStr.length - 9];    NSString *result = [NSString stringWithFormat:@"0.%@ %@",pre,suf];    return result;}
+ (int)ord:(NSString *)str index:(int)index  // 擷取字串某一位的ASCII碼{    int asciiCode = [str characterAtIndex:index];    return asciiCode;}
+ (const char)chr:(int)asciiCode  // 通過ASCII碼擷取字元{    return [[NSString stringWithFormat:@"%C",(unichar)asciiCode] characterAtIndex:0];}
+ (NSString *)strChr:(int)asciiCode // 通過ASCII碼擷取字串{    NSString *data = [NSString stringWithFormat:@"%C",(unichar)asciiCode]; //A    return data;}
+ (NSString *)base64:(NSString *)str // base64編碼{    NSString *base64EncodedString = [[str dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];    return base64EncodedString;}

注意:

  • 只有密碼編譯演算法(因為我不需要解密)
  • 如果需要加密漢字,加密過程中,會出現空白字元,而後端會解析失敗,所以在後台解析iOS端時,要將加密串中的空格替換為+號,才能保證每次解析成功

問題:

  • 因為加密過程中需要轉換ASCII碼,但是Mac和Window的ASCII碼在127位以後就不一樣了,所以我們只能利用前127位ASCII碼

我也是先留著,搞不好什麼時候又用到了~

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.