클로저(Closure)

개발/iOS 2020. 5. 29. 09:49
반응형

클로저(Closure)

  • 클로저(closure)는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다. 클로저는 자바스크립트를 이용한 고난이도의 테크닉을 구사하는데 필수적인 개념으로 활용된다.
  • 예제 코드
function outter(){
    var title = 'coding everybody'; // 외부 함수
    return function(){  // 내부 함수
        alert(title);
    }
}
inner = outter(); // 결과값이 없다.
inner(); // 실행 결과는 alert(title);

 

  • 클로저란 내부함수가 외부함수의 지역변수에 접근 할 수 있고, 외부함수는 외부함수의 지역변수를 사용하는 내부함수가 소멸될 때까지 소멸되지 않는 특성을 의미한다.

 

클로저를 이용해서 private Method 흉내내기

  • 아래는 프라이빗 함수와 변수에 접근하는 퍼블릭 함수를 정의할 수 있는 클로저를 사용하는 방법을 보여주는 코드가 있다. 이렇게 클로저를 사용하는 것을 모듈 패턴이라 한다.
var counter = (function() { // 익명 함수 안에서 만들어진다
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return { // Return 객체
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };
})();

console.log(counter.value()); // logs 0
counter.increment();
counter.increment();

// 클로져 바인딩 시키기
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    (function() {
       var item = helpText[i];
       document.getElementById(item.id).onfocus = function() {
         showHelp(item.help);
       }
    })(); // 익명 클로저를 사용하여 바인딩할 수 있다.
  }
}

setupHelp();
console.log(counter.value()); // logs 2
counter.decrement();
console.log(counter.value()); // logs 1

 

Let 키워드 사용하기

  • let 키워드를 사용하면 블록 범위 변수를 바인딩함으로써 추가적인 클로저를 사용하지 않아도 된다.
function showHelp(help) {
  document.getElementById('help').innerHTML = help;
}

function setupHelp() {
  var helpText = [
      {'id': 'email', 'help': 'Your e-mail address'},
      {'id': 'name', 'help': 'Your full name'},
      {'id': 'age', 'help': 'Your age (you must be over 16)'}
    ];

  for (var i = 0; i < helpText.length; i++) {
    let item = helpText[i];
    document.getElementById(item.id).onfocus = function() {
      showHelp(item.help);
    }
  }
}

setupHelp();

 

Reference

 

 

2020/05/29 - [개발노트] - QR 코드 결제 타입

2020/05/29 - [iOS/Objective-C] - Objective-C Block Syntax

2020/05/29 - [iOS/Objective-C] - Detect permission of camera in iOS

2020/05/29 - [iOS/Swift] - WKWebView에서 history back 처리

2020/05/29 - [iOS/Objective-C] - OpenGL ES View Snapshot

2020/05/29 - [iOS/Objective-C] - Merge two different images in swift

2020/05/29 - [프로그래밍/C, C++] - Base64 encode / decode in C++

2020/05/29 - [OS/Mac OS X] - iPhone SDK location on hard drive

2020/05/29 - [iOS/Objective-C] - NSString <-> CBUUID 변환

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

반응형

'개발 > iOS' 카테고리의 다른 글

WKWebView  (0) 2020.06.01
네비게이션바 투명 처리  (0) 2020.05.29
Objective-C Block Syntax  (0) 2020.05.29
Detect permission of camera in iOS  (0) 2020.05.29
WKWebView에서 history back 처리  (0) 2020.05.29
블로그 이미지

SKY STORY

,
반응형
typedef 로 타입으로 만들기
typedef RETURN_TYPE (^NAME)(PARAMETERS...);

정의 예제(Definition Example):
typedef void (^SomeHandler)(NSError *error);

구현 예제(Implementation Example):
- (void)someWorkWithCompletion:(SomeHandler)handler {
  ...
}
이름이 리턴 타입 뒤에, 즉 중간에 끼어 있기 때문에 많이 헷갈린다. 



