sitelink1 | |
---|---|
sitelink2 | |
sitelink3 | |
sitelink4 | |
extra_vars5 | |
extra_vars6 |
1. DES : 대칭 암호화 알고리즘, 암호화/복호화 키가 같음
2. RSA : 공개키 암호화방식 , 공개키(암호화키), 복소화키는 개인이 소장(비밀키)
3. 공개키 암호화 방식을 이용한 인증과 보안
2. RSA : 공개키 암호화방식 , 공개키(암호화키), 복소화키는 개인이 소장(비밀키)
3. 공개키 암호화 방식을 이용한 인증과 보안
1) A와 B는 각자 공개키/비밀키 쌍을 생성한다
2) A와 B는 각자의 공개키를 서로 주고받는다.
3) A는 B에게 전달할 문서를 B에게서 받은 공개키로 암호화한다.
4) B는 A에게서 암호화된 문서를 받고 저장해 두었던 비밀키로 복호화 한다.
5) B는 공개키를 A에게만 주었으므로, 복호화에 성공한다면 A가 문서를 보낸것이 확인된다.(인증)
6) B는 문서를 받앗으므로 A에게서 받은 공개키로 받았다는 답신을 암호화 해서 A에게 전송한다
7) A는 리턴받은 응답을 저장해 두엇던 B의 비밀키로 복호화한다.
8) 복호화가 되므로 B가 문서를 제대로 받았다는 것이 확인되었다. (부인방지)
4. 자바소스 예제 2) A와 B는 각자의 공개키를 서로 주고받는다.
3) A는 B에게 전달할 문서를 B에게서 받은 공개키로 암호화한다.
4) B는 A에게서 암호화된 문서를 받고 저장해 두었던 비밀키로 복호화 한다.
5) B는 공개키를 A에게만 주었으므로, 복호화에 성공한다면 A가 문서를 보낸것이 확인된다.(인증)
6) B는 문서를 받앗으므로 A에게서 받은 공개키로 받았다는 답신을 암호화 해서 A에게 전송한다
7) A는 리턴받은 응답을 저장해 두엇던 B의 비밀키로 복호화한다.
8) 복호화가 되므로 B가 문서를 제대로 받았다는 것이 확인되었다. (부인방지)
·미리보기 | 소스복사·
- import java.io.*;
- import java.math.*;
- import java.util.*;
- import java.security.*;
- import javax.crypto.*;
- import au.net.aba.crypto.provider.*;
- public class RSACrypt
- {
- public static final int KEY_LENGTH = 512;
- private static final int MSG_BLOCK_LENGTH = 53;
- private static final int ENCRYPTED_MSG_LENGTH = 64;
- // byte 배열로 전달받은 키를 문자열로 만든다.
- private static String makeStrKey(byte bytes[], int arraySize){
- StringBuffer bf = new StringBuffer();
- if (arraySize > 0){
- int noOfZero = arraySize - bytes.length;
- for (int i = 0; i < noOfZero; i++)
- bf.append("00");
- }
- for(int i=0; i<bytes.length; i++)
- {
- if((bytes[i] > 15) || (bytes[i] < 0))
- bf.append(java.lang.Integer.toHexString(bytes[i] & 0xff));
- else
- bf.append("0" + java.lang.Integer.toHexString(bytes[i] & 0xff));
- }
- return bf.toString();
- }
- private static byte[] int2byte(int[] src){
- byte[] dst = new byte[src.length];
- for (int i = 0; i < src.length; i++)
- dst[i] = (byte)src[i];
- return dst;
- }
- private static int [] str2int(String src, int arraySize)
- {
- int[] dst;
- if (arraySize > 0){
- dst = new int[arraySize];
- int noOfZero = arraySize - (src.length() / 2);
- for (int i = 0; i < noOfZero; i++) dst[i] = 0x00;
- for (int i = noOfZero; i < dst.length; i++){
- char first = src.charAt(i * 2);
- char second = src.charAt(i * 2 + 1);
- dst[i] = hex2int(first) * 16 + hex2int(second);
- }
- }
- else{
- dst = new int[src.length() / 2];
- for (int i = 0; i < dst.length; i++){
- char first = src.charAt(i * 2);
- char second = src.charAt(i * 2 + 1);
- dst[i] = hex2int(first) * 16 + hex2int(second);
- }
- }
- return dst;
- }
- private static int hex2int(char src)
- {
- if(src >= '0' && src <= '9') return ((int)src - (int)'0');
- else if(src >= 'a' && src <= 'f') return ((int)src - (int)'a' + 10);
- else if(src >= 'A' && src <= 'F') return ((int)src - (int)'A' + 10);
- else throw new NumberFormatException();
- }
- // Random 한 키쌍을 생성한다
- // 키생성에는 시간이 오래걸리므로, Key Pool을 향후 Key Pool을 만들어야 한다.
- public static KeyPair getRandomKeyPair(int keyLength) throws Exception{
- SecureRandom rand = new SecureRandom();
- rand.nextInt();
- KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
- kpg.initialize(keyLength, rand);
- KeyPair kp = kpg.generateKeyPair();
- return kp;
- }
- // 공개키는 원격지에 전송해 주어야 하므로 스트링 형태로 만드는 것이 필요하다.
- public static String getPubKeyStr(PublicKey pubKey)
- {
- StringBuffer bf = new StringBuffer();
- byte[] tempPubKeyArray = pubKey.getEncoded();
- RSAPubKey rsaPubKey = new RSAPubKey(tempPubKeyArray);
- bf.append(makeStrKey(rsaPubKey.getModulus().toByteArray(), 128));
- bf.append(" ");
- bf.append(makeStrKey(rsaPubKey.getPublicExponent().toByteArray(), 128));
- return bf.toString();
- }
- // 상대방 에게서 전달받은 스트링 형태의 공개키를 공개키 객체로 만들어 주는 함수
- public static PublicKey getPubKey(String hexPubKey)
- {
- StringTokenizer tk = new StringTokenizer(hexPubKey, " ");
- System.out.println(tk.countTokens());
- String strPubModulus = tk.nextToken();
- String strPubExponent = tk.nextToken();
- int[] intArrayPubModulus = str2int(strPubModulus, 128);
- int[] intArrayPubExponent = str2int(strPubExponent, 128);
- byte[] byteArrayPubModulus = int2byte(intArrayPubModulus);
- byte[] byteArrayPubExponent = int2byte(intArrayPubExponent);
- BigInteger bigIntPubModulus = new BigInteger(byteArrayPubModulus);
- BigInteger bigIntPubExponent = new BigInteger(byteArrayPubExponent);
- return new RSAPubKey(bigIntPubModulus, bigIntPubExponent);
- }
- // 문자열과 공개키를 전달받아 암호화를 수행한다.
- public static String encode(String msg, PublicKey rsaPubKey) throws Exception
- {
- int MSG_BLOCK_LENGTH = 53;
- byte[] msgArray = msg.getBytes();
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.ENCRYPT_MODE, rsaPubKey);
- Vector arrayList = new Vector();
- int totalSize = 0;
- for (int i = 0; i < msgArray.length; i += MSG_BLOCK_LENGTH){
- int size = Math.min(MSG_BLOCK_LENGTH, msgArray.length - i);
- byte[] temp = new byte[size];
- System.arraycopy(msgArray, i, temp, 0, size);
- byte[] encedMsg = cipher.doFinal(temp);
- arrayList.addElement(encedMsg);
- totalSize += encedMsg.length;
- }
- byte[] totalArray = new byte[totalSize];
- int offset = 0;
- for (int i = 0; i < arrayList.size(); i++){
- byte[] tempArray = (byte[])arrayList.elementAt(i);
- System.arraycopy(tempArray, 0, totalArray, offset, tempArray.length);
- offset += tempArray.length;
- }
- return makeStrKey(totalArray, -1);
- }
- // 저장된 비밀키를 사용해서 공개키로 암호화된 문자열을 복호화 한다.
- public static String decode(String msg, PrivateKey rsaPrvKey) throws Exception
- {
- int[] intArray = str2int(msg, -1);
- byte[] msgArray = int2byte(intArray);
- Cipher cipher = Cipher.getInstance("RSA");
- cipher.init(Cipher.DECRYPT_MODE, rsaPrvKey);
- Vector arrayList = new Vector();
- int totalSize = 0;
- for (int i = 0; i < msgArray.length; i += ENCRYPTED_MSG_LENGTH)
- {
- byte[] temp = new byte[ENCRYPTED_MSG_LENGTH];
- System.arraycopy(msgArray, i, temp, 0, ENCRYPTED_MSG_LENGTH);
- byte[] decedMsg = cipher.doFinal(temp);
- arrayList.addElement(decedMsg);
- totalSize += decedMsg.length;
- }
- byte[] totalArray = new byte[totalSize];
- int offset = 0;
- for (int i = 0; i < arrayList.size(); i++)
- {
- byte[] tempArray = (byte[])arrayList.elementAt(i);
- System.arraycopy(tempArray, 0, totalArray, offset, tempArray.length);
- offset += tempArray.length;
- }
- return new String(totalArray);
- }
- // 사용예제
- public static void main(String [] args)
- {
- try{
- // Privider Setting
- Security.insertProviderAt(new ABAProvider(), 2);
- // 키쌍을 생성
- KeyPair keyPair = RSACrypt.getRandomKeyPair(512);
- // 공개키와 비밀키를 얻어옴
- PrivateKey privateKey = (PrivateKey) keyPair.getPrivate();
- PublicKey publicKey = (PublicKey ) keyPair.getPublic();
- // 공개키 출력
- System.out.println("> 생성된 공개키 String : "+RSACrypt.getPubKeyStr(publicKey));
- String encResult = RSACrypt.encode("암호화 할 문자열", publicKey);
- System.out.println("> 공개키로 암호화된 문자열 : "+encResult);
- String decResult = RSACrypt.decode(encResult, privateKey);
- System.out.println("> 비밀키로 복호화된 문자열 : "+decResult);
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
댓글 0
번호 | 제목 | sitelink1 | 글쓴이 | 날짜 | 조회 수 |
---|---|---|---|---|---|
공지 | [계속 추가중] SBOM 용어 정의 | 황제낙엽 | 2025.04.10 | 52 | |
공지 | [계속 추가중] Keycloak 용어 및 설정 옵션 정의 | 황제낙엽 | 2024.02.02 | 631 | |
5 |
RSA 암호화 프로그램 예제 (BigInteger 이용)
![]() | 황제낙엽 | 2007.09.08 | 257 | |
4 | 해쉬를 이용한 패스워드 로그인 | 황제낙엽 | 2007.09.05 | 111 | |
3 |
Java 보안과 암호화 (개론)
![]() | 황제낙엽 | 2007.09.05 | 117 | |
» | RSA 공개키 암호화 방식 (java.security, javax.crypto, au.net.aba.crypto.provider 패키지 이용) | 황제낙엽 | 2007.09.05 | 279 | |
1 | 자바 암호화 기법 - MD5를 이용한 해쉬키 생성 (Hash) | 황제낙엽 | 2007.09.01 | 316 |