azdg加密算法

/*
  加密中需要的base64是採用 QSUtilities 可以在 https://github.com/mikeho/QSUtilities 取得
MD5 可以參考 http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/
*/
1
AzDG.h 2 3 #import <Foundation/Foundation.h> 4 @interface AzDG : NSObject 5 { 6 7 } 8 9 -(id) initWithCipher : (NSString*) input; 10 11 -(NSString*) getCipher; 12 -(NSData*) cipherCrypt:(NSData*) inputData; 13 -(NSString*) encode:(NSString*) input; 14 -(NSString*) decode:(NSString*) input; 15 16 @end 17 18 19 20 AzDG.m 21 22 #import "AzDG.h" 23 #import "MD5.h" 24 #import "QSStrings.h" 25 26 27 @implementation AzDG 28 29 NSString* cipher = @"1234567890"; 30 31 -(id) initWithCipher : (NSString*) input 32 { 33 self = [super init]; 34 if (self != nil && input != nil && [input length] > 0) 35 { 36 cipher = input; 37 } 38 return self; 39 } 40 41 -(NSString*) getCipher{ 42 return cipher; 43 } 44 45 -(NSData*) cipherCrypt:(NSData*) inputData 46 { 47 NSMutableData *outData = [[NSMutableData alloc]init]; 48 int loopCount = [inputData length]; 49 const unsigned char * inputChar = [inputData bytes]; 50 const unsigned char *cipherHash = [[[MD5 encode: [self getCipher]] dataUsingEncoding:NSASCIIStringEncoding] bytes]; 51 52 int i = 0; 53 while (i < loopCount) 54 { 55 Byte b = (Byte)( inputChar[i] ^ cipherHash[i%32]); 56 [outData appendBytes:&b length:sizeof(char)]; 57 i++; 58 } 59 return outData; 60 } 61 62 63 -(NSString*) encode:(NSString*) input 64 { 65 NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding]; 66 NSMutableData *outData = [[NSMutableData alloc]init]; 67 int loopCount = [inputData length]; 68 const unsigned char *inputChar = [inputData bytes]; 69 const unsigned char *noiseChar = [[[MD5 encode:[NSString stringWithFormat:@"%@",[NSDate date]]] 70 dataUsingEncoding:NSASCIIStringEncoding] bytes]; 71 72 int i = 0; 73 while (i < loopCount) 74 { 75 [outData appendBytes:&noiseChar[i%32] length:sizeof(char)]; 76 Byte b = (Byte)(inputChar[i] ^ noiseChar[i%32]); 77 [outData appendBytes:&b length:sizeof(char)]; 78 i++; 79 } 80 return [QSStrings encodeBase64WithData:[self cipherCrypt:outData]]; 81 } 82 83 -(NSString*) decode:(NSString*) input 84 { 85 NSData* inputData = [self cipherCrypt:[QSStrings decodeBase64WithString:input]]; 86 NSMutableData *outData = [[NSMutableData alloc] init]; 87 int loopCount = [inputData length]; 88 const unsigned char * inputChar = [inputData bytes]; 89 90 int i = 0; 91 while (i < loopCount) 92 { 93 Byte b = (Byte)( inputChar[i] ^ inputChar[i+1]); 94 [outData appendBytes:&b length:sizeof(char)]; 95 i = i + 2; 96 } 97 return [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding]; 98 } 99 100 @end

posted on 2012-06-19 20:59  甲骨魚  阅读(642)  评论(0编辑  收藏  举报

导航