바로 Parameter Field 로 정의하기
fieldName:(RETURN_TYPE (^)(PARAMETERS...))parameterName

정의 예제(Definition Example):
- (void)someMethodWithCompletion:(void (^)(NSData *data))completionHandler;

구현 예제(Implementation Example):
[someClass someMethodwithCompletion:^(NSData *data) {
  ...
}];



Property로 정의하기
RETURN_TYPE (^)(PARAMETERS...)

정의 예제(Definition Example):
@property (nonatomic, strong) void (^completionHandler)(NSData *data);

구현 예제(Implementation Example):
someClass.completionHandler = ^(NSData *data) {
  ...
};
프로퍼티로 정의하는 경우에도 이름이 가운데에 끼어서 좀 불안한(?) 모양세다.



변수로 생성하기
RETURN_TYPE (^BLOCK_NAME)(PARAMETER_TYPES...) = ^RETURN_TYPE(PARAMETERS...) { ... };

구현 예제(Implementation Example):
void (^someBlock)(NSData *) = ^void(NSData *data) {
  ...
};

[obj methodUsingBlock:someBlock];
[obj anotherMethodUsingBlock:someBlock];
만약 블럭을 여러 곳에서 공통적으로 쓴다면 변수 등으로 정의해서 참조 할 수 있다.


블럭 외부의 변수를 블럭 내부에서 세팅하기
Swift 클로져의 경우는 별 상관 없는데 Objective-C 블럭의 경우 외부 변수에 뭔가를 쓰는 것은 기본적으로 금지되어 있다. (즉 읽기만 가능하다.) 이를 쓰기 가능하게 풀려면 '__block' 을 쓰려는 변수 선언 앞에 달아주면 된다. 아래 코드는 GCD Dispatch 에서 사용하는 예이다.
__block int result = 0;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  ....
  result = [some workAndResult];
});

 

2020/05/29 - [iOS/Objective-C] - Detect permission of camera in iOS

2020/05/29 - [iOS/Swift] - WKWebView에서 history back 처리

2020/05/29 - [iOS/Objective-C] - OpenGL ES View Snapshot

2020/05/29 - [iOS/Objective-C] - Merge two different images in swift

2020/05/29 - [프로그래밍/C, C++] - Base64 encode / decode in C++

2020/05/29 - [OS/Mac OS X] - iPhone SDK location on hard drive

2020/05/29 - [iOS/Objective-C] - NSString <-> CBUUID 변환

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

 

반응형

'개발 > iOS' 카테고리의 다른 글

네비게이션바 투명 처리  (0) 2020.05.29
클로저(Closure)  (0) 2020.05.29
Detect permission of camera in iOS  (0) 2020.05.29
WKWebView에서 history back 처리  (0) 2020.05.29
OpenGL ES View Snapshot  (0) 2020.05.29
블로그 이미지

SKY STORY

,
반응형
@import AVFoundation;

NSString *mediaType = AVMediaTypeVideo;
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
if(authStatus == AVAuthorizationStatusAuthorized) {
  // do your logic
} else if(authStatus == AVAuthorizationStatusDenied){
  // denied
} else if(authStatus == AVAuthorizationStatusRestricted){
  // restricted, normally won't happen
} else if(authStatus == AVAuthorizationStatusNotDetermined){
  // not determined?!
  [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
    if(granted){
      NSLog(@"Granted access to %@", mediaType);
    } else {
      NSLog(@"Not granted access to %@", mediaType);
    }
  }];
} else {
  // impossible, unknown authorization status
}
반응형

'개발 > iOS' 카테고리의 다른 글

클로저(Closure)  (0) 2020.05.29
Objective-C Block Syntax  (0) 2020.05.29
WKWebView에서 history back 처리  (0) 2020.05.29
OpenGL ES View Snapshot  (0) 2020.05.29
Merge two different images in swift  (0) 2020.05.29
블로그 이미지

SKY STORY

,
반응형

스마트폰 BTC 채굴앱

https://get.cryptobrowser.site/34473645

 

