2012年6月18日 星期一

AzDG可逆加密演算法 For Objective-C

iOS初心者第二彈,
花了近7個工作天的時數才完成...... 
加密中需要的base64是採用 QSUtilities 可以在 https://github.com/mikeho/QSUtilities 取得
MD5 可以參考 http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/
Use ARC

AzDG.h
#import 
@interface AzDG : NSObject
{
   
}

-(id) initWithCipher : (NSString*) input;

-(NSString*) getCipher;
-(NSData*) cipherCrypt:(NSData*) inputData;
-(NSString*) encode:(NSString*) input;
-(NSString*) decode:(NSString*) input;

@end
AzDG.m
#import "AzDG.h"
#import "MD5.h"
#import "QSStrings.h"


@implementation AzDG

NSString* cipher = @"1234567890";

-(id) initWithCipher : (NSString*) input
{
    self = [super init];    
    if (self != nil && input != nil && [input length] > 0) 
    {        
        cipher = input;
    }        
    return self;
}

-(NSString*) getCipher{
    return cipher;
}

-(NSData*) cipherCrypt:(NSData*) inputData
{    
    NSMutableData *outData = [[NSMutableData alloc]init];
    int loopCount = [inputData length];  
    const unsigned char * inputChar = [inputData bytes];    
    const unsigned char *cipherHash = [[[MD5 encode: [self getCipher]] dataUsingEncoding:NSASCIIStringEncoding] bytes];
   
    int i = 0;
    while (i < loopCount) 
    {         
        Byte b = (Byte)( inputChar[i] ^ cipherHash[i%32]);
        [outData appendBytes:&b length:sizeof(char)];  
        i++;
    }   
    return outData;  
}


-(NSString*) encode:(NSString*) input
{  
    NSData *inputData = [input dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *outData = [[NSMutableData alloc]init];    
    int loopCount = [inputData length];  
    const unsigned char *inputChar = [inputData bytes];
    const unsigned char *noiseChar = [[[MD5 encode:[NSString stringWithFormat:@"%@",[NSDate date]]]
                                       dataUsingEncoding:NSASCIIStringEncoding] bytes];
  
    int i = 0;
    while (i < loopCount) 
    {      
        [outData appendBytes:&noiseChar[i%32] length:sizeof(char)];
        Byte b = (Byte)(inputChar[i] ^ noiseChar[i%32]);
        [outData appendBytes:&b length:sizeof(char)];
        i++;
    }
    return [QSStrings encodeBase64WithData:[self cipherCrypt:outData]];
}

-(NSString*) decode:(NSString*) input
{
    NSData* inputData = [self cipherCrypt:[QSStrings decodeBase64WithString:input]];
    NSMutableData *outData = [[NSMutableData alloc] init];
    int loopCount = [inputData length]; 
    const unsigned char * inputChar = [inputData bytes];
    
    int i = 0;
    while (i < loopCount) 
    {
        Byte b = (Byte)( inputChar[i] ^ inputChar[i+1]);
        [outData appendBytes:&b length:sizeof(char)];
        i = i + 2;
    }
    return [[NSString alloc] initWithData:outData encoding:NSUTF8StringEncoding]; 
}

@end

沒有留言: