Table of Contents
注意:
问题:
Home Backend Development PHP Tutorial objective-c实现authCode 解决php与ios通信加密的问题

objective-c实现authCode 解决php与ios通信加密的问题

Jun 20, 2016 pm 12:25 PM

最近项目中要加密与服务器的通讯内容,主要是为了防止恶意的抓包利用,本来这样的加密直接在网上就可以找到的,但是无奈关于OC的几乎都来自同一个模版,加密出来的字符窜无法被PHP后端解析,并且也没有有效时间的参数,所以只能对照PHP的加密代码写一个OC版的,其中PHP的很多方法,在OC当中远远没有一句话那么简单(::>_<::>


#import <CommonCrypto/CommonDigest.h>#define STRING_SPLICE(a,b)     ([NSString stringWithFormat:@"%@%@",(NSString *)(a),(NSString *)(b)])//字符串拼接
Copy after login
+ (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]            ];}
Copy after login
// 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:@""]];}
Copy after login
+ (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;}
Copy after login
+ (int)ord:(NSString *)str index:(int)index  // 获取字符串某一位的ASCII码{    int asciiCode = [str characterAtIndex:index];    return asciiCode;}
Copy after login
+ (const char)chr:(int)asciiCode  // 通过ASCII码获取字符{    return [[NSString stringWithFormat:@"%C",(unichar)asciiCode] characterAtIndex:0];}
Copy after login
+ (NSString *)strChr:(int)asciiCode // 通过ASCII码获取字符串{    NSString *data = [NSString stringWithFormat:@"%C",(unichar)asciiCode]; //A    return data;}
Copy after login
+ (NSString *)base64:(NSString *)str // base64编码{    NSString *base64EncodedString = [[str dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:0];    return base64EncodedString;}
Copy after login

注意:

  • 只有加密算法(因为我不需要解密)
  • 如果需要加密汉字,加密过程中,会出现空格字符,而后端会解析失败,所以在后台解析iOS端时,要将加密串中的空格替换为+号,才能保证每次解析成功

问题:

  • 因为加密过程中需要转换ASCII码,但是Mac和Window的ASCII码在127位以后就不一样了,所以我们只能利用前127位ASCII码

我也是先留着,搞不好什么时候又用到了~

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles