iOS2012. 8. 26. 13:02

안녕하세요. 팬텀입니다. 
첨부된 파일은 이번 정모에 발표했던 'App과 Server의 은밀한 대화'에 리뷰했던 코드 예제 입니다.
그날 리뷰했던 코드에 urlencoding / urldecoding 관련된 부분이 추가되었습니다.

첨부된 파일을 xcode에서 실행시키면, 뷰에 버튼이 하나 있습니다. 
이 버튼이 parameter와 security token을 만들고, 서버로 request를 보내고,
서버로부터의 결과를 콘솔에 남기는 일을 합니다. 콘솔에서 다음과 같이 확인할 수 있습니다.

 [Session started at 2010-07-21 00:57:01 +0900.]
 -------------------------------------------
[app]
1) param : id=2&point=450&name=%EB%A7%A5%EB%B6%80%EA%B8%B0&nonce=16807
2) st : PysueoNho2uhis%2B8%2FQjpWuSuYdGYA0m4HM969zadxBZIMNwe%2BJle
 -------------------------------------------
[server]
1) result : id=2&point=450&name=맥부기&nonce=16807

endpoint는 코드에 들어있는 http://rockk.org/mcbugi/test.php 입니다. 2주 정도 열어 놓도록 할께요.
서버쪽 코드는 다음과 같구요. 간단하게 st를 복호화 한 값을 그대로 echo 합니다.
app과 key값을 꼭 맞춰주어야 합니다. 아래 붉게 강조된 부분에요. '123456789abcdef'

 <?php
// base64 decode st
$tmp_st = base64_decode(urldecode($_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))));

// echo decrypted data
echo $st;
exit;
?>


실제로 사용할 땐, $st 값을 &로 파싱하고, key & value로 활용하면 되지 않을까 싶습니다.

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
                               );


혹시나 해서 발표자료도 공유합니다- :D

App과 Server의 은밀한 대화
View more presentations from rockk.




한글 잘림현상- 아래수정 부분 확인해서 사용하삼
- (NSString*)encryptString:(NSString*)string
{
NSRange fullRange;
fullRange.length = [string length];
fullRange.location = 0;

uint8_t buffer[[string length]];

[string getBytes:&buffer maxLength:[string length] usedLength:NULL encoding:NSUTF8StringEncoding options:0 range:fullRange remainingRange:NULL];

// NSData *plainText = [NSData dataWithBytes:buffer length:[string length]];// 한글 잘림
NSData *plainText = [string dataUsingEncoding:NSUTF8StringEncoding];

NSData *encryptedResponse = [self doCipher:plainText key:symmetricKey context:kCCEncrypt padding:&pad];

return [self base64EncodeData:encryptedResponse];
}

Posted by 다오나무
iOS2012. 8. 20. 17:11

copyright www.irontop.com All rights reserved.

This Example show to you that communication with iPhone App, iPhone UIWebView each other 
There is two ways for commucation.
One is the [webView:shouldStartLoadWithRequest:navigationType:]UIWebViewDelegate 
The other is the [stringByEvaluatingJavaScriptFromString:] WebView

You can use "shouldStartLoadWithRequest" to commucate UIWebView 2 APP
You can use "stringByEvaluatingJavaScriptFromString" to commucate APP 2 UIWebView 

유관업체에서 앱과 웹뷰간의 통신 예제를 작성해달라고 해서.
간단히 만들어 보았다.

웹뷰에는 자바스크립트의 머리를 깎아줄 수 있는 api를 제공하기 때문에(eval)
자바스크립트를 잘 이해하고 있다면, 팝업을 포함하여 거의 모든 기능을 훼이크로 구현이 가능하다.

아래는 주요 코드 부분이다.

APP에서 WebView로 값을 보내는 부분

 71 (IBAction)toWeb:(id)sender {
 72     NSString *strScript = [NSString stringWithFormat:
 73                            @"var fromApp = document.getElementById('fromApp');\
 74                            fromApp.value = '%@';"self.txtToWebView.text];
 75     [webView stringByEvaluatingJavaScriptFromString:strScript];
 76 }


input 요소를 id로 찾아서 값을 세팅하는 자바스크립트를 생성한 후에
webView에 밀어 넣고 있다.

WebView로부터 APP로 보내지는 값을 획득하는 부분
 83 (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
 84     
 85     NSString *strUrl = [[request URL] absoluteString];
 86     if ([strUrl hasPrefix:@"toAPP://"]) {
 87         NSString *strRequest = [[strUrl componentsSeparatedByString:@"://"] objectAtIndex:1];
 88         NSArray *arrRequest = [strRequest componentsSeparatedByString:@"?"];
 89         NSString *strCmd = [arrRequest objectAtIndex:0];
 90 
 91         if (YES == [@"toAppCmd" isEqualToString:strCmd]) {
 92             // code to set Your Application communication
 93             self.txtFromWebView.text = [arrRequest objectAtIndex:1];
 94         }
 95         
 96         // toApp protocol do not StartLoad
 97         return NO;
 98     }
 99     
100     // other protocol do StartLoad
101     return YES;
102 }


form GET Action을 사용하였고,
action-url을 "toApp://toAppCmd?toApp=abc" 형식이 되도록 하였다.
즉, 로드할 url을 가로채서 "toAPP" 로 시작하는 경우에는 NO 를 리턴하여 실제로 로드되지 않도록 하고,
url을 파싱하여 toApp 의 값을 획득하도록 하였다.
여기서 strCmd 를 명령으로 사용하는 예제이므로 toAppCmd 를 다른 값으로 바꾸고,
구분하여 처리하는 것으로 처리할 종류(명령)을 구분할 수 있는 구조로 확장도 가능하다.

자세하는 것은 첨부된 예제 파일을 참조하자.~~

Posted by 다오나무
영삼이의 IT정보2012. 5. 29. 15:14

/* 

아래 같은 방식으로 smsURL이라는 주소로 post 형식으로 데이터를 감싸 전송이 가능해진다.

*/

- (void)connectToServer

{

NSString *smsURL = @"http://www.google.co.kr";

NSMutableURLRequest *request = [[[NSMutableURLRequest allocinitautorelease];

NSString *post = [NSString stringWithFormat:@"password=%@&id=%@",@"password",@"id"];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

[request setURL:[NSURL URLWithString:smsURL]];

[request setHTTPMethod:@"POST"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"Mozilla/4.0 (compatible;)" forHTTPHeaderField:@"User-Agent"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData];


[NSURLConnection connectionWithRequest:request delegate:self ];

}


/*

아래 Delegate에서는 HTML이 처리되고 난 후 받는 데이터를 얻을 수 있다.

*/

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

NSString *returnString = [[NSString allocinitWithData:data encoding:NSUTF8StringEncoding];

NSLog(returnString);

}


/* 

아래 Delegate를 이용하면 post를 보낸 후 쿠키를 얻을 수 있다.

*/

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)aResponse

{

NSHTTPCookie *cookie;

int i=0;

for (cookie in [[NSHTTPCookieStorage sharedHTTPCookieStoragecookies])

{

NSLog([cookie description]);

}

}

Posted by 다오나무