자바 암호화/복호화 코드 :: 2008/08/23 23:11

자바에서 대칭키 방식의 문자열 및 파일을 암호화/복호화하는 코드이다. 암복호화 알고리즘은 Java Cryptography Extension (JCE)에 의해 지원된다.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

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

/**
 * 문자열 및 파일에 대한 암호화/복호화
 */
public class Crypto {

    /** 파일 처리용 버퍼 크기 */
    private static final int BUFFER_SIZE = 8192;

    /** 디폴트 비밀키 파일 */
    private static final String DEFAULT_KEY_FILE = "default.key";

    /** 비밀키 */
    private static Key key = null;

    /**
     * 비밀키 파일 생성 메소드
     * 
     * @return 비밀키 파일
     * @throws IOException
     * @throws NoSuchAlgorithmException
     */
    public static File makeKey() throws IOException, NoSuchAlgorithmException {
        return makeKey(DEFAULT_KEY_FILE);
    }

    public static File makeKey(String filename) throws IOException,
                    NoSuchAlgorithmException {
        File file = new File(filename);
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        generator.init(new SecureRandom());
        Key key = generator.generateKey();
        ObjectOutputStream out =
            new ObjectOutputStream(new FileOutputStream(file));
        out.writeObject(key);
        out.close();
        return file;
    }

    /**
     * 지정된 비밀키를 가지고 오는 메서드
     * 
     * @return 비밀키
     * @throws Exception
     */
    private static Key getKey() throws Exception {
        if (key != null) {
            return key;
        } else {
            return getKey(DEFAULT_KEY_FILE);
        }
    }

    private static Key getKey(String filename) throws Exception {
        if (key == null) {
            File file = new File(filename);
            if (!file.exists()) {
                file = makeKey();
            }
            if (file.exists()) {
                ObjectInputStream in =
                    new ObjectInputStream(new FileInputStream(filename));
                key = (Key) in.readObject();
                in.close();
            } else {
                throw new Exception("암호키 객체를 생성할 수 없습니다.");
            }
        }
        return key;
    }

    /**
     * 문자열 대칭 암호화
     * 
     * @param strVal 암호화할 문자열
     * @return 암호화된 문자열
     * @throws Exception
     */
    public static String encrypt(String strVal) throws Exception {
        if (strVal == null || strVal.length() == 0)
            return "";
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getKey());
        String amalgam = strVal;

        byte[] inputBytes1 = amalgam.getBytes("UTF-8");
        byte[] outputBytes1 = cipher.doFinal(inputBytes1);
        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        String outputStr1 = encoder.encode(outputBytes1);
        return outputStr1;
    }

    /**
     * 문자열 대칭 복호화
     * 
     * @param strVal 복호화할 문자열
     * @return 복호화된 문자열
     * @throws Exception
     */
    public static String decrypt(String strVal) throws Exception {
        if (strVal == null || strVal.length() == 0)
            return "";
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, getKey());
        sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

        byte[] inputBytes1 = decoder.decodeBuffer(strVal);
        byte[] outputBytes2 = cipher.doFinal(inputBytes1);

        String strResult = new String(outputBytes2, "UTF-8");
        return strResult;
    }

    /**
     * 파일 대칭 암호화
     * 
     * @param infile 암호화할 파일명
     * @param outfile 암호화된 파일명
     * @throws Exception
     */
    public static void encryptFile(String infile, String outfile)
                    throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, getKey());

        FileInputStream in = new FileInputStream(infile);
        FileOutputStream fileOut = new FileOutputStream(outfile);

        CipherOutputStream out = new CipherOutputStream(fileOut, cipher);
        byte[] buffer = new byte[BUFFER_SIZE];
        int length;
        while ((length = in.read(buffer)) != -1)
            out.write(buffer, 0, length);
        in.close();
        out.close();
    }

    /**
     * 파일 대칭 복호화
     * 
     * @param infile 복호화할 파일명
     * @param outfile 복호화된 파일명
     * @throws Exception
     */
    public static void decryptFile(String infile, String outfile)
                    throws Exception {
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, getKey());

        FileInputStream in = new FileInputStream(infile);
        FileOutputStream fileOut = new FileOutputStream(outfile);

        CipherOutputStream out = new CipherOutputStream(fileOut, cipher);
        byte[] buffer = new byte[BUFFER_SIZE];
        int length;
        while ((length = in.read(buffer)) != -1)
            out.write(buffer, 0, length);
        in.close();
        out.close();
    }
}
Trackback Address :: http://www.java2go.net/blog/trackback/88
  • nick | 2010/01/21 15:58 | PERMALINK | EDIT/DEL | REPLY

    사용하시는 java 개발환경이 뭔지 궁금합니다.

    javaSE 6 DK 를 사용중인데

    sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

    해당 구문에서 오류가 나네요^^;;

  • Sehwan Noh | 2010/01/22 17:15 | PERMALINK | EDIT/DEL | REPLY

    JDK 1.5에서 했었는데, JDK 1.6에서 잘 되는군요. 다시 한번 해보세요.

    public static void main(String[] args) throws Exception {
    String text = "1234";
    String encText = Crypto.encrypt(text);
    System.out.println(encText);
    String decText = Crypto.decrypt(encText);
    System.out.println(decText);
    }

    dGXg+tdoIKM=
    1234

  • nick | 2010/01/25 03:13 | PERMALINK | EDIT/DEL | REPLY

    감사합니다.
    Eclipse Europa 버젼에서 잘 실행이되네요

    Jase EE IDE 라고 뜨는

    Eclipse galilreo 버젼에서는 해당 클래스가 Access restriction 이 되어있었네요.


    개발도구 하나 제대로 맞춰 실행하지 못하다니ㅠㅠ

  • syuanicarus | 2010/05/02 22:49 | PERMALINK | EDIT/DEL | REPLY

    ^^ 프로그램은 잘 봤습니다. 제가 아직 암호화쪽 소스를 잘몰라서 그러는데 설명좀 해주실수 있는지요..

  • 볼우물 | 2010/06/03 22:07 | PERMALINK | EDIT/DEL | REPLY

    1.4버전에서 실행시
    java.io.StreamCorruptedException 이런 에러가 나는데 원인이 뭔가요?
    1.5에서는 잘되는데...

Name
Password
Homepage
Secret
< PREV |  1  |  ...  115  |  116  |  117  |  118  |  119  |  120  |  121  |  122  |  123  |  ...  169  |  NEXT >