반응형

스마트폰 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

 

웹에서 앱을 실행할 경우 대부분 URL scheme을 이용한다.

그런데 만약 같은 scheme id를 사용하는 앱이 2개 이상이면 

어떻게 될까?  안드로이드 운영체제에서는 앱 선택창이 떠서

원하는 앱을 실행할 수 있지만 iOS에서는 무작위로 실행된다.

(물론 내부적으로 규칙은 있겠지만... 공개되어있지 않음)

 

※ iOS 14.4.1버전 부터 타임 트릭을 이용한 앱 존재 여부 체크가

사파리가 비활성화 되도 타이머가 진행되어 앱이 존재하더라도

앱 실행 후 앱스토어 이동이 동시에 일어나는 문제가 발생한다.

 

이럴경우를 위해 URL scheme 대신 도메인 주소로 앱을 

실행할 수 있도록 한 것이 Universal Link이다.

 

유니버셜링크 환경설정 방법을 알아보자.

 

 

개발자 사이트 접속

https://developer.apple.com

 

Certificates, Identifiers & Profiles / Identifiers 선택

 

적용할 App ID 선택하고 'Associated Domains' 체크 

 

Provisioning Profile 설정이 바뀌었으므로 다시 활성화 시킨다.

 

 

Xcode에서 'Associated Domains' 을 추가

 

applinks 도메인 추가

 

스마트폰 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

 

2021.03.16 - [iOS/Tips] - Universal Link (1/4) - 네이티브 환경설정

2021.03.16 - [iOS/Tips] - Universal Link (2/4) - 네이티브 링크 수신

2021.03.16 - [iOS/Tips] - Universal Link (3/4) - 웹서버 환경 설정

2021.03.16 - [iOS/Tips] - Universal Link (4/4) - 웹서버 환경 검증

2020.12.08 - [프로그래밍/Java Script] - Android, iOS 앱 설치여부 체크 및 스토어 이동

2021.06.17 - [iOS/Tips] - Firebase dynamic link (다이나믹 링크) (1/4)

2021.06.17 - [iOS/Tips] - Firebase dynamic link (다이나믹 링크) (2/4)

2021.06.17 - [iOS/Tips] - Firebase dynamic link (다이나믹 링크) (3/4)

2021.06.17 - [iOS/Tips] - Firebase dynamic link (다이나믹 링크) (4/4)

 

반응형

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

Universal Link (3/4) - 웹서버 환경 설정  (0) 2021.03.16
Universal Link (2/4) - 네이티브 링크 수신  (0) 2021.03.16
ARC or Non-ARC Compile Flag 설정  (0) 2021.02.05
String to CGFloat  (0) 2021.01.06
SceneDelegate 포인터 구하기  (0) 2021.01.05
블로그 이미지

SKY STORY

,
반응형

root-level 디렉토리이 기본적으로 생성되어있는 디렉토리는 다음과 같다.

/Applications, /Library, /System, /Users

이곳에 폴더 및 심볼릭링크 생성이 권한문제로 불가능하지만

다음 과정을 통해 생성 가능하다.

/etc 디렉토리에 synthetic.conf 파일 생성

sudo touch /etc/synthetic.conf

 

파일 권한 설정

sudo chmod 755 /etc/synthetic.conf

 

파일에 디렉토리 이름 선언

# 폴더 생성

MyFolder

# 심볼릭링크 폴더 생성

MySymbolicLinkFolder    /Volumes/DATA/MySymbolicLinkFolder

 

저장 후 재부팅

2021.02.22 - [COIN] - DogeCoin Mining

2021.02.08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

2021.02.08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021.02.08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021.02.08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021.02.08 - [Proxmark3] - Proxmark3 RFID Tool

2021.02.05 - [프로그래밍/Java] - RSA 암복호화 테스트

2021.02.05 - [프로그래밍/Java] - RSA key 파일 생성

2021.02.05 - [개발노트] - 용어 정리

반응형

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

git 소스코드 비교  (0) 2022.02.23
20진수 변환  (0) 2021.09.16
RSA 암복호화 테스트  (0) 2021.02.05
RSA key 파일 생성  (0) 2021.02.05
용어 정리  (0) 2021.02.05
블로그 이미지

SKY STORY

,
반응형

1. 카드 감지 및 기본 정보 읽기

hf search

- UID (Unique Identifier):

  카드의 고유 식별 번호이다. 카드가 시스템에서 식별되는 데 사용된다. 이 번호는 카드 제조사에 의해 프로그램되며, 대부분 변경할 수 없다. 

- ATQA (Answer To Request Type A):

  00 04: 카드의 타입과 호환성을 나타내는 응답 코드이다. 이는 카드가 ISO/IEC 14443-A 프로토콜을 따른다는 것을 의미하며, 카드가 어떤 기능과 속성을 지원하는지를 나타낸다.

- SAK (Select Acknowledge):

  08 [2]: 카드의 응답 데이터로, 카드의 종류와 지원 기능을 나타낸다. 예를 들어, 08은 일반적으로 MIFARE Classic 1K 카드를 의미한다. 이 정보는 카드가 MIFARE Classic 프로토콜을 준수하고, 보안이나 메모리 관련 기능에 대한 정보를 제공한다.

- TYPE (Card Type):

  NXP MIFARE CLASSIC 1k | Plus 2k SL1: 카드의 제조사 및 모델명이다. 이 경우, NXP에서 제조한 MIFARE Classic 1K 또는 Plus 2K SL1 카드이다. 이는 카드의 메모리 용량과 보안 레벨을 나타낸다.

- Proprietary Non ISO14443-4 Card Found:

  이 문구는 카드가 표준 ISO/IEC 14443-4 프로토콜을 지원하지 않는다는 것을 의미한다. MIFARE Classic 카드는 자체 프로토콜을 사용하기 때문에, 이는 일반적인 경고 문구이다.

- RATS (Request for Answer To Select) Not Supported:

  RATS는 ISO/IEC 14443-4 카드에서 초기화 및 통신 설정에 사용된다. 이 경고는 해당 카드가 RATS 명령을 지원하지 않는다는 것을 나타내며, MIFARE Classic 카드에서는 일반적인 경우이다.

- No Chinese Magic Backdoor Command Detected:

  일부 카드에는 백도어 명령을 사용하여 보안 메커니즘을 우회할 수 있는 비공식 기능이 있다. 이 메시지는 해당 카드가 그러한 명령을 지원하지 않는다는 것을 나타낸다. 즉, 이 카드에는 알려진 백도어가 없다는 의미이다.

- Prng Detection: WEAK:

  카드의 난수 생성기(PRNG)의 보안 수준을 나타낸다. WEAK는 카드의 PRNG가 예측 가능성이 높아 보안상 취약할 수 있다는 것을 의미한다. MIFARE Classic 카드의 보안 취약점 중 하나이다.

- Valid ISO14443A Tag Found – Quitting Search:

  유효한 ISO/IEC 14443-A 태그가 발견되었음을 나타내며, 검색을 종료하는 메시지이다.

 

2. 카드의 보안 분석 (복제 가능 여부 판단)

hf mf chk *1 ? t

- 명령어 분석: hf mf chk *1 ? t

  • 이 명령어는 MIFARE Classic 카드의 모든 섹터에 대해 기본 키를 사용하여 읽기 시도 및 검증을 수행한다.

  • *1은 카드의 첫 번째 메모리 블록부터 모든 섹터를 확인하겠다는 의미이다.

  • ?는 읽기 시도를 하고 키가 올바른지 확인하도록 지시한다.

  • t 옵션은 터미널 출력 모드를 지정하며 결과를 표 형식으로 출력하도록 한다.

- 출력 내용 설명

1. No key specified, trying default keys:

  • 지정된 키가 없어서 기본 키 목록을 사용하여 시도하고 있다는 의미이다.

