Language/Java

[펌] AES를 이용한 간단한 파일 암/복호화 예제

OIZTLOMO 2012. 5. 24. 22:59

어떤분(?)이 댓글로 AES를 이용한 파일 암/복호화 예제를 만들어달라고 요청을 해왔다.  그래서 간단히 만들어봤다.

 하지만, 세상에 공짜는 없는법~~~ 언제가 될지 모르겠지만, 나중에 혹시 만난다면 차나 한잔 사주세요. ^^;; 
001package cydar;
002 
003import java.io.BufferedInputStream;
004import java.io.BufferedOutputStream;
005import java.io.File;
006import java.io.FileInputStream;
007import java.io.FileOutputStream;
008import java.io.IOException;
009import java.io.InputStream;
010import java.io.OutputStream;
011import java.security.Key;
012 
013import javax.crypto.Cipher;
014import javax.crypto.spec.SecretKeySpec;
015 
016public class FileCoder {
017 
018    private static final String algorithm = "AES";
019    private static final String transformation = algorithm + "/ECB/PKCS5Padding";
020     
021    private Key key;
022 
023    public FileCoder(Key key) {
024        this.key = key;
025    }
026     
027    /**
028     * <p>원본 파일을 암호화해서 대상 파일을 만든다.</p>
029     *
030     * @param source 원본 파일
031     * @param dest 대상 파일
032     * @throws Exception
033     */
034    public void encrypt(File source, File dest) throws Exception {
035        crypt(Cipher.ENCRYPT_MODE, source, dest);
036    }
037     
038    /**
039     * <p>원본 파일을 복호화해서 대상 파일을 만든다.</p>
040     *
041     * @param source 원본 파일
042     * @param dest 대상 파일
043     * @throws Exception
044     */
045    public void decrypt(File source, File dest) throws Exception {
046        crypt(Cipher.DECRYPT_MODE, source, dest);
047    }
048     
049    /**
050     * <p>원본 파일을 암/복호화해서 대상 파일을 만든다.</p>
051     *
052     * @param mode 암/복호화 모드
053     * @param source 원본 파일
054     * @param dest 대상 파일
055     * @throws Exception
056     */
057    private void crypt(int mode, File source, File dest) throws Exception {
058        Cipher cipher = Cipher.getInstance(transformation);
059        cipher.init(mode, key);
060        InputStream input = null;
061        OutputStream output = null;
062        try {
063            input = new BufferedInputStream(new FileInputStream(source));
064            output = new BufferedOutputStream(new FileOutputStream(dest));
065            byte[] buffer = new byte[1024];
066            int read = -1;
067            while ((read = input.read(buffer)) != -1) {
068                output.write(cipher.update(buffer, 0, read));
069            }
070            output.write(cipher.doFinal());
071        finally {
072            if (output != null) {
073                try { output.close(); } catch(IOException ie) {}
074            }
075            if (input != null) {
076                try { input.close(); } catch(IOException ie) {}
077            }
078        }
079    }
080     
081    public static void main(String[] args) throws Exception {
082        // 128비트의 키
083        SecretKeySpec key = new SecretKeySpec(toBytes("696d697373796f7568616e6765656e61"16), algorithm);
084        FileCoder coder = new FileCoder(key);
085        coder.encrypt(new File("C:/ASLog_0.txt"), new File("C:/ASLog_0_E.txt"));
086        coder.decrypt(new File("C:/ASLog_0_E.txt"), new File("C:/ASLog_0_D.txt"));
087    }
088     
089    /**
090     * <p>문자열을 바이트배열로 바꾼다.</p>
091     *
092     * @param digits 문자열
093     * @param radix 진수
094     * @return
095     * @throws IllegalArgumentException
096     * @throws NumberFormatException
097     */
098    public static byte[] toBytes(String digits, int radix) throws IllegalArgumentException, NumberFormatException {
099        if (digits == null) {
100            return null;
101        }
102        if (radix != 16 && radix != 10 && radix != 8) {
103            throw new IllegalArgumentException("For input radix: \"" + radix + "\"");
104        }
105        int divLen = (radix == 16) ? 2 3;
106        int length = digits.length();
107        if (length % divLen == 1) {
108            throw new IllegalArgumentException("For input string: \"" + digits + "\"");
109        }
110        length = length / divLen;
111        byte[] bytes = new byte[length];
112        for (int i = 0; i < length; i++) {
113            int index = i * divLen;
114            bytes[i] = (byte)(Short.parseShort(digits.substring(index, index+divLen), radix));
115        }
116        return bytes;
117    }
118     
119 
120}



 쓸데없는 소리를 조금 하자면, 암호화키 관리(?)가 중요합니다. 여기서는 그냥 소스에 포함되어 있죠. 그리고 운용모드를 ECB말고 딴것을 쓰시는게 조금 더 견고할수 있습니다.
 그리고, 후다닥 만든거라서 장상작동할지 모르겠네요...
 편안히 잠드시길... ^^;;;;


출처: http://blog.kangwoo.kr/90

'Language > Java' 카테고리의 다른 글

Maven plugin - copy dependencies  (0) 2012.07.26
[펌] Add Oracle JDBC Jar to Maven Repository  (0) 2012.07.26
[펌] 자바 암호화 - RSA  (0) 2012.05.24
[펌] MD5와 SHA1  (0) 2012.05.24
[펌] 자바 암호화  (0) 2012.05.24