Earn coins while browsing the web

Earn bitcoins while watching videos, chatting, or playing online. It has never been so easy to increase your income! Tell your friends about CryptoTab Browser, invite them to join, and earn more together. Grow your network—get more profit!

get.cryptobrowser.site

 

네이티브에서 직접 처리할 경우 canGoBack, webView.goBack 함수를 직접 호출하면 되지만 웹에서 뒤로가기를 할 경우 네이티브에 다음과 같이 선언하여 처리하도록 한다.

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        guard let url = navigationAction.request.url else {
            decisionHandler(.cancel)
            return
        }
        
        if(navigationAction.navigationType == .backForward) {
            if navigationAction.request.url != nil {
                if webView.canGoBack {
                    print ("Can go back")
                    webView.goBack()
                    //webView.reload()
                    decisionHandler(.cancel)
                    return
                } else {
                    print ( "Can't go back")
                }
            }
        }
        
        // 생략 ~
}

 

스마트폰 BTC 채굴앱

https://get.cryptobrowser.site/34473645

 

Earn coins while browsing the web

Earn bitcoins while watching videos, chatting, or playing online. It has never been so easy to increase your income! Tell your friends about CryptoTab Browser, invite them to join, and earn more together. Grow your network—get more profit!

get.cryptobrowser.site

 

2020/05/29 - [iOS/Objective-C] - OpenGL ES View Snapshot

2020/05/29 - [iOS/Objective-C] - Merge two different images in swift

2020/05/29 - [프로그래밍/C, C++] - Base64 encode / decode in C++

2020/05/29 - [OS/Mac OS X] - iPhone SDK location on hard drive

2020/05/29 - [iOS/Objective-C] - NSString <-> CBUUID 변환

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

2020/05/19 - [AI/Algorithm] - neural network

2020/05/19 - [AI/Algorithm] - minimax full search example

반응형

'개발 > iOS' 카테고리의 다른 글

Objective-C Block Syntax  (0) 2020.05.29
Detect permission of camera in iOS  (0) 2020.05.29
OpenGL ES View Snapshot  (0) 2020.05.29
Merge two different images in swift  (0) 2020.05.29
NSString <-> CBUUID 변환  (0) 2020.05.29
블로그 이미지

SKY STORY

,

OpenGL ES View Snapshot

