반응형

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

,

HTTP Content-Type

개발/Note 2020. 5. 29. 08:53
반응형

HTTP는 하이퍼텍스트 통신 프로토콜으로 서버와 클라이언트가 서로 통신하기 위하여 요청과 응답을 받는다.

이때 클라이언트가 서버에게 요청할 때 보내는 데이터 유형과 어떻게 보내야 올바른지 알아보자.

REST 클라이언트 앱인 Postman은 다음과 같은 Content-Type을 제공한다.

일반적인 HTML 폼으로 전송할 때는 x-www-form-urlencoded 또는 multipart/form-data로 전송된다고 알고 있다.

혹시 모르고 있었더라도 걱정하지 말아라. 이제 알았으면 된거다.

중요한 것은 왜 요청 바디가 raw일 때 text/plain, application/json, application/xml등을 선택할 수 있는지를 아는 것이다.

Content-Type 헤더

우리가 중점적으로 알아보아야 할 것은 multipart/form-data, x-www-form-urlencoded, application/json이다.

application/json

대부분의 API에서 활용하는 Content-Type 헤더로써 application/json으로 페이로드와 함께 HTTP 요청을 하게 되면 서버가 JSON 타입으로 변환해서 사용한다.

const data = {
    key1: 'foo',
    key2: 'bar'
}

axios({
    method: 'post',
    url: 'https://localhost:8080',
    headers: {
        'Content-Type': 'application/json'
    },
    data: data
}).then((res) => {
    // handle success
}).catch((err) => {
    // handle error
}).then(() => {
    // always
})

::: tip Spring MVC
스프링 컨트롤러에서 @RequestMapping과 함께 @RequestBody로 요청 페이로드를 Jackson ObjectMapper를 통해 JSON으로 받을 수 있다.
:::

x-www-form-urlencoded

위에서 일반적으로 서버로 요청할 때는 x-www-form-urlencoded를 Content-Type 헤더로 명시하여 전송한다고 말했다.

그러면 x-www-form-urlencoded를 Content-Type으로 사용할 경우 요청 페이로드는 어떻게 구성되는지 살펴보자.

다음은 모질라 웹 레퍼런스 문서에서 제공하는 예시이다.

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom

say=Hi&to=Mom가 위 요청에 대한 페이로드 부분이다.

이 페이로드는 키와 값을 =와 함께 표현하고 &의 묶음으로 표현하는게 x-www-form-urlencoded의 데이터 구조이다.

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

const data = {
    key1: 'foo',
    key2: 'bar'
}

axios({
    method: 'post',
    url: 'https://localhost:8080',
    data: data
}).then((res) => {
    // handle success
}).catch((err) => {
    // handle error
}).then(() => {
    // always
})

스프링 MVC에서의 모델 바인딩

사실 이 글을 쓰는 이유는 초보 개발자 입장에서 스프링 MVC에서 HTTP 요청 데이터에 대하여 어떻게 모델로 바인딩을 하는지 알려주기 위해서이다.

스프링 공식 레퍼런스 : Setting and Getting Basic and Nested Properties에서는 프로퍼티를 가져오거나 설정하는 것을 getPropertyValue와 getPropertyValues 그리고 setPropertyValue와 setPropertyValues 메소드로 수행한다고 설명한다.

그리고 자바빈 스펙에 따라 오브젝트의 프로퍼티로 나타내는 규칙도 같이 알려주고 있다.

프로퍼티 예시

  • name
    Indicates the property name that corresponds to the getName() or isName() and setName(…) methods.
  • account.name
    Indicates the nested property name of the property account that corresponds to (for example) the getAccount().setName() or getAccount().getName() methods.
  • account[2]
    Indicates the third element of the indexed property account. Indexed properties can be of type array, list, or other naturally ordered collection.
  • account[COMPANYNAME]
    Indicates the value of the map entry indexed by the COMPANYNAME key of the account Map property.

간단하게 살펴보면 account 클래스의 name 프로퍼티를 바인딩할 경우에는 account.name이라고 표현되어야하고 account[2]라고 표현되면 3번째 인덱스 프로퍼티로 나타내며 account[COMPANYNAME]이면 COMPANYNAME을 키로 가지는 Map 프로퍼티인 것이다.

@ModelAttribute

 @ModelAttribute 어노테이션은 컨트롤러에서 리퀘스트 파라미터를 쉽게 빈 오브젝트로 바인딩하기 위해 사용한다.

그런데 다음과 같이 빈 오브젝트에 맵 프로퍼티가 존재할 경우 @ModelAttribute로 데이터 바인딩을 시도할 때 주의해야한다. 앞서 x-www-form-urlencoded의 데이터 구조를 살펴본 것은 바로 이 때문이다.

만약에 빈 오브젝트에 메타데이터로 맵 오브젝트를 담고 싶다고 가정할 때 서버로 맵 오브젝트를 보내어야하는 요구사항이 생긴다.

public class Person {
    private String name;
    private Map metadata;
}

그런데 위 자바 빈 스펙 규칙에 따르면 맵 프로퍼티는 metadata[address][location]와 같이 표현되어야 한다.

그런데 서버로 요청되는 페이로드가 metadata[address][location]=value가 되어버리면 metadata 프로퍼티의 address가 배열의 인덱스인지 맵의 인덱스 키인지 구별할 수 없다

결국 관련 포스트처럼 다음과 같은 오류가 발생할 것이다.

Property referenced in indexed property path 'metadata[address][location]' is neither an array nor a List nor a Map

그러면 요청 페이로드가 .형식으로 데이터를 변환되어 metadata.address.location=value로 전송된다면 올바르게 바인딩 할 수 있을까?

답은 아니다!

바인딩이 되지 않는다.

맵 프로퍼티로 바인딩하기 위해서는 person.metadata[address]이어야만 하기 때문이다.

복잡한 페이로드라면 application/json을 사용하자.

따라서, 복잡한 형태로 데이터가 구성되어야 한다면x-www-form-urlencoded가 아니라 application/json으로 명시하여 서버가 처리할 수 있도록 해야하는게 좋다.

그리고 서버 API도 복잡한 형태의 오브젝트를 페이로드로 받도록 요구된다면 애초에 application/json만 요청할 수 있도록 하자.

{"metadata":{"address":{"location":"value"}}}

물론 스프링이 BeanWrapper 또는 DataBinder를 구현하는 것도 하나의 방법이긴 하다.

하지만, 모델 바인딩을 위한 코드를 API와 오브젝트별로 작성해야 하기에 배보다 배꼽이 더 커질수가 있다.

그리고 @Valid와 @Validated를 이용한 벨리데이션을 쉽게 적용할 수 없고 Validator도 추가로 직접 호출해서 오브젝트를 검증해야 한다.

참조

출처 : kdevkr.github.io/archives/2018/understanding-http-content-types/

 

반응형

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

QR 코드 결제 타입  (0) 2020.05.29
Base64 encode / decode in C++  (0) 2020.05.29
HMAC SHA256  (0) 2020.05.28
UUID의 구성 요소  (0) 2020.05.19
Storyboard References (스토리보드 분리)  (0) 2020.05.18
블로그 이미지

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

,

HMAC SHA256

개발/Note 2020. 5. 28. 15:45
반응형

Examples of creating base64 hashes using HMAC SHA256 in different languages

21 Oct 2012

I recently went through the processing of creating SDKs for an in house API. The API required signing every REST request with HMAC SHA256 signatures. Those signatures then needed to be converted to base64. Amazon S3 uses base64 strings for their hashes. There are some good reasons to use base64 encoding. See the stackOverflow question What is the use of base 64 encoding?

Below are some simplified HMAC SHA 256 solutions. They should all output qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc= given the values of secret and Message. Take notice of the capital M. The hashed message is case sensitive.

Jump to an implementation:

Javascript HMAC SHA256

Run the code online with this jsfiddle. Dependent upon an open source js library called http://code.google.com/p/crypto-js/.

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac-sha256.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/enc-base64.min.js"></script> <script> var hash = CryptoJS.HmacSHA256("Message", "secret"); var hashInBase64 = CryptoJS.enc.Base64.stringify(hash); document.write(hashInBase64); </script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/hmac-sha256.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/enc-base64.min.js"></script>

<script>
  var hash = CryptoJS.HmacSHA256("Message", "secret");
  var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
  document.write(hashInBase64);
</script>

PHP HMAC SHA256

PHP has built in methods for hash_hmac (PHP 5) and base64_encode (PHP 4, PHP 5) resulting in no outside dependencies. Say what you want about PHP but they have the cleanest code for this example.

$s = hash_hmac('sha256', 'Message', 'secret', true); echo base64_encode($s);

$s = hash_hmac('sha256', 'Message', 'secret', true);
echo base64_encode($s);

Java HMAC SHA256

Dependent on Apache Commons Codec to encode in base64.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ApiSecurityExample {
  public static void main(String[] args) {
    try {
     String secret = "secret";
     String message = "Message";

     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
     System.out.println(hash);
    }
    catch (Exception e){
     System.out.println("Error");
    }
   }
}

Groovy HMAC SHA256

It is mostly java code but there are some slight differences. Adapted from Dev Takeout - Groovy HMAC/SHA256 representation.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;

def hmac_sha256(String secretKey, String data) {
 try {
    Mac mac = Mac.getInstance("HmacSHA256")
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256")
    mac.init(secretKeySpec)
    byte[] digest = mac.doFinal(data.getBytes())
    return digest
   } catch (InvalidKeyException e) {
    throw new RuntimeException("Invalid key exception while converting to HMac SHA256")
  }
}

def hash = hmac_sha256("secret", "Message")
encodedData = hash.encodeBase64().toString()
log.info(encodedData)

C# HMAC SHA256

using System.Security.Cryptography;

namespace Test
{
  public class MyHmac
  {
    private string CreateToken(string message, string secret)
    {
      secret = secret ?? "";
      var encoding = new System.Text.ASCIIEncoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
      }
    }
  }
}

Objective C and Cocoa HMAC SHA256

Most of the code required was for converting to bae64 and working the NSString and NSData data types.

#import "AppDelegate.h"
#import <CommonCrypto/CommonHMAC.h>

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
 NSString* key = @"secret";
 NSString* data = @"Message";

 const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
 const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
 unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
 CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
 NSData *hash = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];

 NSLog(@"%@", hash);

 NSString* s = [AppDelegate base64forData:hash];
 NSLog(s);
}

+ (NSString*)base64forData:(NSData*)theData {
 const uint8_t* input = (const uint8_t*)[theData bytes];
 NSInteger length = [theData length];

 static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

 NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
 uint8_t* output = (uint8_t*)data.mutableBytes;

 NSInteger i;
 for (i=0; i < length; i += 3) {
 NSInteger value = 0;
 NSInteger j;
 for (j = i; j < (i + 3); j++) {
 value <<= 8;

 if (j < length) {  value |= (0xFF & input[j]);  }  }  NSInteger theIndex = (i / 3) * 4;  output[theIndex + 0] = table[(value >> 18) & 0x3F];
 output[theIndex + 1] = table[(value >> 12) & 0x3F];
 output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
 output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
 }

 return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; }

@end

Go programming language - Golang HMAC SHA256

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
)

func ComputeHmac256(message string, secret string) string {
    key := []byte(secret)
    h := hmac.New(sha256.New, key)
    h.Write([]byte(message))
    return base64.StdEncoding.EncodeToString(h.Sum(nil))
}

func main() {
    fmt.Println(ComputeHmac256("Message", "secret"))
}

Ruby HMAC SHA256

Requires openssl and base64.

require 'openssl'
require "base64"

hash  = OpenSSL::HMAC.digest('sha256', "secret", "Message")
puts Base64.encode64(hash)

Python (2.7) HMAC SHA256

import hashlib
import hmac
import base64

message = bytes("Message").encode('utf-8')
secret = bytes("secret").encode('utf-8')

signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
print(signature)

Tested with Python 2.7.6. Also, be sure not to name your python demo script the same as one of the imported libraries.

Python (3.7) HMAC SHA256

import hashlib
import hmac
import base64

message = bytes('Message', 'utf-8')
secret = bytes('secret', 'utf-8')

signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
print(signature)

Tested with Python 3.7.0. Also, be sure not to name your python demo script the same as one of the imported libraries. Thanks to @biswapanda.

Perl HMAC SHA256

See Digest::SHA documentation. By convention, the Digest modules do not pad their Base64 output. To fix this you can test the length of the hash and append equal signs "=" until it is the length is a multiple of 4. We will use a modulus function below.

use Digest::SHA qw(hmac_sha256_base64);
$digest = hmac_sha256_base64("Message", "secret");

# digest is currently: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc

# Fix padding of Base64 digests
while (length($digest) % 4) {
    $digest .= '=';
}

print $digest;
# digest is now: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=

Dart HMAC SHA256

Dependent upon the Dart crypto package.

import 'dart:html';
import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {

  String secret = 'secret';
  String message = 'Message';

  List<int> secretBytes = UTF8.encode('secret');
  List<int> messageBytes = UTF8.encode('Message');

  var hmac = new HMAC(new SHA256(), secretBytes);
  hmac.add(messageBytes);
  var digest = hmac.close();

  var hash = CryptoUtils.bytesToBase64(digest);

  // output to html page
  querySelector('#hash').text = hash;
  // hash => qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=
}

Swift HMAC SHA256

I have not verified but see this stackOverflow post

Rust

Take a look at the alco/rust-digest repository for Rust (lang) guidance. I have not verified yet.

Powershell (Windows) HMAC SHA256

Mostly wrapping of .NET libraries but useful to see it in powershell's befuddling syntax. See code as gist

$message = 'Message'
$secret = 'secret'

$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::ASCII.GetBytes($secret)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($message))
$signature = [Convert]::ToBase64String($signature)

echo $signature

# Do we get the expected signature?
echo ($signature -eq 'qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=')

Shell (Bash etc) HMAC SHA256

Using openssl. Credit to @CzechJiri

MESSAGE="Message"
SECRET="secret"

echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64

### Delphi HMAC SHA256

https://stackoverflow.com/a/40182566/215502

 

출처 : www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/

 

2020/12/16 - [개발노트] - Code 128 Barcode의 Check Digit 계산방법

2020/12/15 - [iOS/Tips] - 디버깅 차단 처리 (Anti Debug)

2020/12/14 - [iOS/Tips] - bundle id 알아내기

2020/12/12 - [AI/Algorithm] - 2D 충돌처리

2020/12/11 - [iOS/Swift] - UIViewController 스위칭

2020/12/11 - [개발노트] - PlantUML 설치 (Mac OS X)

2020/12/11 - [개발노트] - 특수문자 발음

2020/12/10 - [iOS/Objective-C] - 웹뷰에서 javascript 함수 동기식 호출

2020/12/10 - [iOS/Tips] - Fat Static Library 빌드 (2/2)

2020/12/10 - [iOS/Tips] - Fat Static Library 빌드 (1/2)

2020/12/10 - [iOS/Tips] - Custom UserAgent 설정

2020/12/10 - [iOS/Tips] - CocoaPods 설치 및 제거

2020/12/10 - [iOS/Tips] - Clang diagnostic 경고 무시하기

2020/12/10 - [개발노트] - Bluetooth UUID

2020/12/08 - [개발노트] - 모바일 앱 메모리덤프 이슈 해결방법

반응형

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

Base64 encode / decode in C++  (0) 2020.05.29
HTTP Content-Type  (0) 2020.05.29
UUID의 구성 요소  (0) 2020.05.19
Storyboard References (스토리보드 분리)  (0) 2020.05.18
Release 모드에서 디버깅  (0) 2020.05.18
블로그 이미지

SKY STORY

,

Array <-> Data 변환

개발/iOS 2020. 5. 26. 16:41
반응형
반응형

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

NSString <-> CBUUID 변환  (0) 2020.05.29
SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제 (1/2)  (0) 2020.05.28
UserAgent 변경/추가  (0) 2020.05.25
RSA 암호화 / 복호화  (0) 2020.05.25
Base64 인코딩/디코딩  (0) 2020.05.25
블로그 이미지

SKY STORY

,

UserAgent 변경/추가

개발/iOS 2020. 5. 25. 17:58
반응형
let webConfiguration = WKWebViewConfiguration()
webConfiguration.applicationNameForUserAgent = "customize User-Agent"
let webView = WKWebView(frame: .zero, configuration: webConfiguration)

Output : Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7

(KHTML, like Gecko) customize User-Agent

 

let webView = WKWebView()
webView.evaluateJavaScript("navigator.userAgent") { (userAgent, error) in
    if let ua = userAgent {
        print("default WebView User-Agent > \(ua)")
    }

    // User-Agent에 '(my test)' 추가할 경우
    webView.customUserAgent = "\(ua) (my test)"
}

UserDefaults.standard.register(defaults: ["UserAgent": userAgentValue])

 

Output : Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7

(KHTML, like Gecko) customize User-Agent (my test)

 

 

 

반응형

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

SEED 블록암호 알고리즘 CBC (Cipher Block Chaining) 예제 (1/2)  (0) 2020.05.28
Array <-> Data 변환  (0) 2020.05.26
RSA 암호화 / 복호화  (0) 2020.05.25
Base64 인코딩/디코딩  (0) 2020.05.25
Bitbucket Carthage 사용  (0) 2020.05.19
블로그 이미지

SKY STORY

,
반응형

RsaUtils 클래스를 생성하여 프로젝트에 추가한다.

//  RsaUtils.swift

import Foundation
import Security

public class RSAUtils {

    private static let PADDING_FOR_DECRYPT = SecPadding()

    @available(iOS, introduced: 1.2.0)
    public class RSAUtilsError: NSError {
        init(_ message: String) {
            super.init(domain: "com.ubpay.RSAUtils", code: 500, userInfo: [
                NSLocalizedDescriptionKey: message
            ])
        }

        @available(*, unavailable)
        required public init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }

    // Base64 encode a block of data
    @available(iOS, introduced: 1.2.0)
    private static func base64Encode(_ data: Data) -> String {
        return data.base64EncodedString(options: [])
    }

    // Base64 decode a base64-ed string
    @available(iOS, introduced: 1.2.0)
    private static func base64Decode(_ strBase64: String) -> Data {
        let data = Data(base64Encoded: strBase64, options: [])
        return data!
    }

    /**
     * Deletes an existing RSA key specified by a tag from keychain.
     *
     * - Parameter tagName: tag name to query for RSA key from keychain
     */
    @available(iOS, introduced: 1.2.0)
    public static func deleteRSAKeyFromKeychain(_ tagName: String) {
        let queryFilter: [String: AnyObject] = [
            String(kSecClass)             : kSecClassKey,
            String(kSecAttrKeyType)       : kSecAttrKeyTypeRSA,
            String(kSecAttrApplicationTag): tagName as AnyObject
        ]
        SecItemDelete(queryFilter as CFDictionary)
    }

    /**
     * Gets an existing RSA key specified by a tag from keychain.
     *
     * - Parameter tagName: tag name to query for RSA key from keychain
     *
     * - Returns: SecKey reference to the RSA key
     */
    @available(iOS, introduced: 1.2.0)
    public static func getRSAKeyFromKeychain(_ tagName: String) -> SecKey? {
        let queryFilter: [String: AnyObject] = [
            String(kSecClass)             : kSecClassKey,
            String(kSecAttrKeyType)       : kSecAttrKeyTypeRSA,
            String(kSecAttrApplicationTag): tagName as AnyObject,
            //String(kSecAttrAccessible)    : kSecAttrAccessibleWhenUnlocked,
            String(kSecReturnRef)         : true as AnyObject
        ]

        var keyPtr: AnyObject?
        let result = SecItemCopyMatching(queryFilter as CFDictionary, &keyPtr)
        if ( result != noErr || keyPtr == nil ) {
            return nil
        }
        return keyPtr as! SecKey?
    }

    /**
     * Adds a RSA private key (PKCS#1 or PKCS#8) to keychain and returns its SecKey reference.
     *
     * On disk, a PEM RSA PKCS#8 private key file starts with string "-----BEGIN PRIVATE KEY-----", and ends with string "-----END PRIVATE KEY-----"; PKCS#1 private key file starts with string "-----BEGIN RSA PRIVATE KEY-----", and ends with string "-----END RSA PRIVATE KEY-----".
     *
     * - Parameter privkeyBase64: RSA private key (PKCS#1 or PKCS#8) in base64
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the input key is not a valid PKCS#8 private key
     *
     * - Returns: SecKey reference to the RSA private key.
     */
    @available(iOS, introduced: 1.2.0)
    @discardableResult public static func addRSAPrivateKey(_ privkeyBase64: String, tagName: String) throws -> SecKey? {
        let fullRange = NSRange(location: 0, length: privkeyBase64.lengthOfBytes(using: .utf8))
        let regExp = try! NSRegularExpression(pattern: "(-----BEGIN.*?-----)|(-----END.*?-----)|\\s+", options: [])
        let myPrivkeyBase64 = regExp.stringByReplacingMatches(in: privkeyBase64, options: [], range: fullRange, withTemplate: "")
        return try addRSAPrivateKey(base64Decode(myPrivkeyBase64), tagName: tagName)
    }

    /**
     * Adds a RSA private key to keychain and returns its SecKey reference.
     *
     * - Parameter privkey: RSA private key (PKCS#1 or PKCS#8)
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the input key is not a valid PKCS#8 private key
     *
     * - Returns: SecKey reference to the RSA private key.
     */
    @available(iOS, introduced: 1.2.0)
    @discardableResult private static func addRSAPrivateKey(_ privkey: Data, tagName: String) throws -> SecKey? {
        // Delete any old lingering key with the same tag
        deleteRSAKeyFromKeychain(tagName)

        let privkeyData = try stripPrivateKeyHeader(privkey)
        if ( privkeyData == nil ) {
            return nil
        }

        // Add persistent version of the key to system keychain
        let queryFilter: [String : Any] = [
            (kSecClass as String)              : kSecClassKey,
            (kSecAttrKeyType as String)        : kSecAttrKeyTypeRSA,
            (kSecAttrApplicationTag as String) : tagName,
            //(kSecAttrAccessible as String)     : kSecAttrAccessibleWhenUnlocked,
            (kSecValueData as String)          : privkeyData!,
            (kSecAttrKeyClass as String)       : kSecAttrKeyClassPrivate,
            (kSecReturnPersistentRef as String): true
            ] as [String : Any]
        let result = SecItemAdd(queryFilter as CFDictionary, nil)
        if ((result != noErr) && (result != errSecDuplicateItem)) {
            NSLog("Cannot add key to keychain, status \(result).")
            return nil
        }

        return getRSAKeyFromKeychain(tagName)
    }

    /**
     * Verifies that the supplied key is in fact a PEM RSA private key, and strips its header.
     *
     * If the supplied key is PKCS#8, its ASN.1 header should be stripped. Otherwise (PKCS#1), the whole key data is left intact.
     *
     * On disk, a PEM RSA PKCS#8 private key file starts with string "-----BEGIN PRIVATE KEY-----", and ends with string "-----END PRIVATE KEY-----"; PKCS#1 private key file starts with string "-----BEGIN RSA PRIVATE KEY-----", and ends with string "-----END RSA PRIVATE KEY-----".
     *
     * - Parameter privkey: RSA private key (PKCS#1 or PKCS#8)
     *
     * - Throws: `RSAUtilsError` if the input key is not a valid RSA PKCS#8 private key
     *
     * - Returns: the RSA private key with header stripped.
     */
    @available(iOS, introduced: 1.2.0)
    private static func stripPrivateKeyHeader(_ privkey: Data) throws -> Data? {
        if ( privkey.count == 0 ) {
            return nil
        }

        var keyAsArray = [UInt8](repeating: 0, count: privkey.count / MemoryLayout<UInt8>.size)
        (privkey as NSData).getBytes(&keyAsArray, length: privkey.count)

        //PKCS#8: magic byte at offset 22, check if it's actually ASN.1
        var idx = 22
        if ( keyAsArray[idx] != 0x04 ) {
            return privkey
        }
        idx += 1

        //now we need to find out how long the key is, so we can extract the correct hunk
        //of bytes from the buffer.
        var len = Int(keyAsArray[idx])
        idx += 1
        let det = len & 0x80 //check if the high bit set
        if (det == 0) {
            //no? then the length of the key is a number that fits in one byte, (< 128)
            len = len & 0x7f
        } else {
            //otherwise, the length of the key is a number that doesn't fit in one byte (> 127)
            var byteCount = Int(len & 0x7f)
            if (byteCount + idx > privkey.count) {
                return nil
            }
            //so we need to snip off byteCount bytes from the front, and reverse their order
            var accum: UInt = 0
            var idx2 = idx
            idx += byteCount
            while (byteCount > 0) {
                //after each byte, we shove it over, accumulating the value into accum
                accum = (accum << 8) + UInt(keyAsArray[idx2])
                idx2 += 1
                byteCount -= 1
            }
            // now we have read all the bytes of the key length, and converted them to a number,
            // which is the number of bytes in the actual key.  we use this below to extract the
            // key bytes and operate on them
            len = Int(accum)
        }
        return privkey.subdata(in: idx..<idx+len)
        //return privkey.subdata(in: NSMakeRange(idx, len).toRange()!)
    }

    /**
     * Adds a RSA public key to keychain and returns its SecKey reference.
     *
     * - Parameter pubkeyBase64: X509 public key in base64 (data between "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----")
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the input key is indeed not a X509 public key
     *
     * - Returns: SecKey reference to the RSA public key.
     */
    @available(iOS, introduced: 1.2.0)
    public static func addRSAPublicKey(_ pubkeyBase64: String, tagName: String) throws -> SecKey? {
        let fullRange = NSRange(location: 0, length: pubkeyBase64.lengthOfBytes(using: .utf8))
        let regExp = try! NSRegularExpression(pattern: "(-----BEGIN.*?-----)|(-----END.*?-----)|\\s+", options: [])
        let myPubkeyBase64 = regExp.stringByReplacingMatches(in: pubkeyBase64, options: [], range: fullRange, withTemplate: "")
        return try addRSAPublicKey(base64Decode(myPubkeyBase64), tagName: tagName)
    }

    /**
     * Adds a RSA pubic key to keychain and returns its SecKey reference.
     *
     * - Parameter pubkey: X509 public key
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the input key is not a valid X509 public key
     *
     * - Returns: SecKey reference to the RSA public key.
     */
    @available(iOS, introduced: 1.2.0)
    private static func addRSAPublicKey(_ pubkey: Data, tagName: String) throws -> SecKey? {
        // Delete any old lingering key with the same tag
        deleteRSAKeyFromKeychain(tagName)

        let pubkeyData = try stripPublicKeyHeader(pubkey)
        if ( pubkeyData == nil ) {
            return nil
        }

        // Add persistent version of the key to system keychain
        //var prt1: Unmanaged<AnyObject>?
        let queryFilter: [String : Any] = [
            (kSecClass as String)              : kSecClassKey,
            (kSecAttrKeyType as String)        : kSecAttrKeyTypeRSA,
            (kSecAttrApplicationTag as String) : tagName,
            (kSecValueData as String)          : pubkeyData!,
            (kSecAttrKeyClass as String)       : kSecAttrKeyClassPublic,
            (kSecReturnPersistentRef as String): true
            ] as [String : Any]
        let result = SecItemAdd(queryFilter as CFDictionary, nil)
        if ((result != noErr) && (result != errSecDuplicateItem)) {
            return nil
        }

        return getRSAKeyFromKeychain(tagName)
    }

    /**
     * Verifies that the supplied key is in fact a X509 public key, and strips its header.
     *
     * On disk, a X509 public key file starts with string "-----BEGIN PUBLIC KEY-----", and ends with string "-----END PUBLIC KEY-----"
     *
     * - Parameter pubkey: X509 public key
     *
     * - Throws: `RSAUtilsError` if the input key is not a valid X509 public key
     *
     * - Returns: the RSA public key with header stripped.
     */
    @available(iOS, introduced: 1.2.0)
    private static func stripPublicKeyHeader(_ pubkey: Data) throws -> Data? {
        if ( pubkey.count == 0 ) {
            return nil
        }

        var keyAsArray = [UInt8](repeating: 0, count: pubkey.count / MemoryLayout<UInt8>.size)
        (pubkey as NSData).getBytes(&keyAsArray, length: pubkey.count)

        var idx = 0
        if (keyAsArray[idx] != 0x30) {
            throw RSAUtilsError("Provided key doesn't have a valid ASN.1 structure (first byte should be 0x30).")
            //return nil
        }
        idx += 1

        if (keyAsArray[idx] > 0x80) {
            idx += Int(keyAsArray[idx]) - 0x80 + 1
        } else {
            idx += 1
        }

        /*
         * If current byte is 0x02, it means the key doesn't have a X509 header (it contains only modulo & public exponent). In this case, we can just return the provided DER data as is
         */
        if (Int(keyAsArray[idx]) == 0x02) {
            return pubkey
        }

        let seqiod = [UInt8](arrayLiteral: 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00)
        for i in idx..<idx+seqiod.count {
            if ( keyAsArray[i] != seqiod[i-idx] ) {
                throw RSAUtilsError("Provided key doesn't have a valid X509 header.")
                //return nil
            }
        }
        idx += seqiod.count

        if (keyAsArray[idx] != 0x03) {
            throw RSAUtilsError("Invalid byte at index \(idx) (\(keyAsArray[idx])) for public key header.")
            //return nil
        }
        idx += 1

        if (keyAsArray[idx] > 0x80) {
            idx += Int(keyAsArray[idx]) - 0x80 + 1;
        } else {
            idx += 1
        }

        if (keyAsArray[idx] != 0x00) {
            throw RSAUtilsError("Invalid byte at index \(idx) (\(keyAsArray[idx])) for public key header.")
            //return nil
        }
        idx += 1
        return pubkey.subdata(in: idx..<keyAsArray.count)
        //return pubkey.subdata(in: NSMakeRange(idx, keyAsArray.count - idx).toRange()!)
    }

    /**
     * Encrypts data with a RSA key.
     *
     * - Parameter data: the data to be encrypted
     * - Parameter rsaKeyRef: the RSA key
     * - Parameter padding: padding used for encryption
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAKey(_ data: Data, rsaKeyRef: SecKey, padding: SecPadding) -> Data? {
        let blockSize = SecKeyGetBlockSize(rsaKeyRef)
        let dataSize = data.count / MemoryLayout<UInt8>.size
        let maxChunkSize = padding==SecPadding.OAEP ? (blockSize - 42) : (blockSize - 11)

        var dataAsArray = [UInt8](repeating: 0, count: dataSize)
        (data as NSData).getBytes(&dataAsArray, length: dataSize)

        var encryptedData = [UInt8](repeating: 0, count: 0)
        var idx = 0
        while (idx < dataAsArray.count ) {
            var idxEnd = idx + maxChunkSize
            if ( idxEnd > dataAsArray.count ) {
                idxEnd = dataAsArray.count
            }
            var chunkData = [UInt8](repeating: 0, count: maxChunkSize)
            for i in idx..<idxEnd {
                chunkData[i-idx] = dataAsArray[i]
            }

            var encryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
            var encryptedDataLength = blockSize

            let status = SecKeyEncrypt(rsaKeyRef, padding, chunkData, idxEnd-idx, &encryptedDataBuffer, &encryptedDataLength)
            if ( status != noErr ) {
                NSLog("Error while encrypting: %i", status)
                return nil
            }
            encryptedData += encryptedDataBuffer

            idx += maxChunkSize
        }

        return Data(bytes: UnsafePointer<UInt8>(encryptedData), count: encryptedData.count)
    }

    /**
     * Decrypts data with a RSA key.
     *
     * - Parameter encryptedData: the data to be decrypted
     * - Parameter rsaKeyRef: the RSA key
     * - Parameter padding: padding used for decryption
     *
     * - Returns: the decrypted data
     */
    @available(iOS, introduced: 1.2.0)
    public static func decryptWithRSAKey(_ encryptedData: Data, rsaKeyRef: SecKey, padding: SecPadding) -> Data? {
        let blockSize = SecKeyGetBlockSize(rsaKeyRef)
        let dataSize = encryptedData.count / MemoryLayout<UInt8>.size

        var encryptedDataAsArray = [UInt8](repeating: 0, count: dataSize)
        (encryptedData as NSData).getBytes(&encryptedDataAsArray, length: dataSize)

        var decryptedData = [UInt8](repeating: 0, count: 0)
        var idx = 0
        while (idx < encryptedDataAsArray.count ) {
            var idxEnd = idx + blockSize
            if ( idxEnd > encryptedDataAsArray.count ) {
                idxEnd = encryptedDataAsArray.count
            }
            var chunkData = [UInt8](repeating: 0, count: blockSize)
            for i in idx..<idxEnd {
                chunkData[i-idx] = encryptedDataAsArray[i]
            }

            var decryptedDataBuffer = [UInt8](repeating: 0, count: blockSize)
            var decryptedDataLength = blockSize

            let status = SecKeyDecrypt(rsaKeyRef, padding, chunkData, idxEnd-idx, &decryptedDataBuffer, &decryptedDataLength)
            if ( status != noErr ) {
                return nil
            }
            let finalData = removePadding(decryptedDataBuffer)
            decryptedData += finalData

            idx += blockSize
        }

        return Data(bytes: UnsafePointer<UInt8>(decryptedData), count: decryptedData.count)
    }

