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

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool