#import <Foundation/Foundation.h> @interface NSString (Password) -(NSString *)MD5; -(NSString *)SHA1; @end
#import "NSString+Password.h" #import <CommonCrypto/CommonDigest.h> @implementation NSString (Password) #pragma mark - 使用MD5加密字符串 -(NSString *)MD5{ const char *cStr = [self UTF8String]; unsigned char digest[CC_MD5_DIGEST_LENGTH]; CC_MD5(cStr, strlen(cStr), digest); NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2]; for (int i = 0 ; i < CC_MD5_DIGEST_LENGTH; i++) { [result appendFormat:@"%02x",digest[i]]; } return result; } #pragma mark 使用SHA1加密字符串 -(NSString *)SHA1{ const char *cStr = [self UTF8String]; NSData *data = [NSData dataWithBytes:cStr length:self.length]; uint8_t digest[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(data.bytes, data.length, digest); NSMutableString *result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { [result appendFormat:@"%02x",digest[i]]; } return result; } @end
#import <UIKit/UIKit.h> @interface MLViewController : UIViewController @end
#import "MLViewController.h" #import "NSString+Password.h" static NSString *token = @"hiwanvwiauh9vwn2983urh92fbib2yvbdiwf208fhwf2rfH&Hfjo8whfb-2mwcc _2ej8H&Q#RH(@ERUH@#NFOMO((@#UDNUB&@#((23ewancOIFhdfbw"; @interface MLViewController () @end @implementation MLViewController - (void)viewDidLoad { [super viewDidLoad]; //http://www.cmd5.com/ 該網站用於破解MD5等編碼的破解 [self test1]; [self test2]; } //直接加密(簡單,易破解) -(void) test1 { NSString *str = @"test"; //md5加密 NSString *secureMD5 = [str MD5]; //sha1加密 NSString *secureSHA1 = [str SHA1]; NSLog(@"MD5-%@",secureMD5); NSLog(@"SHA1-%@",secureSHA1); } //在原有的字符串上加「鹽」,上面定義了一個靜態字符串(至關於私人密鑰),每次加密的時候都拼接上這個字符串,而後再進行加密。很難破解 -(void) test2 { NSString *str = @"test"; NSString *str2 = [NSString stringWithFormat:@"%@%@",str, token]; //md5加密 NSString *secureMD5 = [str2 MD5]; //sha1加密 NSString *secureSHA1 = [str2 SHA1]; NSLog(@"MD5-%@",secureMD5); NSLog(@"SHA1-%@",secureSHA1); }