    @available(iOS, introduced: 1.2.0)
    private static func removePadding(_ data: [UInt8]) -> [UInt8] {
        var idxFirstZero = -1
        var idxNextZero = data.count
        for i in 0..<data.count {
            if ( data[i] == 0 ) {
                if ( idxFirstZero < 0 ) {
                    idxFirstZero = i
                } else {
                    idxNextZero = i
                    break
                }
            }
        }
        if ( idxNextZero-idxFirstZero-1 == 0 ) {
            idxNextZero = idxFirstZero
            idxFirstZero = -1
        }
        var newData = [UInt8](repeating: 0, count: idxNextZero-idxFirstZero-1)
        for i in idxFirstZero+1..<idxNextZero {
            newData[i-idxFirstZero-1] = data[i]
        }
        return newData
    }

    /**
     * Encrypts data using a RSA key from keychain specified by `tagName`.
     *
     * Note: The RSA key must be added to keychain by calling `addRSAPublicKey()` or `addRSAPrivateKey()` period to calling this function.
     *
     * - Parameter data: data to be encrypted
     * - Parameter tagName: tag name to query for RSA key from keychain.
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAKey(data: Data, tagName: String) -> Data? {
        let keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(data, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /**
     * Encrypts a string using a RSA key from keychain specified by `tagName`.
     *
     * Note: The RSA key must be added to keychain by calling `addRSAPublicKey()` or `addRSAPrivateKey()` period to calling this function.
     *
     * - Parameter str: string to be encrypted
     * - Parameter tagName: tag name to query for RSA key from keychain.
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAKey(str: String, tagName: String) -> Data? {
        let keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(str.data(using: .utf8)!, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /**
     * Decrypts an encrypted data using a RSA key from keychain specified by `tagName`.
     *
     * Note: The RSA key must be added to keychain by calling `addRSAPublicKey()` or `addRSAPrivateKey()` period to calling this function.
     *
     * - Parameter encryptedData: data to be decrypted
     * - Parameter tagName: tag name to query for RSA key from keychain.
     *
     * - Returns: the decrypted data
     */
    @available(iOS, introduced: 1.2.0)
    public static func decryptWithRSAKey(encryptedData: Data, tagName: String) -> Data? {
        let keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            return nil
        }

        return decryptWithRSAKey(encryptedData, rsaKeyRef: keyRef!, padding: PADDING_FOR_DECRYPT)
    }

    /*----------------------------------------------------------------------*/

    /**
     * Encrypts data using RSA public key.
     *
     * Note: the public key will be stored in keychain with tag as `pubkeyBase64.hashValue`.
     *
     * - Parameter data: data to be encrypted
     * - Parameter pubkeyBase64: X509 public key in base64 (data between "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----")
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid X509 public key
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAPublicKey(data: Data, pubkeyBase64: String) throws -> Data? {
        let tagName = "PUBIC-" + String(pubkeyBase64.hashValue)
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPublicKey(pubkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(data, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /**
     * Encrypts a string using RSA public key.
     *
     * Note: the public key will be stored in keychain with tag as `pubkeyBase64.hashValue`.
     *
     * - Parameter str: string to be encrypted
     * - Parameter pubkeyBase64: X509 public key in base64 (data between "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----")
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid X509 public key
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAPublicKey(str: String, pubkeyBase64: String) throws -> Data? {
        let tagName = "PUBIC-" + String(pubkeyBase64.hashValue)
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPublicKey(pubkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(str.data(using: .utf8)!, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /**
     * Encrypts data using RSA public key.
     *
     * Note: the public key will be stored in keychain specified by tagName.
     *
     * - Parameter data: data to be encrypted
     * - Parameter pubkeyBase64: X509 public key in base64 (data between "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----")
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid X509 public key
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAPublicKey(data: Data, pubkeyBase64: String, tagName: String) throws -> Data? {
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPublicKey(pubkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(data, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /**
     * Encrypts a string using RSA public key.
     *
     * Note: the public key will be stored in keychain specified by tagName.
     *
     * - Parameter str: string to be encrypted
     * - Parameter pubkeyBase64: X509 public key in base64 (data between "-----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----")
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid X509 public key
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func encryptWithRSAPublicKey(str: String, pubkeyBase64: String, tagName: String) throws -> Data? {
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPublicKey(pubkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return encryptWithRSAKey(str.data(using: .utf8)!, rsaKeyRef: keyRef!, padding: SecPadding.PKCS1)
    }

    /*----------------------------------------------------------------------*/

    /**
     * Decrypts an encrypted data using a RSA private key.
     *
     * Note: the private key will be stored in keychain with tag as `privkeyBase64.hashValue`.
     *
     * - Parameter encryptedData: data to be decrypted
     * - Parameter privkeyBase64: RSA PKCS#8 private key in base64 (data between "-----BEGIN PRIVATE KEY-----" and "-----END PRIVATE KEY-----")
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid RSA PKCS#8 private key
     *
     * - Returns: the decrypted data
     */
    @available(iOS, introduced: 1.2.0)
    public static func decryptWithRSAPrivateKey(encryptedData: Data, privkeyBase64: String) throws -> Data? {
        let tagName = "PRIVATE-" + String(privkeyBase64.hashValue)
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPrivateKey(privkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return decryptWithRSAKey(encryptedData, rsaKeyRef: keyRef!, padding: PADDING_FOR_DECRYPT)
    }

    /**
     * Decrypts an encrypted data using a RSA private key.
     *
     * Note: the private key will be stored in keychain specified by tagName.
     *
     * - Parameter encryptedData: data to be decrypted
     * - Parameter privkeyBase64: RSA PKCS#8 private key in base64 (data between "-----BEGIN PRIVATE KEY-----" and "-----END PRIVATE KEY-----")
     * - Parameter tagName: tag name to store RSA key to keychain
     *
     * - Throws: `RSAUtilsError` if the supplied key is not a valid RSA PKCS#8 private key
     *
     * - Returns: the data in encrypted form
     */
    @available(iOS, introduced: 1.2.0)
    public static func decryptWithRSAPrivateKey(encryptedData: Data, privkeyBase64: String, tagName: String) throws -> Data? {
        var keyRef = getRSAKeyFromKeychain(tagName)
        if ( keyRef == nil ) {
            keyRef = try addRSAPrivateKey(privkeyBase64, tagName: tagName)
        }
        if ( keyRef == nil ) {
            return nil
        }

        return decryptWithRSAKey(encryptedData, rsaKeyRef: keyRef!, padding: PADDING_FOR_DECRYPT)
    }
}

 

RSA 키 생성은 아래 사이트에서 생성 및 테스트하였다.

https://8gwifi.org/RSAFunctionality?keysize=2048

 

테스트를 위해 생성된 키쌍은 다음과 같다.

Generate RSA Key Size :2048 bit