개발/iOS 2020. 5. 29. 09:24
반응형
// IMPORTANT: Call this method after you draw and before -presentRenderbuffer:.
- (UIImage*)snapshot:(UIView*)eaglview
{
    GLint backingWidth, backingHeight;
 
    // Bind the color renderbuffer used to render the OpenGL ES view
    // If your application only creates a single color renderbuffer which is already bound at this point,
    // this call is redundant, but it is needed if you're dealing with multiple renderbuffers.
    // Note, replace "_colorRenderbuffer" with the actual name of the renderbuffer object defined in your class.
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, _colorRenderbuffer);
 
    // Get the size of the backing CAEAGLLayer
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
 
    NSInteger x = 0, y = 0, width = backingWidth, height = backingHeight;
    NSInteger dataLength = width * height * 4;
    GLubyte *data = (GLubyte*)malloc(dataLength * sizeof(GLubyte));
 
    // Read pixel data from the framebuffer
    glPixelStorei(GL_PACK_ALIGNMENT, 4);
    glReadPixels(x, y, width, height, GL_RGBA, GL_UNSIGNED_BYTE, data);
 
    // Create a CGImage with the pixel data
    // If your OpenGL ES content is opaque, use kCGImageAlphaNoneSkipLast to ignore the alpha channel
    // otherwise, use kCGImageAlphaPremultipliedLast
    CGDataProviderRef ref = CGDataProviderCreateWithData(NULL, data, dataLength, NULL);
    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
    CGImageRef iref = CGImageCreate(width, height, 8, 32, width * 4, colorspace, kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast,
                                    ref, NULL, true, kCGRenderingIntentDefault);
 
    // OpenGL ES measures data in PIXELS
    // Create a graphics context with the target size measured in POINTS
    NSInteger widthInPoints, heightInPoints;
    if (NULL != UIGraphicsBeginImageContextWithOptions) {
        // On iOS 4 and later, use UIGraphicsBeginImageContextWithOptions to take the scale into consideration
        // Set the scale parameter to your OpenGL ES view's contentScaleFactor
        // so that you get a high-resolution snapshot when its value is greater than 1.0
        CGFloat scale = eaglview.contentScaleFactor;
        widthInPoints = width / scale;
        heightInPoints = height / scale;
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(widthInPoints, heightInPoints), NO, scale);
    }
    else {
        // On iOS prior to 4, fall back to use UIGraphicsBeginImageContext
        widthInPoints = width;
        heightInPoints = height;
        UIGraphicsBeginImageContext(CGSizeMake(widthInPoints, heightInPoints));
    }
 
    CGContextRef cgcontext = UIGraphicsGetCurrentContext();
 
    // UIKit coordinate system is upside down to GL/Quartz coordinate system
    // Flip the CGImage by rendering it to the flipped bitmap context
    // The size of the destination area is measured in POINTS
    CGContextSetBlendMode(cgcontext, kCGBlendModeCopy);
    CGContextDrawImage(cgcontext, CGRectMake(0.0, 0.0, widthInPoints, heightInPoints), iref);
 
    // Retrieve the UIImage from the current context
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
 
    UIGraphicsEndImageContext();
 
    // Clean up
    free(data);
    CFRelease(ref);
    CFRelease(colorspace);
    CGImageRelease(iref);
 
    return image;
}

 

2020/05/29 - [iOS/Objective-C] - Merge two different images in swift

2020/05/29 - [프로그래밍/C, C++] - Base64 encode / decode in C++

2020/05/29 - [OS/Mac OS X] - iPhone SDK location on hard drive

2020/05/29 - [iOS/Objective-C] - NSString <-> CBUUID 변환

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

2020/05/19 - [AI/Algorithm] - neural network

2020/05/19 - [AI/Algorithm] - minimax full search example

2020/05/19 - [AI/Algorithm] - minimax, alpha-beta pruning

 

반응형
블로그 이미지

SKY STORY

,
반응형
UIImage *image1 = [UIImage imageNamed:@"image1.png"];
UIImage *image2 = [UIImage imageNamed:@"image2.png"];

CGSize size = CGSizeMake(image1.size.width, image1.size.height + image2.size.height);

UIGraphicsBeginImageContext(size);

[image1 drawInRect:CGRectMake(0,0,size.width, image1.size.height)];
[image2 drawInRect:CGRectMake(0,image1.size.height,size.width, image2.size.height)];

UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

//Add image to view
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, finalImage.size.width, finalImage.size.height)];
imageView.image = finalImage;
[self.view addSubview:imageView];

 

2020/05/29 - [프로그래밍/C, C++] - Base64 encode / decode in C++

2020/05/29 - [OS/Mac OS X] - iPhone SDK location on hard drive

2020/05/29 - [iOS/Objective-C] - NSString <-> CBUUID 변환

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

2020/05/19 - [AI/Algorithm] - neural network

2020/05/19 - [AI/Algorithm] - minimax full search example

2020/05/19 - [AI/Algorithm] - minimax, alpha-beta pruning

2020/05/19 - [iOS/Tips] - Bitbucket Carthage 사용

반응형

'개발 > iOS' 카테고리의 다른 글

WKWebView에서 history back 처리  (0) 2020.05.29
OpenGL ES View Snapshot  (0) 2020.05.29
NSString <-> CBUUID 변환  (0) 2020.05.29
SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제 (1/2)  (0) 2020.05.28
Array <-> Data 변환  (0) 2020.05.26
블로그 이미지

SKY STORY

,
반응형

NSString -> CBUUID

