'PrivateKey'에 해당되는 글 2건

반응형

rsa공개키 생성후 파일로 전달하므로 파일을 변환하여 공개/개인 키 구하는 방법을 알아보자.

 

openssl rsa -text -in public.key -inform DER -pubin

(base) netcanis@netcanis-MacBook-Pro KeyPair % openssl rsa -text -in public.key -inform DER -pubin
RSA Public-Key: (1024 bit)
Modulus:
    00:9f:41:52:c2:d0:82:17:18:29:6e:17:3a:ac:a2:
    1a:8c:de:17:5c:89:c1:15:18:78:90:88:53:03:92:
    7e:36:ab:83:26:7d:f5:4b:37:8e:2e:d9:f3:d9:7e:
    e1:b9:0b:fd:99:c9:f4:67:06:c0:df:9f:29:51:2f:
    2b:40:0b:9d:32:4c:47:38:02:f7:6c:d9:d1:72:b1:
    cb:f1:11:90:18:ca:28:dc:00:e3:f8:ce:a9:f9:b7:
    5b:d1:62:ae:5b:06:f8:b2:40:93:bb:31:c1:3a:63:
    76:82:65:11:76:67:db:8a:5d:76:2b:b0:42:ed:31:
    24:a1:76:4b:cb:53:ed:a8:7b
Exponent: 65537 (0x10001)
writing RSA key
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfQVLC0IIXGCluFzqsohqM3hdc
icEVGHiQiFMDkn42q4MmffVLN44u2fPZfuG5C/2ZyfRnBsDfnylRLytAC50yTEc4
Avds2dFyscvxEZAYyijcAOP4zqn5t1vRYq5bBviyQJO7McE6Y3aCZRF2Z9uKXXYr
sELtMSShdkvLU+2oewIDAQAB
-----END PUBLIC KEY-----

 

openssl rsa -text -in private.key -inform DER

(base) netcanis@netcanis-MacBook-Pro KeyPair % openssl rsa -text -in private.key -inform DER
RSA Private-Key: (1024 bit, 2 primes)
modulus:
    00:9f:41:52:c2:d0:82:17:18:29:6e:17:3a:ac:a2:
    1a:8c:de:17:5c:89:c1:15:18:78:90:88:53:03:92:
    7e:36:ab:83:26:7d:f5:4b:37:8e:2e:d9:f3:d9:7e:
    e1:b9:0b:fd:99:c9:f4:67:06:c0:df:9f:29:51:2f:
    2b:40:0b:9d:32:4c:47:38:02:f7:6c:d9:d1:72:b1:
    cb:f1:11:90:18:ca:28:dc:00:e3:f8:ce:a9:f9:b7:
    5b:d1:62:ae:5b:06:f8:b2:40:93:bb:31:c1:3a:63:
    76:82:65:11:76:67:db:8a:5d:76:2b:b0:42:ed:31:
    24:a1:76:4b:cb:53:ed:a8:7b
publicExponent: 65537 (0x10001)
privateExponent:
    25:ca:9a:99:20:61:be:99:3d:3b:a2:c7:89:af:ee:
    1c:ff:97:0b:9e:a4:f3:1c:9b:7f:b0:da:02:3f:01:
    34:77:fe:e7:63:7c:92:1c:dc:e0:c1:57:dc:84:ff:
    8b:aa:0c:c4:31:e8:8d:8a:4c:ba:c4:4a:49:b9:a7:
    c9:ca:f7:c2:57:38:df:0a:95:27:da:42:66:b0:55:
    03:75:61:53:42:57:f6:8d:f5:d5:0c:f4:81:a9:6c:
    ae:37:9f:e1:39:02:69:11:ec:55:67:31:08:0b:b8:
    66:aa:19:6c:e5:f0:87:5a:16:c5:12:98:71:df:84:
    6c:e0:1a:ac:9b:b6:96:01
prime1:
    00:e5:8c:be:c1:67:56:95:fa:6b:39:8e:43:12:5b:
    fd:e1:e6:2f:86:cb:12:87:df:6d:19:d3:a7:a9:6c:
    70:c5:6f:11:92:4a:e8:ee:d1:70:0c:5d:82:ca:6c:
    03:e6:2a:7d:ce:49:9b:fd:39:3b:71:4a:9f:75:89:
    18:a9:95:23:4d
prime2:
    00:b1:9b:07:6b:e5:a4:c2:9e:1f:eb:24:98:c1:7e:
    c2:e1:3a:5c:d7:20:c0:4e:02:24:e1:3f:15:1c:0d:
    e2:78:c9:54:7e:86:54:92:e5:88:05:f8:90:6b:3c:
    c5:be:4f:61:b7:c3:c0:88:69:7d:34:f3:16:78:bc:
    2a:ec:23:06:e7
exponent1:
    00:b4:ff:2c:2d:dd:68:85:6b:65:fe:84:f0:d7:da:
    17:2e:76:cc:c4:b0:fc:94:8c:14:3f:88:07:2c:6c:
    e7:e2:95:38:3a:ac:bc:4c:0a:72:1a:1d:e5:91:ec:
    67:8a:a5:b8:7a:de:c9:93:79:fc:27:d1:5a:38:57:
    f8:4d:46:de:05
exponent2:
    00:aa:75:94:a5:e5:fe:40:1b:eb:9e:8f:bd:5c:d9:
    00:c9:92:6e:50:bb:4a:56:94:90:38:ef:86:9f:2a:
    64:56:71:44:fb:3a:8a:29:82:cb:0e:90:06:6c:26:
    23:d4:07:f4:4d:9f:3f:46:ad:98:52:1d:8d:4f:cb:
    a9:96:81:f7:b9
coefficient:
    0a:6e:ee:7a:01:58:9b:40:32:e0:d1:d7:d3:a1:45:
    c2:3b:60:9b:84:41:26:7d:01:bf:ec:db:bb:c9:5e:
    57:34:ef:e1:62:9b:a5:0b:b2:21:88:63:07:e5:ab:
    1d:9e:cf:f4:83:ed:5f:0c:78:6a:62:34:e8:51:f8:
    85:13:d3:7c
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQCfQVLC0IIXGCluFzqsohqM3hdcicEVGHiQiFMDkn42q4MmffVL
N44u2fPZfuG5C/2ZyfRnBsDfnylRLytAC50yTEc4Avds2dFyscvxEZAYyijcAOP4
zqn5t1vRYq5bBviyQJO7McE6Y3aCZRF2Z9uKXXYrsELtMSShdkvLU+2oewIDAQAB
AoGAJcqamSBhvpk9O6LHia/uHP+XC56k8xybf7DaAj8BNHf+52N8khzc4MFX3IT/
i6oMxDHojYpMusRKSbmnycr3wlc43wqVJ9pCZrBVA3VhU0JX9o311Qz0galsrjef
4TkCaRHsVWcxCAu4ZqoZbOXwh1oWxRKYcd+EbOAarJu2lgECQQDljL7BZ1aV+ms5
jkMSW/3h5i+GyxKH320Z06epbHDFbxGSSuju0XAMXYLKbAPmKn3OSZv9OTtxSp91
iRiplSNNAkEAsZsHa+Wkwp4f6ySYwX7C4Tpc1yDATgIk4T8VHA3ieMlUfoZUkuWI
BfiQazzFvk9ht8PAiGl9NPMWeLwq7CMG5wJBALT/LC3daIVrZf6E8NfaFy52zMSw
/JSMFD+IByxs5+KVODqsvEwKchod5ZHsZ4qluHreyZN5/CfRWjhX+E1G3gUCQQCq
dZSl5f5AG+uej71c2QDJkm5Qu0pWlJA474afKmRWcUT7OoopgssOkAZsJiPUB/RN
nz9GrZhSHY1Py6mWgfe5AkAKbu56AVibQDLg0dfToUXCO2CbhEEmfQG/7Nu7yV5X
NO/hYpulC7IhiGMH5asdns/0g+1fDHhqYjToUfiFE9N8
-----END RSA PRIVATE KEY-----

 

2020/12/17 - [Android/Java] - RSA 암복호화

2020/12/17 - [iOS/Tips] - URL query 파싱 및 json string 변환

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 경고 무시하기

반응형
블로그 이미지

SKY STORY

,

RSA 암복호화

개발/Note 2020. 12. 17. 16:18
반응형

결제 관련 API 연동(VAN, PG, 간편결제 등) 할 경우 RSA암복호화 과정을 거치게되는데

이 부분에 대한 샘플 코드를 작성해 보았다.

 

Apache Commons Codec 다운로드

commons.apache.org/proper/commons-codec/

 

Codec – Home

Apache Commons Codec Apache Commons Codec (TM) software provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs. Impetus Codec was formed as an attempt to focus development effort on one definitive implementation of

commons.apache.org

 

프로젝트 라이브러리에 추가. 

 

PublicKey와 PrivateKey 파일을 생성

package com.ubpay.keypair;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;

//
// RSA Key 파일 생성
//
// Created by netcanis on 2019/04/29.
// Copyright © 2019 netcanis. All rights reserved.
//

// Download Apache Commons Codec
// https://commons.apache.org/proper/commons-codec/download_codec.cgi

public class GenKeys
{
	private KeyPairGenerator keyGen;
	private KeyPair pair;
	private PrivateKey privateKey;
	private PublicKey publicKey;

	// RSA 초기화 및 키 생성 
	public GenKeys(int keysize) throws NoSuchAlgorithmException, NoSuchProviderException {
		this.keyGen = KeyPairGenerator.getInstance("RSA");
		this.keyGen.initialize(keysize);
		this.pair = this.keyGen.generateKeyPair();
		this.publicKey = pair.getPublic();
		this.privateKey = pair.getPrivate();
	}

	public PublicKey getPublicKey() {
		return this.publicKey;
	}
	
	public PrivateKey getPrivateKey() {
		return this.privateKey;
	}
	
	public void writeToFile(String path, byte[] key) throws IOException {
		File f = new File(path);
		f.getParentFile().mkdirs();

		FileOutputStream fos = new FileOutputStream(f);
		fos.write(key);
		fos.flush();
		fos.close();
	}

	
	
	public static void main(String[] args) {
		GenKeys genKeys;
		try {
			// 1024bit key pair 생성  
			genKeys = new GenKeys(1024);
			
			System.out.println(genKeys.publicKey);
			System.out.println(genKeys.privateKey);
			
			// 바이너리 파일로 저장 
			genKeys.writeToFile("KeyPair/public.key", genKeys.getPublicKey().getEncoded());
			genKeys.writeToFile("KeyPair/private.key", genKeys.getPrivateKey().getEncoded());
			
		} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
			System.err.println(e.getMessage());
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}

 

생성 결과

 

생성된 키를 이용하여 암복호화 테스트

package com.ubpay.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);
	}
	
	// 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");
	}

	// 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("----------------------------------------------------");
	}
}




결과 :
--------------------------------------------------------------------------
:::: TEST 암호화 및 복호화 ::::
--------------------------------------------------------------------------
원문 = test message
공개키 암호화 = gz2WQHCyHxsPV5IB0xehk8RSbGrhGR86nQRGj09CphxiIAjRsCony8myWfRGJgDVyK6ixuK13gtL/20j4K5c1GcCKxPT9xqYaa6tBxTakho9klHNAO6KhQJK0nGeIQRDpZ1qecB6pPMsRqVVO5rb81NFqbjLKMoqi2tO1f55/iM=
개인키 복호화 = test message
--------------------------------------------------------------------------

 

2020/12/17 - [OS/Mac OS X] - OpenSSL을 이용한 Key 정보 Text 변환

2020/12/17 - [iOS/Tips] - URL query 파싱 및 json string 변환

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

 

반응형
블로그 이미지

SKY STORY

,