RSA Ciphers : RSA

Public Key :

-----BEGIN PUBLIC KEY-----

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk3EUep+Y0Ps8qumkNW8x

fvAEpill5SG/jBN3bJhwr6G5qpiC0g1ys4YcV9T0KKg2JBJIYFCHht4DH5GMyRxu

SWxh2lRC0mGJ38QVHBUGoJcbclCN3wsrUI9T+FhHN7TRL3YF+MzdbdMNultaCKq1

9KoPgYLo342rrfyvI9D51peed3CotaoQFAK7UqX/oggoP04OQ83fkSkZCu7T5uBG

b3ARjapwSEvvlC+A4E8WtqwjCx6YoE/XRa9iPAR5Fm0KUK2G8La0g9oUtG2dn+gL

iHkX00iI5PlIe0cFjPmKb5N75fLZNA9g0CkpVG2DrIGbdgp2CHD4Ufk3U99NSaH0

XwIDAQAB

-----END PUBLIC KEY-----

Private Key :

-----BEGIN RSA PRIVATE KEY-----

MIIEpAIBAAKCAQEAk3EUep+Y0Ps8qumkNW8xfvAEpill5SG/jBN3bJhwr6G5qpiC

0g1ys4YcV9T0KKg2JBJIYFCHht4DH5GMyRxuSWxh2lRC0mGJ38QVHBUGoJcbclCN

3wsrUI9T+FhHN7TRL3YF+MzdbdMNultaCKq19KoPgYLo342rrfyvI9D51peed3Co

taoQFAK7UqX/oggoP04OQ83fkSkZCu7T5uBGb3ARjapwSEvvlC+A4E8WtqwjCx6Y

oE/XRa9iPAR5Fm0KUK2G8La0g9oUtG2dn+gLiHkX00iI5PlIe0cFjPmKb5N75fLZ

NA9g0CkpVG2DrIGbdgp2CHD4Ufk3U99NSaH0XwIDAQABAoIBABCid28GRpV9YvDd

f1tP+kOaDMw6a3aYgiXppFWqNTx7gJkQr+HHBqPeg6AdNJbJs6IKNgQ30bKTpcKQ

B1RBUugRxFB/pTJbMtT+KGuMq7y+j6gsEnWRqwdhxFWGkDJmwhsas73IT0suvqPB

3ryPlgvOjAVOobtnHnF4ysG9uBJPyP03hCG97OIuHCQ0wpGlQAktyh7J5jXfGBJp

+bfOLGXZCqFO+iU0CRCf6si8/owTTXOYw7sANjtzbQt69GO+Vr3hi8SC2rGf/bkq

XFrajTOf1UC2wENKZJTY2H4cxedVViCMRThjMh5K1+661gKwUbSXyqN4jF4qsy/H

iAN/hgECgYEAyyf4dFhxjnTj7UiJtljqsF9seChqjtXHjHx0yq3wMCl+UMeMZ4Df

b5zOk9n4E6ntTEom4ZkUY+zYX+K4rR4W7FV5hhH/F5n+9BfXTludyPaQDWhpnaHw

1ZjQ8i7VMiYmy393Wd5sT5d1tDs4C1bvq10yAydKFV5a3bron8PsIt8CgYEAucsf

zQGtKb7emnDW4Cg61t1Bg/HXDxhm0EunP6gmTI+SUP/zZehg23xdajKYZ3zb3npm

Lz8LxGAxFIdp2o6BGgbTjotBTNlrza9Zh2H3BnV74TKS/gag3LfBtuRdZwhKgCPs

g4kkH4D1t6hza0Nql8cVjLvJnl++J+6YX3J53oECgYEAnIfvp7V9yYXHGM0LTrS0

H7Fmoi6B7AxL9LLwSjo7FuDhstwOErH5dsYbZVBNFNmZPW7lBm4sh9G15iuKn9jP

UMmLGQJEyqqdBvZXrshoiq9vzuTke9CLAAj+9ZugKUO8II/WJih6y9inmHcId7RE

doUYQ9XB/zT0TmP1WSRcjYECgYA37vDp9QE+uhmmASaPYU0ldoLMyDfocX4yYzQ8

s9Cj5+0yuXt7SJQwP6aX3BeJwEspFUxCGQbf3d2owoOZqqEvRrLWDRJhomsUByA6

48FMjn329BTQqQowqJmHCAUeiZ50KVyA1P6tBVP0MKBewHMMsoDIV5iBN22189yn

j30lAQKBgQCZoAR0wMlhcXqMt6GwlRDCrkBURyKy29sW+77AxXALPuxUGeEV0iBS

TFc8UUgmtMt7ZmaynukPThI7qtLXsNibVYFqENy1dF64SHIa1a0Qa0fBnhDqqWdk

oDeXJrKFS38ZGNfPpbPmI9Ti/7h2ct7WWWZAEtGO1buk7nZCxiOxig==

-----END RSA PRIVATE KEY-----

 

 

RSA Encode

// RSA Encode
let publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk3EUep+Y0Ps8qumkNW8xfvAEpill5SG/jBN3bJhwr6G5qpiC0g1ys4YcV9T0KKg2JBJIYFCHht4DH5GMyRxuSWxh2lRC0mGJ38QVHBUGoJcbclCN3wsrUI9T+FhHN7TRL3YF+MzdbdMNultaCKq19KoPgYLo342rrfyvI9D51peed3CotaoQFAK7UqX/oggoP04OQ83fkSkZCu7T5uBGb3ARjapwSEvvlC+A4E8WtqwjCx6YoE/XRa9iPAR5Fm0KUK2G8La0g9oUtG2dn+gLiHkX00iI5PlIe0cFjPmKb5N75fLZNA9g0CkpVG2DrIGbdgp2CHD4Ufk3U99NSaH0XwIDAQAB"

let string = "hello world"
//let data = string.data(using: .utf8)!
let encryptedData = try! RSAUtils.encryptWithRSAPublicKey(str: string, pubkeyBase64: publicKey)// Data
let encryptedString = (encryptedData!.base64EncodedString()) as String// Base64
print("\(encryptedString)")

Output: eDXn/2IJZYiCULVYR+IvmF6FVMvgU9YLVTnzDLlaXUJKib0FJy8Zhc2gJUZTtDtg4n48zVYU/jTL9UV0mpUls9jKScEBmm5lkR8qzV80skaAPTGnknYFg7nBtrsQPy2l1EUK0W9KaK1wN47JO/Si2Lyt9po3W2ErUFo1El3Gt/PdHTVpzftC64D+3iY/JU7YeHwBllPwEHQkY3hpgcVl4BxyNfbMCZuQXw5R8qiv5PObcKVliBYO7N4+5lXJXQoldMtGXzm+5G9M8xBgJDPJXzeqxl63o4AmG0ULKvhvHirHScOn0jvT5BEXM+oCkFm5SntQRt/iHtKCeIjqLE5eUg==

 

