참고 : http://blog.naver.com/PostView.nhn?blogId=ugigi&logNo=70058661623
         http://blog.naver.com/xxrcn11/20135603375
         http://blog.daum.net/wetet/1813

CryptTest.java

 package iwa.crypt;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;

public class CryptTest {

 public static final int bufSize = 1024;

 // 파일 암호화

 public void encryptFile(String in, String out) throws Exception {
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("PublicKey.ser"));
  PublicKey publicKey = (PublicKey) ois.readObject();
  ois.close();
  cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  FileInputStream fis = new FileInputStream(in);
  FileOutputStream fos = new FileOutputStream(out);
  CipherOutputStream cos = new CipherOutputStream(fos, cipher);
  byte[] buffer = new byte[bufSize];
  int length;
  while ((length = fis.read(buffer)) != -1)
   cos.write(buffer, 0, length);
  fis.close();
  fos.close();
 }

 // 파일 복호화
 public void decryptFile(String in, String out) throws Exception {
  Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
  ObjectInputStream ois = new ObjectInputStream(new FileInputStream("PrivateKey.ser"));
  PrivateKey privateKey = (PrivateKey) ois.readObject();
  ois.close();
  cipher.init(Cipher.DECRYPT_MODE, privateKey);
  FileInputStream fis = new FileInputStream(in);
  FileOutputStream fos = new FileOutputStream(out);
  CipherOutputStream cos = new CipherOutputStream(fos, cipher);
  byte[] buffer = new byte[bufSize];
  int length;
  while ((length = fis.read(buffer)) != -1)
   cos.write(buffer, 0, length);
  fis.close();
  fos.close();
 }

 // 키 생성
 public void genKey() throws Exception {
  KeyPairGenerator key = KeyPairGenerator.getInstance("RSA");
  key.initialize(1024);
  KeyPair kp = key.genKeyPair();
  PrivateKey privateKey = kp.getPrivate();
  PublicKey publicKey = kp.getPublic();
  ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("PrivateKey.ser"));
  out.writeObject(privateKey);
  out.close();
  out = new ObjectOutputStream(new FileOutputStream("PublicKey.ser"));
  out.writeObject(publicKey);
  out.close();
 }

 public static void main(String[] args) {
  CryptTest c = new CryptTest();
  try {
   // 키 생성
   c.genKey();
   // 파일 암호화
   c.encryptFile("a.txt", "b.txt");
   // 파일 복호화
   c.decryptFile("b.txt", "c.txt");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}


+ Recent posts