2. chk default key[0] ~ key[17]:

  • 이 부분은 Proxmark3가 MIFARE Classic 카드의 기본 키 리스트를 사용해 각 섹터의 읽기 권한을 확인하고 있는 과정이다.

  • 예를 들어, ffffffffffff, 000000000000, a0a1a2a3a4a5 등 잘 알려진 기본 키를 사용해 각 섹터에 대한 액세스 시도를 수행한다.

- 표 내용 분석:

  • sec: 섹터 번호이다. 000, 001, 002, … 등의 번호가 섹터를 나타낸다.

  • key A: 섹터에 대한 Key A의 값이다. ffffffffffff와 같은 기본 키를 사용해 시도한 결과를 표시한다.

  • res (결과): 시도한 키로 접근이 성공했는지를 나타내며, 1은 성공, 0은 실패를 의미한다.

  • key B: 섹터에 대한 Key B의 값이다. 역시 기본 키를 사용해 시도한 결과가 표시된다.

  • res (결과): Key B에 대한 접근 성공 여부를 나타낸다.

- 요약

  • Proxmark3가 기본 키로 각 섹터의 접근을 시도했고, 대부분 성공한 것을 볼 수 있다.

  • 이 과정은 MIFARE Classic 카드의 보안 분석이나 카드 복제를 위한 중요한 단계이다.

  • 접근이 실패한 섹터의 경우, 추가적인 키 추출이나 분석이 필요할 수 있다.

 

3. 카드 키를 크래킹하고 덤프파일 생성

hf mf nested 1 0 A ffffffffffff d

- 명령어 분석: hf mf nested 1 0 A ffffffffffff d

  • hf mf nested: MIFARE Classic 카드의 키를 크래킹하는 명령어이다. 인증 방식을 통해 기본 키를 사용하여 다른 섹터의 키를 찾는다.

  • 1: 첫 번째 섹터(섹터 1)에서 시작하겠다는 의미이다.

  • 0: 블록 0에서 인증을 시도한다.

  • A: Key A를 사용해 인증을 시도한다.

  • ffffffffffff: 인증에 사용할 기본 Key A 값이다.

  • d: 결과를 출력할 때 디버그 정보를 표시한다.

- 출력 내용 설명

  1. Nested statistic:

    • 명령어의 실행 결과에 대한 요약 통계이다.

    • 'Iterations count: 6'은 이 작업이 6번의 반복을 거쳐 수행되었음을 나타낸다.

    • 'Time in nested'는 이 작업이 걸린 총 시간을 보여주며, 4.921초 동안 수행되었다.

  2. 각 섹터에 대한 결과 표:

    • sec: 섹터 번호이다. 각 섹터의 Key A와 Key B에 대한 시도 결과가 표시된다.

    • key A: 발견된 Key A 값이다.

    • res (결과): Key A의 인증 결과를 나타내며, 1은 성공, 0은 실패를 의미한다.

    • key B: 발견된 Key B 값이다.

    • res (결과): Key B의 인증 결과를 나타낸다.

  3. 유효한 키 발견:

    • Found valid key 메시지와 함께 표시된 키는 작업 중에 유효한 키가 발견되었음을 나타낸다.

    • 예를 들어, 섹터 9에서 Key A와 Key B에 대해 각각 유효한 키가 발견되었고, 그 키가 표에 표시되어 있다.

  4. Printing keys to binary file dumpkeys.bin...:

    • 발견된 키들을 dumpkeys.bin 파일로 출력하여 저장하고 있다는 의미이다. 이 파일은 나중에 카드 데이터에 접근하거나 복제할 때 사용할 수 있다.

- 주요 설명

  • Nested 공격 방식은 인증된 섹터의 키를 사용해 이웃 섹터의 키를 추출해 나가는 방식으로, 보안 연구나 교육 목적으로 사용된다.

  • 성공적인 키 발견은 해당 섹터의 Key A 또는 Key B를 찾았다는 것을 의미하며, 이를 통해 카드의 다른 섹터에 접근할 수 있게 된다.

  • 디버그 정보는 각 인증 시도의 세부적인 과정과 실패/성공 여부를 자세히 보여준다.

- 결론

  • 이 결과는 MIFARE Classic 카드의 특정 섹터에서 Key A와 Key B를 성공적으로 찾아냈음을 보여준다. 이를 통해 해당 카드의 데이터를 덤프하거나 복제할 수 있는 기반이 마련됬었다.

- 발견된 키 정보 저장

 hf mf chk keydump > keys.bin

 

4. 홈 디렉토리에 ‘dumpkeys.bin’파일이 생성된다.

 

5. 모든 섹터 데이터를 덤프

hf mf dump

... 중간 생략 ...

 

6.홈 디렉토리에 ‘dumpdata.bin’파일이 생성된다.

 

7. 원본 카드를 제거하고 복제할 카드를 올려놓는다.

 

8. 복제할 카드의 UID값을 원본 카드의 UID값을 설정한다.

hf mf csetuid xxxxxxxx

 

9. 복사할 카드에 원본데이터로 복원한다. 

hf mf restore 1

... 중간 생략...

- 명령어 분석: hf mf restore 1

  섹터 1의 데이터를 덮어쓰기하며, 백업된 데이터가 유효하고 올바른 접근 키를 사용할 수 있어야 한다.

  현재 위치에 존재하는 dumpdata.bin 또는 dumpkeys.bin 파일을 읽어 두번째 섹터1에 복제한다.

 

10.복제 완료. 

- 전원 OFF 이후 다시 복제 시도

  hf mf nested 명령으로 발견된 키 정보는 카드의 섹터 접근 권한을 얻기 위해 필요하다. 이 키 정보는 hf mf restore 명령어가 섹터의 데이터를 복원할 때 인증 단계에서 사용된다. 해당 키 정보는 Proxmark3의 메모리에 남아있다. 즉, 전원이 OFF되면 해당 정보는 사라진다.

  만약 Proxmark3 메모리에 키 정보가 없는 상태에서 덤프파일로 복제를 시도하려면 키 파일을 로드한 후 복제 명령을 시도하면 된다. 

  hf mf cload f keys.bin

  hf mf restore 1

 

 

2021/02/08 - [Proxmark3] - Proxmark3 RFID Tool

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

 

반응형
블로그 이미지

SKY STORY

,
반응형

Testing

 

1. USB 연결을 해제한 뒤 다시 재 접속을 한다. (연결이 안되면 재부팅 후 재시도)

 

2.USB연결 기기정보 확인

system_profiler SPUSBDataType

... 중간 생략 ...

 

3.proxmark3 시작

/usr/local/Cellar/proxmark3/3.1.0/bin/proxmark3 /dev/cu.usbmodem146224101

 

4.명령어 목록 확인

help

 

2021/02/08 - [Proxmark3] - Proxmark3 RFID Tool

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

 

반응형
블로그 이미지

SKY STORY

,
반응형

Update

 

1.설치 디렉토리 이동

cd /usr/local/Cellar/proxmark3/3.1.0

or

cd /opt/homebrew/Cellar/proxmark3/3.1.0

 

2. 파일 목록 확인

ls -la

 

3.디바이스 연결 확인

ls /dev/cu*

or

좌측 Button을 누른 상태로 USB를 재연결 한다. 약 5초뒤 기기가 연결된다. 계속 누른상태는 유지한다.

이후 조회하면 아래와 같이 ‘/dev/cu.usbmodem146224101’라는 장치가 추가 됬음을 알 수 있다.

 

4.Flash the Bootrom

bootrom을 업그레이드 한다.

./bin/proxmark3-flasher /dev/cu.usbmodem146224101 -b ./share/firmware/bootrom.elf

or

./bin/proxmark3-flasher /dev/cu.usbmodem114301 -b ./share/firmware/bootrom.elf

 

5.Update the Firmware(FPGA and OS)

펌웨어 (FPGA와 OS) 업데이트

./bin/proxmark3-flasher /dev/cu.usbmodem146224101 ./share/firmware/fullimage.elf

or

./bin/proxmark3-flasher /dev/cu.usbmodem114301 ./share/firmware/fullimage.elf

 

6.설치 완료. 

 

2021/02/08 - [Proxmark3] - Proxmark3 RFID Tool

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

 

반응형
블로그 이미지

SKY STORY

,
반응형

Mac 환경에서 개발환경 구축 방법을 알아보도록 한다.

테스트된 운영체제 환경은 다음과 같다.

macOS Big Sur Version 11.2

 

Tap and Build

1. homebrew 설치 

http://brew.sh/

 

2.Mac Ports 설치

https://www.macports.org/install.php

 

3. Tap proxmark repo

brew tap proxmark/proxmark3

 

4. Install Proxmark3

안정 버전 :

brew install proxmark3

최신 버전(비 안정 버전) :

brew install --HEAD proxmark3

… 중간생략 …

 

 

2021/02/08 - [Proxmark3] - Proxmark3 RFID Tool

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

반응형
블로그 이미지

SKY STORY

,
반응형

 

개발자 커뮤니티 사이트

Proxmark3 developers community

http://proxmark.org/forum/index.php

 

개요

  • proxmark3는 강력한 범용 RFID 툴입니다.
  • 신용카드 크기의 리더기로 동작하며 125khz의 저주파수 태그에서 13.56mhz의 고주파 태그에 이르기까지의 모든 것을 에뮬레이션이 가능하고, 다른 리더기와 태그 사이의 통신 트랜잭션 정보를 엿들을 수 있습니다.
  • 프록스마크 보드와 LF, HF 안테나 및 RFID 태그 등이 포함되어 있습니다.
  • 프록스마크 전체 하드웨어 및 소프트웨어 플랫폼은 오픈소스입니다.
  • 알림: 본 제품은 연구/개발용/교육용 제품으로 기타의 목적으로 사용될 수 없습니다.

 

특징

Supporting tags

 

 

참고자료 :

https://axcheron.github.io/updating-the-proxmark3-on-osx/

https://www.gavinjl.me/proxmark-3-cloning-a-mifare-classic-1k/

 

1. http://www.proxmark.org/forum

proxmark3 와 관련한 포럼

 

2. http://www.libnfc.org/

NFC(Near Field Communication) 와 관련한 libnfc 사이트

 

3. http://www.libnfc.org/community/

libnfc 와 관련한 포럼

 

4. http://code.google.com/p/proxmark3/

proxmark3 firmware site

 

5. http://code.google.com/p/micmd/

mifare classic command line 유틸

 

6. http://code.google.com/p/nfc-tools/

libnfc 와 관련한 툴

 

7. http://code.google.com/p/mfcuk/

mifare classic universal toolkit

(Dark side Attack implementation~! ^^)

 

8. http://code.google.com/p/crapto1/

mirare classic 에 사용된 crypto-1 의 구현 및 그 취약성을 역이용한 crapto1 구현

 

9. http://www.libnfc.org/community/topic/89/mifare-classic-offline-cracker/

http://www.nethemba.com/mfoc.tar.bz2

mifare classic offline cracker

 