NSString *string = [@"233R194013780790" toUUID];
CBUUID *harexUUID = [CBUUID UUIDWithString:string];
// 결과 :
// 32333352-3139-3430-3133-373830373930

 

CBUUID -> NSString

// 32333352-3139-3430-3133-373830373930
NSString *uuidString = [harexUUID representativeString];
NSString *tid = [harexUUID toString];
// 결과 :
// 233R194013780790

 

관련 함수 :

// String to Hexadecimal String
-(NSString *)toHex {
    char *utf8 = (char *)[self UTF8String];
    NSMutableString *hex = [NSMutableString string];
    while ( *utf8 ) {
        [hex appendFormat:@"%02X" , *utf8++ & 0x00FF];
    }
    return [NSString stringWithFormat:@"%@", hex];
}

// Hexadecimal String to NSData
-(NSData *)hex2Data {
    NSMutableData *stringData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [self length] / 2; i++) {
        byte_chars[0] = [self characterAtIndex:i*2];
        byte_chars[1] = [self characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [stringData appendBytes:&whole_byte length:1];
    }
    return stringData;
}

-(CBUUID *)toCBUUID {
    if (NO == [self isValidUUID]) {
        NSLog(@"포멧 비정상.");
        return nil;
    }
    return [CBUUID UUIDWithString:self];
}

-(BOOL)isValidUUID {
    return (BOOL)[[NSUUID alloc] initWithUUIDString:self];
}

