Java/Jakarta Project2009. 7. 3. 16:37

Java 뿐 아니라 개발자라면 한번쯤은 접해봤을법한 Base64 인코딩...
Base64의 인코딩 원리는 아래의 글을 확인해 주시고...

2009/02/23 - [정보보안/암호학] - Base64 인코딩 원리

Java 에서 Base64 인코딩을 하기 위해서는 기본적으로 Java에서 제공하는 클래스를 이용하는 방법과
Apache Commons Codec 의 Base64 클래스를 사용하는 방법이 있다.

먼저 자바에서 기본적으로 제공하는 Base64 인코딩...
static 메서드가 아니기 때문에 객체 생성후 호출을 해야하고
decoding의 경우 예외처리까지 해야하는 불편함이 있다.

01.import java.io.IOException;
02. 
03.import sun.misc.BASE64Decoder;
04.import sun.misc.BASE64Encoder;
05. 
06.public class TestBase64Encoder {
07.    public static void main(String[] args) {
08.        BASE64Encoder encoder = new BASE64Encoder();
09.        BASE64Decoder decoder = new BASE64Decoder();
10. 
11.        String txtPlain = "베이스64 인코딩, 디코딩 테스트입니다.";
12.        String txtCipher = "";
13.        System.out.println("Source String : " + txtPlain);
14. 
15.        txtCipher = encoder.encode(txtPlain.getBytes());
16.        System.out.println("Encode Base64 : " + txtCipher);
17. 
18.        try {
19.            txtPlain = new String(decoder.decodeBuffer(txtCipher));
20.        } catch (IOException ioe) {
21.            ioe.printStackTrace();
22.        }
23.        System.out.println("Decode Base64 : " + txtPlain);
24.    }
25.}

다음은 Apache Commons Codec  의 Base64 클래스를 이용하는 방법이다.
이전 소스코드보다 상대적으로 많이 길이가 줄어들었으며 static 메서드라서 바로 호출이 가능하다.
물론 이전 소스코드보다 가독성 또한 뛰어나다.

01.import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
02. 
03.public class TestCodecBase64 {
04.    public static void main(String[] args) {
05.        String txtPlain = "베이스64 인코딩, 디코딩 테스트입니다.";
06.        String txtCipher = "";
07.        System.out.println("Source String : " + txtPlain);
08. 
09.        txtCipher = Base64.encode(txtPlain.getBytes());
10.        System.out.println("Encode Base64 : " + txtCipher);
11. 
12.        txtPlain = new String(Base64.decode(txtCipher));
13.        System.out.println("Decode Base64 : " + txtPlain);
14.    }
15.}

위 두개 소스의 결과는 동일하며 아래와 같다.

Source String : 베이스64 인코딩, 디코딩 테스트입니다.
Encode Base64 : uqPAzL26NjQgwM7E2rX5LCC18MTatfkgxde9usauwNS0z7TZLg==
Decode Base64 : 베이스64 인코딩, 디코딩 테스트입니다.

 

 

Posted by Huikyun