2021/02/08 - [Proxmark3] - Proxmark3 RFID Tool

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (1/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (2/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (3/4)

2021/02/08 - [Proxmark3] - Proxmark3 V5 개발환경 구축 (4/4)

반응형
블로그 이미지

SKY STORY

,
반응형

RSA 키생성 후 생성된 키로 암복호화 테스트 해 보았다.

package com.rsatest.rsaTest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.apache.commons.codec.binary.Base64;


//
// RSA 암복호화 및 테스트
//
// Created by netcanis on 2019/04/29.
// Copyright © 2019 netcanis. All rights reserved.
//

public class RSAEncryption
{
	private Cipher cipher;
	
	public RSAEncryption() throws NoSuchAlgorithmException, NoSuchPaddingException{
		this.cipher = Cipher.getInstance("RSA");
	}
	
	// 주어진 파일을 byte array로 읽기 
	public byte[] getFileInBytes(File f) throws IOException{
		FileInputStream fis = new FileInputStream(f);
		byte[] fbytes = new byte[(int) f.length()];
		fis.read(fbytes);
		fis.close();
		return fbytes;
	}
		
	// X509EncodedKey
	public PublicKey getPublic(String filename) throws Exception {
		byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
		X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		return kf.generatePublic(spec);
	}

	// PKCS8EncodedKeySpec
	public PrivateKey getPrivate(String filename) throws Exception {
		byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
		
		//byte[] decoded = Base64.getDecoder().decode(keyBytes);
		//println(new String(decoded));    // Outputs "Hello"
		
		//Base64 codec = new Base64();
		//byte[] decoded = codec.decode(keyBytes);
		//System.out.println( new String(decoded) );    // Outputs "Hello"
		
		PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		return kf.generatePrivate(spec);
	}
	
	
	
	// PKCS1
//	public PrivateKey getPrivate2(String filename) throws Exception {
//		PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
//		JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
//		Object object = pemParser.readObject();
//		KeyPair kp = converter.getKeyPair((PEMKeyPair) object);
//		PrivateKey privateKey = kp.getPrivate();
//	}
	
	// public key로 암호화 
	public String encrypt(String str, PublicKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException{
		this.cipher.init(Cipher.ENCRYPT_MODE, key);
		return Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
	}
	
	// private key로 복호화 
	public String decrypt(String str, PrivateKey key) throws InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException{
		this.cipher.init(Cipher.DECRYPT_MODE, key);
		return new String(cipher.doFinal(Base64.decodeBase64(str)), "UTF-8");
	}

	/*
	  String hexString = "01020304FF11";
      byte[] ByteArray = hexStringToByteArray(hexString);
      String str = byteArrayToHexString(ByteArray);
      System.out.println(str);
	 */
	
	// hex to byte[]
	public byte[] hexStringToByteArray(String s) {
	    int len = s.length();
	    byte[] data = new byte[len / 2];
	    for (int i = 0; i < len; i += 2) {
	        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
	                             + Character.digit(s.charAt(i+1), 16));
	    }
	    return data;
	}
	
	// byte[] to hex
	public String byteArrayToHexString(byte[] bytes){ 
		StringBuilder sb = new StringBuilder(); 
		for(byte b : bytes){ 
			sb.append(String.format("%02X", b&0xff)); 
		} 
		return sb.toString(); 
	} 
    
	
	public static void main(String[] args) throws Exception {
		RSAEncryption ac = new RSAEncryption();
		
		// 공개키
		PublicKey publicKey = ac.getPublic("KeyPair/public.key");
		// 개인키 
		PrivateKey privateKey = ac.getPrivate("KeyPair/private.key");
		
		// 원문 
		String msg = "test message";
		
		
		System.out.println("----------------------------------------------------");
		System.out.println(":::: TEST 암호화 및 복호화 ::::");
		
		// 암호화 원문 BASE64
		String encryptedString = ac.encrypt(msg, publicKey);
		// 복호화
		String decryptedString = ac.decrypt(encryptedString, privateKey);
		
		System.out.println("----------------------------------------------------");
		System.out.println(
    			"원문 = " + msg + "\n" +
				"공개키 암호화 = " + encryptedString + "\n" +
				"개인키 복호화 = " + decryptedString
				);
		System.out.println("----------------------------------------------------");

	}
}

 

사용방법 :

Encode or decode byte arrays:

byte[] encoded = Base64.getEncoder().encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = Base64.getDecoder().decode(encoded);
println(new String(decoded))    // Outputs "Hello"
Or if you just want the strings:

String encoded = Base64.getEncoder().encodeToString("Hello".getBytes());
println(encoded);   // Outputs "SGVsbG8="

String decoded = new String(Base64.getDecoder().decode(encoded.getBytes()));
println(decoded)    // Outputs "Hello"


Base64 codec = new Base64();
byte[] encoded = codec.encode("Hello".getBytes());
println(new String(encoded));   // Outputs "SGVsbG8="

byte[] decoded = codec.decode(encoded);
println(new String(decoded))    // Outputs "Hello"


	

openssl rsa -text -in public.key -inform DER -pubin
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCH+bC/6rGV8I9NgqCUTpcUcUX
q15NC8N86kHtSPFl03dwwGIO3hPQVZyMiVwJYq8gz0ZFacf27tkvgphqJOAf/ckY
PKb52+8bEXNowbPhKqiwPaclEmtvm8MJplxZKa/Y+IhYitRRI7aVow841PRxC/nA
Z8AEiw5xkfBMsy9jdwIDAQAB
-----END PUBLIC KEY-----


openssl rsa -text -in private.key -inform DER
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCCH+bC/6rGV8I9NgqCUTpcUcUXq15NC8N86kHtSPFl03dwwGIO
3hPQVZyMiVwJYq8gz0ZFacf27tkvgphqJOAf/ckYPKb52+8bEXNowbPhKqiwPacl
Emtvm8MJplxZKa/Y+IhYitRRI7aVow841PRxC/nAZ8AEiw5xkfBMsy9jdwIDAQAB
AoGAGfdvvz3xwD7G/hwIoNTAxqdyozSJTuqoCgddPJKvyVgXn6Jkbv8WCR7sbIcE
nMLam7uBFFz1kGs9X+O5soTFTJHvyN1QyhvWODd2Gqqheh2fHqNunjegBJKnMVDS
ZCF+0HQe1SBub2D/WkPRMNb1O24v0FaR9LalaZAPqgM9eYECQQDpl+lSEddOsB7f
jX6QS9Z56s8St2Lql/HVlEsyZ3RZIHA+oGMuHaK124fo/CEQxH/SHouVCrjdgiR1
2rLbZY1hAkEAjps5Yw2SHb3AOUqG7x+FmVhb+DaMR+KZZpVlJvRxy4fQpoB2GdC4
Okf7idpQGZJHXeOI8sQbtS4GTFT7nwgH1wJBAKS2natlMTEnN13jZA9TqpSlYgaM
kY9iPQChZLTSBlSibwN6DPWDqCwb9KXww1ATfx4ms74QpXJsRlFkOSJDZYECQD4I
T6JC2PiO/frt7FxAPgFCal9CeysZ6tiwy9tyIb4DSkPjRXxdSoYvob+Jc6Zr9xdk
TsIrhFH/v0WdAgdfmukCQQCRnRh0nMw5GhjkP9pJTLZo4j8H/kp7lY0LDBLzo1cW
+nvyJ4Xg+Jgig5/lsn3QaIckocfnxcq10fGk+bFr67gM
-----END RSA PRIVATE KEY-----


UBpay RSA 암호화 결과 (위의 public key로 암호화)
원문 = test message
원문 HEXA = 74657374206D657373616765
암호화 원문 BASE64 = JLvhRkfskdQNcJ5mjMIy9hcCrfM1QDL5Qy/4tsnW8pG7QXvPrwmo7OxiTiC4FVBMw/Ae/NeLJCxY2jr9uRvKXFxqSrdrjBoO3QL+oFpKbldcvTRUzXCRsWzKzeM8v3FOclWgkZYZMzGq8PQQu3PgFKHCVMnX7//UE7aguHvLiJo=

반응형

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

20진수 변환  (0) 2021.09.16
root-level 디렉토리에 폴더, symbolic link 생성 방법  (0) 2021.03.15
RSA key 파일 생성  (0) 2021.02.05
용어 정리  (0) 2021.02.05
Korea Bank Codes  (0) 2021.02.05
블로그 이미지

SKY STORY

,