공개키 암호화 [RSA구현]

Posted by 백창
2015. 1. 16. 15:33 컴퓨터보안/Programming
반응형


 개념


 공개키 알고리즘은 암호화하는 키와 해독하는 키가 동일하지 않도록(혹은 하나로 다른 하나를 유추할 수 없도록) 고안된 방식이다. 공개키 알고리즘을 이용하면, 암호문을 작성할 때 사용하는 암호키가 외부에 공개되어도 비밀키를 모르면 암호문을 해독할 수 없다.


 공개키 알고리즘에서는 사용자가 두 개의 암호키(공개키와 비밀키)를 사용하는데, 공개키는 원문서를 암호화하는 데 사용하므로 원칙적으로 누구에게나 공개된다. 따라서 송신 호스트는 공개키로 원문서를 암호화하여 전송한다. 수신 호스트에서는 암호문을 해독하기 위해 비밀키를 사용한다.


 공개키 알고리즘의 대표 예는 RSA 알고리즘이 있다.



그림출처 : 네이버 지식백과



 RSA 구현


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
 
import javax.crypto.Cipher;
 
public class RSA {
    //RSA
    private PublicKey publicKey;
    private PrivateKey privateKey;
    
    /**
     * 키 쌍 생성
     * */
    public KeyPair keyGen(){
        KeyPair keyPair = null;
        
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
            keyPair = keyPairGen.generateKeyPair();
            
            publicKey = keyPair.getPublic();
            privateKey= keyPair.getPrivate();
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
        return keyPair;
    }
    
    public PublicKey getPublic(){
        return publicKey;
    }
    public PrivateKey getPrivate(){
        return privateKey;
    }
    
    /**
     * 암호화
     * */
    public byte[] encryptRSA(byte[] input, PublicKey publicKey)throws Exception{
        byte[] encrypted = null;
        
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            encrypted = cipher.doFinal(input);
            
        } catch(Exception e){
            e.printStackTrace();
        }
        
        return encrypted;
    }
    /**
     * 암호화
     * */
    public byte[] encryptRSA(byte[] input, PrivateKey privateKey)throws Exception{
        byte[] encrypted = null;
        
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            encrypted = cipher.doFinal(input);
            
        } catch(Exception e){
            e.printStackTrace();
        }
        
        return encrypted;
    }
    
    /**
     * 복호화
     * */
    public byte[] decryptRSA(byte[] input, PrivateKey privateKey) throws Exception{
        byte[] decrypted = null;
        try{
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            decrypted = cipher.doFinal(input);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return decrypted;
    }
    
    /**
     * 복호화
     * */
    public byte[] decryptRSA(byte[] input, PublicKey publicKey) throws Exception{
        byte[] decrypted = null;
        try{
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            decrypted = cipher.doFinal(input);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        return decrypted;
    }
    
}
 
 
cs


반응형

'컴퓨터보안 > Programming' 카테고리의 다른 글

대칭키 암호화  (0) 2014.12.27
DES 암호화 과정(java)  (0) 2014.10.20

FTP - Client 만들기

Posted by 백창
2014. 11. 28. 15:52 개발/Java
반응형


 개요


 JAVA로 간단한 FTP 클라이언트를 만들어보자



 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
 
public class Client {
 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String IP = "127.0.0.1";
        Socket socket = null;
        
        try{
            socket = new Socket(IP, 8521);
            System.out.println("서버와 연결");
            
            FileSender fs = new FileSender(socket);
            fs.start();
            
        }catch(IOException e){
            e.printStackTrace();
        }
    }
 
}
 
class FileSender extends Thread{
    Socket socket;
    DataOutputStream dos;
    FileInputStream fis;
    BufferedInputStream bis;
        