// 문자열을 hex로 변경한뒤 UUID포멧으로 변경
-(NSString *)toUUID {
    NSString *string = self;
    if (string.length < 16) {
        NSString *spaceString = @"";
        for (NSInteger i=0; i<(16 - string.length); ++i) {
            spaceString = [spaceString stringByAppendingString:@" "];
        }
        // 길이가 작을 경우 앞쪽에 공백추가
        //string = [NSString stringWithFormat:@"%@%@", spaceString, self];

        // 길이가 작을 경우 뒤쪽에 공백추가
        string = [NSString stringWithFormat:@"%@%@", self, spaceString];
    }
    
    NSData *data = [string toData];
    NSUInteger bytesToConvert = [data length];
    const unsigned char *uuidBytes = [data bytes];
    NSMutableString *outputString = [NSMutableString stringWithCapacity:16];
    
    for (NSUInteger currentByteIndex = 0; currentByteIndex < bytesToConvert; currentByteIndex++) {
        switch (currentByteIndex) {
            case 3:
            case 5:
            case 7:
            case 9:[outputString appendFormat:@"%02X-", uuidBytes[currentByteIndex]]; break;
            default:[outputString appendFormat:@"%02X", uuidBytes[currentByteIndex]];
        }
        //SLog(@"%@", outputString);
    }

 

 

 

2020/05/29 - [개발노트] - HTTP Content-Type

2020/05/28 - [iOS/Swift] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data 변환

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

2020/05/19 - [AI/Algorithm] - neural network

2020/05/19 - [AI/Algorithm] - minimax full search example

2020/05/19 - [AI/Algorithm] - minimax, alpha-beta pruning

2020/05/19 - [iOS/Tips] - Bitbucket Carthage 사용

2020/05/19 - [iOS/Jailbreak] - Fridump 사용법 (3/3) - 메모리 덤프

2020/05/19 - [iOS/Jailbreak] - Fridump 사용법 (2/3) - Mac OS X 환경 구축

 

반응형

'개발 > iOS' 카테고리의 다른 글

OpenGL ES View Snapshot  (0) 2020.05.29
Merge two different images in swift  (0) 2020.05.29
SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제 (1/2)  (0) 2020.05.28
Array <-> Data 변환  (0) 2020.05.26
UserAgent 변경/추가  (0) 2020.05.25
블로그 이미지

SKY STORY

,
반응형

KISA의 암호알고리즘을 이용한 Swift 프로젝트 셈플 입니다.

실제 프로젝트 사용 시 예제 (2/2)를 참고하세요.

 

SEED 블록암호 알고리즘 

seed.kisa.or.kr/kisa/Board/17/detailView.do

 

KISA 암호이용활성화 - 암호알고리즘 소스코드

한국인터넷진흥원(KISA)에서는 128비트 블록암호 SEED를 쉽게 활용할 수 있도록, ECB, CBC, CTR, CCM, GCM, CMAC 운영모드에 대한 소스코드를 배포하고 있습니다. 언어 : C/C++, Java, ASP, JSP, PHP  다음글 2019-01-3

seed.kisa.or.kr

 

KISA_SEED_CBC.h

다음 함수를 헤더에 선언해 주도록 한다.

extern int encryptSeedCBC( IN BYTE *pbszPlainText, OUT BYTE *pbszCipherText );
extern int decryptSeedCBC( IN BYTE *pbszCipherText, OUT BYTE *pbszPlainText );

 

KISA_SEED_CBC.c

아래 함수를 선언해 준다. 

void main(void) 함수는 제거한다.

// 초기화 벡터 - 사용자가 지정하는 초기화 벡터(16 BYTE)
BYTE pbszIV[16] = {0x026, 0x08d, 0x066, 0x0a7, 0x035, 0x0a8, 0x01a, 0x081, 0x06f, 0x0ba, 0x0d9, 0x0fa, 0x036, 0x016, 0x025, 0x001};

// 사용자가 지정하는 입력 키(16bytes), 암호화 대칭키
BYTE pbszUserKey[16] = {0x088, 0x0e3, 0x04f, 0x08f, 0x008, 0x017, 0x079, 0x0f1, 0x0e9, 0x0f3, 0x094, 0x037, 0x00a, 0x0d4, 0x005, 0x089};


int encryptSeedCBC( IN BYTE *pbszPlainText, OUT BYTE *pbszCipherText )
{
    printf("\n---------------------------------");
    printf("\nplainText : %s\n", (char *)pbszPlainText);
    
    int nPlainTextLen = (int)strlen((char *)pbszPlainText);// 평문의 Byte길이
    printf ("\n---------------------------------");
    printf ("\nSEED CBC Encryption....\n");
    // 암호문의 Byte길이 - 패딩 로직때문에 16바이트 블럭으로 처리함으로 pbszCipherText는 평문보다 16바이트 커야 한다.
    int nCipherTextLen = SEED_CBC_Encrypt( pbszUserKey, pbszIV, pbszPlainText, nPlainTextLen, pbszCipherText );
    return nCipherTextLen;
}

int decryptSeedCBC( IN BYTE *pbszCipherText, OUT BYTE *pbszPlainText )
{
    int nCipherTextLen = (int)strlen((char *)pbszCipherText);// 암호문의 Byte길이
    printf ("\n---------------------------------");
    printf ("\nSEED CBC Decryption....\n");
    // 평문의 Byte길이
    int nPlainTextLen = SEED_CBC_Decrypt( pbszUserKey, pbszIV, pbszCipherText, nCipherTextLen, pbszPlainText );
    return nPlainTextLen;
}

 

Swift에서 사용하기 위해 KISA_SEED_CBC.h, KISA_SEED_CBC.c 파일들을 프로젝트에 추가한다.

SEED.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface SEED : NSObject

+(NSString *)encrypt:(NSString *)plainText;
+(NSString *)decrypt:(NSString *)cipherText;

@end

NS_ASSUME_NONNULL_END

 

SEED.mm

#import "SEED.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "KISA_SEED_CBC.h"


@implementation SEED

+(NSString *)encrypt:(NSString *)plainText {

    BYTE pbszPlainText[2048] = {0,};
    memset(pbszPlainText, 0, [plainText length]);
    const char *byteBuff = [msg UTF8String];
    memcpy(pbszPlainText, (BYTE *)byteBuff, strlen(byteBuff));
    
    // 암호문 출력 버퍼
    BYTE pbszCipherText[2048] = {0,};
    int nCipherTextLen = encryptSeedCBC( pbszPlainText, pbszCipherText );
    
    // base64 encode
    NSData *data = [[NSData alloc] initWithBytes:pbszCipherText length:nCipherTextLen];
    NSString *base64String = [data base64EncodedStringWithOptions:0];
    
    // memory clean
    memset(pbszPlainText, 0, nCipherTextLen);
    memset((void *)[data bytes], 0, [data length]);
    
    // log
    [SEED printHexaLog:pbszCipherText length:nCipherTextLen];

    return base64String;
}

+(NSString *)decrypt:(NSString *)cipherText {

    // base64 decode
    NSData *data = [[NSData alloc] initWithBase64EncodedString:cipherText options:0];

    BYTE pbszCipherText[2048] = {0,};
    memcpy(pbszCipherText, [data bytes], [data length]);
    
    // 사용자 입력 평문
    BYTE pbszPlainText[2048] = {0,};
    int nPlainTextLen = decryptSeedCBC( pbszCipherText, pbszPlainText );
    
    NSString *plainText = [[NSString alloc] initWithBytes:pbszPlainText length:nPlainTextLen encoding:NSUTF8StringEncoding];
    
    // memory clean
    memset(pbszCipherText, 0, nPlainTextLen);
    
    // log
    [SEED printHexaLog:pbszPlainText length:nPlainTextLen];
    
    return plainText;
}

+(void)printHexaLog:(BYTE *)pbBytes length:(NSInteger)length {
    printf ("\nLength (%ld)  : ", (long)length);
    for (int i=0;i<length;i++) {
        printf("%02X ",pbBytes[i]);
    }
}

@end

 

Swift 프로젝트에 추가하고 Bridging Header 생성

#import "SEED.h"

 

사용방법 :

let str = "hello world"
let enc = SEED.encrypt(str)
print("\nenc = \(enc)")
let dec = SEED.decrypt(enc)
print("\ndec = \(dec)")

 

결과 :

---------------------------------
plainText : hello world

---------------------------------
SEED CBC Encryption....

Length (16)  : 53 81 F3 E0 18 41 85 70 29 3F 98 8F 9A A1 84 06 
enc = U4Hz4BhBhXApP5iPmqGEBg==

---------------------------------
SEED CBC Decryption....

Length (11)  : 68 65 6C 6C 6F 20 77 6F 72 6C 64 
dec = hello world

 

2020/07/11 - [분류 전체보기] - SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제2

2020/05/28 - [개발노트] - HMAC SHA256

2020/05/26 - [iOS/Swift] - Array <-> Data

2020/05/25 - [분류 전체보기] - UserAgent 추가

2020/05/25 - [iOS/Swift] - RSA 암호화 / 복호화

2020/05/25 - [iOS/Swift] - Base64 인코딩/디코딩

2020/05/19 - [AI/Algorithm] - Generic algorithm

2020/05/19 - [AI/Algorithm] - neural network

2020/05/19 - [AI/Algorithm] - minimax full search example

2020/05/19 - [AI/Algorithm] - minimax, alpha-beta pruning

2020/05/19 - [iOS/Tips] - Bitbucket Carthage 사용

2020/05/19 - [iOS/Jailbreak] - Fridump 사용법 (3/3) - 메모리 덤프

2020/05/19 - [iOS/Jailbreak] - Fridump 사용법 (2/3) - Mac OS X 환경 구축

2020/05/19 - [iOS/Jailbreak] - Fridump 사용법 (1/3) - iOS디바이스 환경 구축

2020/05/19 - [iOS/Jailbreak] - Fridump, Tcpdump, OpenSSL Quick Guide

2020/05/19 - [OS/Mac OS X] - gdb 사용

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

Merge two different images in swift  (0) 2020.05.29
NSString <-> CBUUID 변환  (0) 2020.05.29
Array <-> Data 변환  (0) 2020.05.26
UserAgent 변경/추가  (0) 2020.05.25
RSA 암호화 / 복호화  (0) 2020.05.25
블로그 이미지

SKY STORY

,