티스토리 뷰

Java 플랫폼의 서버와 IOS&Android 간의 RSA암호화 문자열을 주고받아야 하는 상황이 발생되었다.
구글링과 맥부기 카페의 도움으로 아래의 IOS용 RSA암호화클래스를 작성했다. 

인터페이스 RSAEncryptor.h

#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import "SecKeyWrapper.h"

@interface RSAEncryptor : SecKeyWrapper {
    SecKeyRef keyref;
}
+ (RSAEncryptor *)sharedSingleton;
-(NSString*)encrypt:(NSString *)str;

@end

구현클래스 RSAEncryptor.h

#import "RSAEncryptor.h"
#import "SecKeyWrapper.h"
#import "BasicEncodingRules.h"
#import "Base64.h"

//공개키-modulus (바이너리를 BASE64로 인코딩한 문자열)
#define PUBLICKEY_MODULUS @"AMQJe/E1jYwMhyGfrFULikXkiwAMyN2mmb1dYn8F15ELwK6obGIfDiOaVQGqItO+xrWWZHNi9KA39+MmsNc2pSUzLSaNCjaWWNmeKQ4K08CctUVIkTRg4YG6Q/ZDAy5vaZkzNFPSUJLWw7dRLsyQW3H4zJanLKYIetxu3ILkQ471"

//공개키-exponent (바이너리를 BASE64로 인코딩한 문자열)
#define PUBLICKEY_EXPONENT @"AQAB"

@implementation RSAEncryptor

static RSAEncryptor *rsaEncryptor = nil;

+ (RSAEncryptor *)sharedSingleton
{
    @synchronized(self)
    {
        if (rsaEncryptor == NULL)
            rsaEncryptor = [[self alloc] init];
    }
    return(rsaEncryptor);
}
- (id)init {
    if (self = [super init]) {
        
        //공개키 생성
        NSData *pubKeyModData = [Base64 decode:PUBLICKEY_MODULUS];
        NSData *pubKeyExpData = [Base64 decode:PUBLICKEY_EXPONENT];
        
        NSString *peerName = @"thisissometagname";	//태그명
        NSMutableArray *pubKeyArray = [[NSMutableArray alloc] init];
        [pubKeyArray addObject:pubKeyModData];
        [pubKeyArray addObject:pubKeyExpData];
        NSData *pubKeys = [pubKeyArray berData];
        
        keyref = [self addPeerPublicKey:peerName keyBits:pubKeys];
    }
    return self;
}
- (void)dealloc {
    // Should never be called, but just here for clarity really.
    if (false) {	//ignore warning
        [super dealloc];
    }
}

-(NSString*)encrypt:(NSString *)str {
    if (keyref) {
        size_t cipherBufferSize;
        uint8_t *cipherBuffer;                     // 1 암호화 된 텍스트를 저장할 버퍼를 할당합니다.
        const char *dataToEncrypt = [str UTF8String];
        size_t dataLength = strlen(dataToEncrypt);
        cipherBufferSize = SecKeyGetBlockSize(keyref);
        cipherBuffer = malloc(cipherBufferSize);
        //NSLog(@"RSA암호화할 문자열 : %s", dataToEncrypt);
        OSStatus status = SecKeyEncrypt(keyref,
                                        kSecPaddingPKCS1,
                                        (uint8_t*)dataToEncrypt,
                                        (size_t) dataLength,
                                        cipherBuffer,
                                        &cipherBufferSize
                                        );
        
        if (status==0) {
            [Base64 initialize];
            NSString *encoded = [Base64 encode:cipherBuffer length:cipherBufferSize];
            //NSLog(@"RSA암호화(BASE64문자열) : %@", encoded);
            return encoded;
        }
    }
    return @"";
}


@end

사용방법

[[RSAEncryptor sharedSingleton] encrypt:@"암호화할 문자열"];


ps) SecKeyWrapper 클래스를 시뮬레이터에서 작동시키려면 시뮬레이터에서만 빌드되게 해놓은 코드를 돌지않게끔 수정해야한다. 아래코드 참고

#if FALSE
#error This sample is designed to run on a device, not in the simulator. To run this sample, \
choose Project > Set Active SDK > Device and connect a device. Then click Build and Go.


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함