본문 바로가기

Program/iOS

AES-128/256 Encryption & Decryption

 
CryptoHelper 관련 참고 URL
http://pastie.org/297563.txt
http://stackoverflow.com/questions/1235171/iphone-how-to-encrypt-a-string

php의 mcrypt와 padding을 다루는 부분에서 차이가 있어CryptoHelper.m의 아래부분에 kCCOptionECBMode를 추가했다.

// Create and Initialize the crypto reference.
    ccStatus = CCCryptorCreate(    encryptOrDecrypt,
                               kCCAlgorithmAES128,
                               kCCOptionPKCS7Padding | kCCOptionECBMode,
                               (const void *)[theSymmetricKey bytes],
                               kCCKeySizeAES128,
                               (const void *)iv,
                               &thisEncipher
                               );


#1. App에서의 구현

- (void) sendRequest {
    
    NSMutableURLRequest *request;
    
    // setting up the URL to post to
    NSString *urlString = [NSString stringWithFormat:@"http://rockk.org/mcbugi/savePoint.php"];
    
    // setting up the request object now
    request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    
    // make st
    NSString *param = [[NSString stringWithFormat:@"id=2&point=450&nonce=%d", rand()] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *st = [[CryptoHelper sharedInstance] encryptString:param];
    
    NSLog(@"%@", param);
    NSLog(@"%@", st);
    
    // now lets create the body of the post
    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];   
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"st\"\r\n\r\n%@", st] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    [request setHTTPBody:body];
        
    // now lets make the connection to the web
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", returnString);
    
    return;
    
}

#2. Server에서의 구현
<?php

// encrypted data
// echo "from server : ".$_POST['st'];
// exit;

// base64 decode st
$tmp_st = base64_decode($_POST['st']);

// decrypt st (key is бо123456789abcdefбп)
$st = urldecode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, '123456789abcdef', $tmp_st, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND))));

// decrypted data
//echo "from server : ".$st;
//exit;

?>


-------------------------------------------------------------------------------------
AES 256

Encryption

@implementation NSString (AES256)


- (NSData *)AES256EncryptWithKey:(NSString *)key {

NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];

char keyPtr[kCCKeySizeAES256+1];

bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [data length];

size_t bufferSize = dataLength + kCCBlockSizeAES128;

void *buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;

CCCryptorStatus cryptStatus = 

CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,

keyPtr, kCCKeySizeAES256, NULL, [data bytes], dataLength, buffer, bufferSize, &numBytesEncrypted);


if (cryptStatus == kCCSuccess) {

return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];

}


free(buffer);

return nil;

}

@end


Decryption

@implementation NSData (AES256)


- (NSString *)AES256DecryptWithKey:(NSString *)key {

char keyPtr[kCCKeySizeAES256+1];

bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

size_t bufferSize = dataLength + kCCBlockSizeAES128;

void *buffer = malloc(bufferSize);

size_t numBytesDecrypted = 0;

CCCryptorStatus cryptStatus = 

CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,

  keyPtr, kCCKeySizeAES256, NULL, [self bytes], dataLength,   buffer, bufferSize, &numBytesDecrypted);

if (cryptStatus == kCCSuccess) {

return [[[NSString alloc] initWithData:[NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted] encoding:NSUTF8StringEncoding] autorelease];

}

free(buffer);

return nil;

}



@end


'Program > iOS' 카테고리의 다른 글

UIDeviceOrientation  (5) 2011.05.12
Xcode4 svn login timeout  (0) 2011.05.12
Mac - Parallels 한영전환  (1) 2010.12.24
iPhone Safari  (0) 2010.11.06
Object-C 전역객체 (shard Object)  (1) 2010.11.06