오늘은 어디로 갈까...

AES를 이용한 간단한 파일 암/복호화 예제 본문

낙서

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

剛宇 2009. 6. 17. 09:22

 어떤분(?)이 댓글로 AES를 이용한 파일 암/복호화 예제를 만들어달라고 요청을 해왔다.  그래서 간단히 만들어봤다.
 하지만, 세상에 공짜는 없는법~~~ 언제가 될지 모르겠지만, 나중에 혹시 만난다면 차나 한잔 사주세요. ^^;;
package cydar;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class FileCoder {

	private static final String algorithm = "AES";
	private static final String transformation = algorithm + "/ECB/PKCS5Padding";
	
	private Key key;

	public FileCoder(Key key) {
		this.key = key;
	}
	
	/**
	 * <p>원본 파일을 암호화해서 대상 파일을 만든다.</p>
	 * 
	 * @param source 원본 파일
	 * @param dest 대상 파일
	 * @throws Exception
	 */
	public void encrypt(File source, File dest) throws Exception {
		crypt(Cipher.ENCRYPT_MODE, source, dest);
	}
	
	/**
	 * <p>원본 파일을 복호화해서 대상 파일을 만든다.</p>
	 * 
	 * @param source 원본 파일
	 * @param dest 대상 파일
	 * @throws Exception
	 */
	public void decrypt(File source, File dest) throws Exception {
		crypt(Cipher.DECRYPT_MODE, source, dest);
	}
	
	/**
	 * <p>원본 파일을 암/복호화해서 대상 파일을 만든다.</p>
	 * 
	 * @param mode 암/복호화 모드
	 * @param source 원본 파일
	 * @param dest 대상 파일
	 * @throws Exception
	 */
	private void crypt(int mode, File source, File dest) throws Exception {
		Cipher cipher = Cipher.getInstance(transformation);
		cipher.init(mode, key);
		InputStream input = null;
		OutputStream output = null;
		try {
			input = new BufferedInputStream(new FileInputStream(source));
			output = new BufferedOutputStream(new FileOutputStream(dest));
			byte[] buffer = new byte[1024];
			int read = -1;
			while ((read = input.read(buffer)) != -1) {
				output.write(cipher.update(buffer, 0, read));
			}
			output.write(cipher.doFinal());
		} finally {
			if (output != null) {
				try { output.close(); } catch(IOException ie) {}
			}
			if (input != null) {
				try { input.close(); } catch(IOException ie) {}
			}
		}
	}
	
	public static void main(String[] args) throws Exception {
		// 128비트의 키
		SecretKeySpec key = new SecretKeySpec(toBytes("696d697373796f7568616e6765656e61", 16), algorithm);
		FileCoder coder = new FileCoder(key);
		coder.encrypt(new File("C:/ASLog_0.txt"), new File("C:/ASLog_0_E.txt"));
		coder.decrypt(new File("C:/ASLog_0_E.txt"), new File("C:/ASLog_0_D.txt"));
	}
	
	/**
	 * <p>문자열을 바이트배열로 바꾼다.</p>
	 * 
	 * @param digits 문자열
	 * @param radix 진수
	 * @return
	 * @throws IllegalArgumentException
	 * @throws NumberFormatException
	 */
	public static byte[] toBytes(String digits, int radix) throws IllegalArgumentException, NumberFormatException {
		if (digits == null) {
			return null;
		}
		if (radix != 16 && radix != 10 && radix != 8) {
			throw new IllegalArgumentException("For input radix: \"" + radix + "\"");
		}
		int divLen = (radix == 16) ? 2 : 3;
    	int length = digits.length();
    	if (length % divLen == 1) {
    		throw new IllegalArgumentException("For input string: \"" + digits + "\"");
    	}
    	length = length / divLen;
    	byte[] bytes = new byte[length];
    	for (int i = 0; i < length; i++) {
    		int index = i * divLen;
    		bytes[i] = (byte)(Short.parseShort(digits.substring(index, index+divLen), radix));
    	}
    	return bytes;
	}
	

}



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