RSA Decode

let privateKey = "MIIEpAIBAAKCAQEAk3EUep+Y0Ps8qumkNW8xfvAEpill5SG/jBN3bJhwr6G5qpiC0g1ys4YcV9T0KKg2JBJIYFCHht4DH5GMyRxuSWxh2lRC0mGJ38QVHBUGoJcbclCN3wsrUI9T+FhHN7TRL3YF+MzdbdMNultaCKq19KoPgYLo342rrfyvI9D51peed3CotaoQFAK7UqX/oggoP04OQ83fkSkZCu7T5uBGb3ARjapwSEvvlC+A4E8WtqwjCx6YoE/XRa9iPAR5Fm0KUK2G8La0g9oUtG2dn+gLiHkX00iI5PlIe0cFjPmKb5N75fLZNA9g0CkpVG2DrIGbdgp2CHD4Ufk3U99NSaH0XwIDAQABAoIBABCid28GRpV9YvDdf1tP+kOaDMw6a3aYgiXppFWqNTx7gJkQr+HHBqPeg6AdNJbJs6IKNgQ30bKTpcKQB1RBUugRxFB/pTJbMtT+KGuMq7y+j6gsEnWRqwdhxFWGkDJmwhsas73IT0suvqPB3ryPlgvOjAVOobtnHnF4ysG9uBJPyP03hCG97OIuHCQ0wpGlQAktyh7J5jXfGBJp+bfOLGXZCqFO+iU0CRCf6si8/owTTXOYw7sANjtzbQt69GO+Vr3hi8SC2rGf/bkqXFrajTOf1UC2wENKZJTY2H4cxedVViCMRThjMh5K1+661gKwUbSXyqN4jF4qsy/HiAN/hgECgYEAyyf4dFhxjnTj7UiJtljqsF9seChqjtXHjHx0yq3wMCl+UMeMZ4Dfb5zOk9n4E6ntTEom4ZkUY+zYX+K4rR4W7FV5hhH/F5n+9BfXTludyPaQDWhpnaHw1ZjQ8i7VMiYmy393Wd5sT5d1tDs4C1bvq10yAydKFV5a3bron8PsIt8CgYEAucsfzQGtKb7emnDW4Cg61t1Bg/HXDxhm0EunP6gmTI+SUP/zZehg23xdajKYZ3zb3npmLz8LxGAxFIdp2o6BGgbTjotBTNlrza9Zh2H3BnV74TKS/gag3LfBtuRdZwhKgCPsg4kkH4D1t6hza0Nql8cVjLvJnl++J+6YX3J53oECgYEAnIfvp7V9yYXHGM0LTrS0H7Fmoi6B7AxL9LLwSjo7FuDhstwOErH5dsYbZVBNFNmZPW7lBm4sh9G15iuKn9jPUMmLGQJEyqqdBvZXrshoiq9vzuTke9CLAAj+9ZugKUO8II/WJih6y9inmHcId7REdoUYQ9XB/zT0TmP1WSRcjYECgYA37vDp9QE+uhmmASaPYU0ldoLMyDfocX4yYzQ8s9Cj5+0yuXt7SJQwP6aX3BeJwEspFUxCGQbf3d2owoOZqqEvRrLWDRJhomsUByA648FMjn329BTQqQowqJmHCAUeiZ50KVyA1P6tBVP0MKBewHMMsoDIV5iBN22189ynj30lAQKBgQCZoAR0wMlhcXqMt6GwlRDCrkBURyKy29sW+77AxXALPuxUGeEV0iBSTFc8UUgmtMt7ZmaynukPThI7qtLXsNibVYFqENy1dF64SHIa1a0Qa0fBnhDqqWdkoDeXJrKFS38ZGNfPpbPmI9Ti/7h2ct7WWWZAEtGO1buk7nZCxiOxig=="
        
let decryptedData = try! RSAUtils.decryptWithRSAPrivateKey(encryptedData: encryptedData!, privkeyBase64: privateKey)// Data
let decryptedString = String(data: decryptedData!, encoding: .utf8)
print("\(decryptedString)")

Output:  hello world

 

출처 : 

https://github.com/btnguyen2k/swiftutils/blob/master/SwiftUtils/RSAUtils.swift

 

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 사용

2020/05/19 - [iOS/Jailbreak] - Frida 설치 및 사용법

2020/05/19 - [OS/Mac OS X] - gdb 설치

2020/05/19 - [OS/Mac OS X] - Mac에서 Node.js 설치

반응형

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

Array <-> Data 변환  (0) 2020.05.26
UserAgent 변경/추가  (0) 2020.05.25
Base64 인코딩/디코딩  (0) 2020.05.25
Bitbucket Carthage 사용  (0) 2020.05.19
Fridump 사용법 (3/4) - 메모리 덤프  (0) 2020.05.19
블로그 이미지

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

 

// String을 Data로 변경
let string = "hello world"
let strData = string.data(using: .utf8)!

 

 

Base64 인코딩 / 디코딩 ( String )

// Base64 인코딩 ( Data -> Base64 encoded String )
let base64EncString = strData.base64EncodedString()

// Base64 디코딩 ( Base64 encoded String -> Base64 decoded String )
let decodedData = Data(base64Encoded: base64EncString)!
let base64DecString = String(data: decodedData, encoding: .utf8)!


print("Base64인코딩(String) : \(base64EncString)")
print("Base64디코딩(String) : \(base64DecString)")

 

 

Base64 인코딩 / 디코딩 ( Data )

// Base64 인코딩 ( Data -> Base64 encoded Data )
let base64EncData = strData.base64EncodedData(options: .lineLength64Characters)

// Base64 디코딩 ( Base64 encoded Data -> Base64 decoded Data )
let base64DecData = Data(base64Encoded: base64EncData, options: [])! as Data


print("Base64인코딩(Data) : \(String(data: base64EncData, encoding: .utf8)!)")
print("Base64디코딩(Data) : \(String(data: base64DecData, encoding: .utf8)!)")

 

스마트폰 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/25 - [iOS/Swift] - RSA 암호화 / 복호화

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 사용

2020/05/19 - [iOS/Jailbreak] - Frida 설치 및 사용법

2020/05/19 - [OS/Mac OS X] - gdb 설치

2020/05/19 - [OS/Mac OS X] - Mac에서 Node.js 설치

반응형

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

UserAgent 변경/추가  (0) 2020.05.25
RSA 암호화 / 복호화  (0) 2020.05.25
Bitbucket Carthage 사용  (0) 2020.05.19
Fridump 사용법 (3/4) - 메모리 덤프  (0) 2020.05.19
Fridump 사용법 (2/4) - Mac OS X 환경 구축  (0) 2020.05.19
블로그 이미지

SKY STORY

,