    public FileSender(Socket socket){
        this.socket = socket;
        try{
            //데이터 전송용 스트림 생성
            dos = new DataOutputStream(socket.getOutputStream());
        }catch(IOException e){
            e.printStackTrace();
        }
        
        
    }
    @Override
    public void run(){
        try{
            //String fileName = "test.txt";
            String fileName = "test.png";
 
            
            dos.writeUTF(fileName);
            
            File f =new File(fileName);
            fis = new FileInputStream(f);
            bis = new BufferedInputStream(fis);
            
            int len;
            int size = 4096;
            byte[] data = new byte[size];
            while((len = bis.read(data))!=-1){
                
                dos.write(data,0,len);
            }
            
            dos.flush();
            dos.close();
            bis.close();
            fis.close();
            
        }catch(IOException e){
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


반응형

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

FTP - server 만들기  (0) 2014.11.28
csv파일 읽기  (0) 2014.09.27
JDOM을 이용한 XML 생성  (0) 2014.09.14
JDOM을 이용한 XML 파싱  (0) 2014.09.14
현재 시간 구하기  (0) 2014.09.14

FTP - server 만들기

Posted by 백창
2014. 11. 28. 15:49 개발/Java
반응형


 개요


 JAVA로 간단한 FTP 서버를 만들어보자.


 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
 
 
public class Server {
 
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        
        try{
            //리스너 소켓 생성 후 대기
            serverSocket = new ServerSocket(8521);
            System.out.println("#####    서버실행    #####");
            
            //클라이언트와 연결 완료
            socket = serverSocket.accept();
            System.out.println("#####    연결완료    #####");
            
            //수신시작
            FileReceiver fr = new FileReceiver(socket);
            fr.start();
            
        }catch(IOException e){
            e.printStackTrace();
        }
 
    }
 
}
 
class FileReceiver extends Thread{
    Socket socket;
    DataInputStream dis;
    FileOutputStream fos;
    BufferedOutputStream bos;
        
    String filePath = "D:\\ForSecurity\\data\\";
    
    public FileReceiver(Socket socket){
        this.socket = socket;
    }
    
    @Override
    public void run(){
        try{
            System.out.println("#####    수신시작    #####");
            dis = new DataInputStream(socket.getInputStream());
            
            //파일명 수신
            String fName = dis.readUTF();
            System.out.println("#    파일명 : "+fName);
            
            //파일 생성
            File f = new File(filePath+fName);
            fos = new FileOutputStream(f);
            bos = new BufferedOutputStream(fos);
            System.out.println("#    "+fName+" 파일을 생성");
            
            //파일 쓰기
            int len;
            int size=4096;
            byte[] data = new byte[size];
            while((len = dis.read(data))!=-1){
                bos.write(data,0,len);
            }
            
            
            bos.flush();
            bos.close();
            fos.close();
            dis.close();
            
            System.out.println("#    전송완료 사이즈 : "+f.length());
            
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
 










반응형

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

FTP - Client 만들기  (0) 2014.11.28
csv파일 읽기  (0) 2014.09.27
JDOM을 이용한 XML 생성  (0) 2014.09.14
JDOM을 이용한 XML 파싱  (0) 2014.09.14
현재 시간 구하기  (0) 2014.09.14

spring Framework 파일 업로드

Posted by 백창
2014. 9. 29. 13:54 개발/Spring
반응형


 개요


 Spring에서 파일 업로드를 처리해보자



 설정


servlet_context.xml 파일 설정


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- 파일저장 -->
    <bean id="uploadPathResource" class="org.springframework.core.io.FileSystemResource">
        <constructor-arg>
            <value>D:\R\work\demo\file\</value>
        </constructor-arg>
    </bean>
    
    <!-- Upload File Size Definition -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
        <!-- 파일 업로드 최대 용량 단위 byte -->
            <value>10485677</value>
        </property>
    </bean>




 소스


UploadItem.java 파일


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.nara.comm;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
 
public class UploadItem
{
  private CommonsMultipartFile fileData;
  private String name;
  
  public String getName(){
      return name;
  }
  
  public void setName(String name){
      this.name = name;
  }
  
  public CommonsMultipartFile getFileData()
  {
    return fileData;
  }
 
  public void setFileData(CommonsMultipartFile fileData)
  {
    this.fileData = fileData;
  }
}


Controller 파일


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 
import org.springframework.core.io.FileSystemResource;
import org.springframework.validation.BindingResult;
import com.nara.demo.UploadItem;
 
@Inject private FileSystemResource uploadFilePath;
 
public void getFileName(@RequestParam Map<String, Object> paramMap, ModelMap model,UploadItem uploadItem, BindingResult result) throws Throwable{
        
        String getFileName = "";
        
        date = dateFormat.format(System.currentTimeMillis());
        
        if (result.hasErrors()){
            for(ObjectError error : result.getAllErrors()){
                System.err.println("Error: " + error.getCode() +  " - " + error.getDefaultMessage());
            }
        }
 
        if(!uploadItem.getFileData().isEmpty()){
            
            fileName = date+"_"+uploadItem.getFileData().getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
            
            //upload 가능한 파일 타입 지정
            if(fileExt.equalsIgnoreCase("csv")){
                byte[] bytes = uploadItem.getFileData().getBytes();
                try{
                    File lOutFile = new File(uploadFilePath.getPath()+fileName);
                    FileOutputStream lFileOutputStream = new FileOutputStream(lOutFile);
                    lFileOutputStream.write(bytes);
                    lFileOutputStream.close();
                }catch(IOException ie){
                    //Exception 처리
                    System.err.println("File writing error! ");
                }
                System.err.println("File upload success! ");
            }else{
                System.err.println("File type error! ");
            }
            model.put("fileName",fileName);
        }
 
        // Some type of file processing...
        System.err.println("upload path : " + uploadFilePath.getPath());
        System.err.println("upload fileName: " + fileName);
}




view 부분


1
2
3
4
5
6
7
8
9
10
11
12
            <form name="aform" method="post" enctype="multipart/form-data">
            <table width="231" border="0" cellpadding="0" cellspacing="0">
                Choose the File<br>
                <input type="file" id="fileData" name="fileData"  /><br><br>
    <!--             onchange="javascrpit:document.getElementById('fileName').value = this.value" -->
<!--                 <input type="button" id="searchFile" name="searchFile" value="파일 찾기" /> -->
                <input type="button" value="show" onclick="fnShow()" />
                
                
            </table>
            
        </form>



 Form 으로 감싸는 부분에서 enctype="multipart/form-data" 를 추가해야 파일 데이터가 Post방식으로 전송 된다.


 결과


파일 업로드


파일 업로드 목록



반응형

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

[myBatis] selectKey 사용  (0) 2014.09.03

csv파일 읽기

Posted by 백창
2014. 9. 27. 12:08 개발/Java
반응형


 개요


다음 소스는 필요에 따라 csv 파일의 헤더만 읽기위해 사용되었다.

 csv파일 전체를 읽기위해서는 



위 소스 부분을 다음과 같이 바꾸어야 한다.




 소스


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
 
 
public class readFile {
    
    /**
     * Header 받아오기
     * */
    @SuppressWarnings("null")
    public ArrayList<String> readHeader(String filePath) throws IOException{
 
        ArrayList<String> ret = new ArrayList<String>();
        File csv = new File(filePath);
        BufferedReader br = new BufferedReader(new FileReader(csv));
        
        String line = "";
        line = br.readLine();
        
        String[] token = line.split(",");
        
        for(String output:token){
            System.out.println(output);
            ret.add(output);
        }
        
        br.close();
        
        return ret;
    }
    
    /**
     * \을 /으로 변환
     * */
    public String convertDash(String fileName){
        String convertFileName="";
        
        convertFileName = fileName.replace('\\','/');
        return convertFileName;
    }
}




 결과



반응형

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

FTP - Client 만들기  (0) 2014.11.28
FTP - server 만들기  (0) 2014.11.28
JDOM을 이용한 XML 생성  (0) 2014.09.14
JDOM을 이용한 XML 파싱  (0) 2014.09.14
현재 시간 구하기  (0) 2014.09.14

[eclipse 오류]PermGen space

Posted by 백창
2014. 9. 23. 20:49 개발/Android
반응형


 오류내용




Exception in checkAndLoadTargetData


PermGen space


라는 오류가 발생하였다. (원인은 잘 모르겠지만 원격제어 때문인듯)




 해결방법


eclipse 폴더에 eclipse.in파일을 열고 다음과 같이 수정해준다.



저장하고 eclipse를 다시 실행하면 오류 해결

반응형

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

지니모션 설치  (0) 2014.09.14
AVD 작성  (0) 2014.09.13
Android 설치  (0) 2014.09.13

JDOM을 이용한 XML 생성

Posted by 백창
2014. 9. 14. 22:41 개발/Java
반응형


 목적


 이전 포스팅에서 출력한 XML 파일에 새로운 정보를 더해 재조립해서 xml형식으로 저장한다.



 Source


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.springframework.ui.ModelMap;
 
public class xmlTest {
    public void testAddName(ModelMap model , String name) throws JDOMException, IOException{
        
        //파일경로
        String filePath="xmlTest.xml";
        String newFilePath = "madeXmlTest.xml";
        
        File file = new File(filePath);
        
        FileInputStream input = new FileInputStream(file);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(input);
        
        //Root Element
        Element xmlRoot = doc.getRootElement();
        
        //Child Element
        List l_list = xmlRoot.getChildren();
        Element basic = (Element) l_list.get(0);
        
        //New Element
        Element addName = new Element("name");
        addName.setText(name);
        
        //Added Child Element
        basic.addContent(addName);
        
        //FILE IO
        FileWriter writer = new FileWriter(newFilePath);
        
        XMLOutputter outputter = new XMLOutputter();
        try{
            outputter.setFormat(Format.getPrettyFormat());  //개행 등 을 처리
            
            /**
             * 한글 변환! 중요
             * */
            Format fm = outputter.getFormat();
            fm.setEncoding("EUC-KR");
            outputter.setFormat(fm);
            
            outputter.output(doc, writer);
            
            writer.close();
        }catch(Exception e){
            System.err.println(e);
        }
        
    }
}


 Test


이전 XML 파일



새로 생성된 XML 파일



name이라는 부분이 새로 생성되었다.



 힘들었던 부분


XML을 생성하는 경우 인코딩에서 문제가 발생하였다. 


UTF-8 방식으로 저장되는데 한글이 깨져서 출력되는 문제가 발생하여 다음과 같이 해결하였다.



반응형

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

FTP - Client 만들기  (0) 2014.11.28
FTP - server 만들기  (0) 2014.11.28
csv파일 읽기  (0) 2014.09.27
JDOM을 이용한 XML 파싱  (0) 2014.09.14
현재 시간 구하기  (0) 2014.09.14

JDOM을 이용한 XML 파싱

Posted by 백창
2014. 9. 14. 22:31 개발/Java
반응형


 JDOM이란?


 자바에서 제공하는 XML 데이터를 가공하기 위해 제공되는 라이브러리 이다. SAX(Simple API for XML)과 DOM의 장점만을 골라 만든 클래스와 인터페이스를 제공한다.



 Source


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
 
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.springframework.ui.ModelMap;
 
public class xmlTest {
    public void test(ModelMap model) throws JDOMException, IOException {
        
        //파일 경로
        String filePath="xmlTest.xml";
        
        File file = new File(filePath);
        
        FileInputStream input = new FileInputStream(file);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(input);
        
        //Root Element
        Element xmlRoot = doc.getRootElement();
        
        //Child Element
        List l_list = xmlRoot.getChildren();
        Element e_list = (Element) l_list.get(0);
        
        List l_basic = e_list.getChildren();
        
        //Output
        for(int i=0; i<l_basic.size(); i++) {
            Element e_basic = (Element) l_basic.get(i);
            System.out.println("e_basic.getName() : "+e_basic.getName());
            System.out.println("e_basic.getText() : "+e_basic.getText());
            
            model.put(e_basic.getName(), e_basic.getText());
        }
    }
}



 출력할 XML File





 Test




반응형

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

FTP - Client 만들기  (0) 2014.11.28
FTP - server 만들기  (0) 2014.11.28
csv파일 읽기  (0) 2014.09.27
JDOM을 이용한 XML 생성  (0) 2014.09.14
현재 시간 구하기  (0) 2014.09.14

현재 시간 구하기

Posted by 백창
2014. 9. 14. 22:19 개발/Java
반응형


 개요


 Java에서 현재 시간을 구해보자.


 Method


시간을 구하는 method 는 


 System.currentTimeMillis();


이다.


위 method의 리턴형은 long 형이고 1/1000 초 값을 리턴한다. (1970년 1월 1일 부터 계산)



 Source





 Test



반응형

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

FTP - Client 만들기  (0) 2014.11.28
FTP - server 만들기  (0) 2014.11.28
csv파일 읽기  (0) 2014.09.27
JDOM을 이용한 XML 생성  (0) 2014.09.14
JDOM을 이용한 XML 파싱  (0) 2014.09.14

[myBatis] selectKey 사용

Posted by 백창
2014. 9. 3. 09:52 개발/Spring
반응형


 개요


selectKey의 사용법에 대해 알아보자


 동적 sql SelectKey


 insert 시 조건에 따라 다른 값을 넣고자 하면 selectKey를 이용하여 전달된 자바 빈 또는 map에 원하는 값을 지정할 수 있다.



 keyProperty 이 id로 value 값에 #{id} 형식으로 사용한다.


 주의사항


1. insert 문에서만 사용이 가능하다.

2. insert문 한 개에 한 개의 selectKey만 사용이 가능하다.

반응형

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

spring Framework 파일 업로드  (0) 2014.09.29