Recent Posts
Recent Comments
Link
06-30 12:53
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

BASE64 (64진법) 본문

DEV&OPS/Java

BASE64 (64진법)

ALEPH.GEM 2022. 5. 26. 17:36

Base64는 64진법이라는 뜻입니다.

디지털 신호인 2진법은 너무도 길어서 8진법이나 16진법 등으로 묶어서 표현 하기도 합니다.

64진법은 영어권의 ASCII 문자들을 써서 표현 할 수 있는 가장 큰 진법인데

그래서 Base64는 전자 메일을 통한 2진 데이터 전송에 많이 쓰이고 있습니다.

보통 알파벳 대문자 A~Z, 소문자 a~z, 숫자0~9, 그리고 마지막 두 개를 어떤 기호를 쓰느냐의 차이만 있습니다.

Base64의 정확한 규격은 RFC 1421, RFC 2045에 정의 됩니다. 

연속된 8비트를 인코딩하도록 정의되어 있습니다.

인코딩된 결과는 padding된 비트 때문에 원본보다 용량이 4/3 정도 늘어나게 됩니다.

2진(binary)데이터를 알파벳 등으로 변환하는 것이기 때문에 이미지 데이터도 2진데이터 이므로 base64로 인코딩 하여 전달 후 디코딩 할 수 있습니다.

 

jdk 1.8 이전 버전에서는 org.apache.commons.codec.binary 패키지 같은 3rd party 라이브러리를 사용 했습니다만,

jdk 1.8 부터 표준 API 로 util 패키지에 base64 인코딩과 디코딩이 포함되었습니다!
아래 코드는 java.util 패키지 예제 입니다.

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;


public class Base64Sample {

    public static void main(String[] args) throws UnsupportedEncodingException {
        
        String target = "base64로 인코딩 할 데이터";
        byte[] targetBytes = target.getBytes("UTF-8");
        
        // Base64 인코더 생성
        Encoder encoder = Base64.getEncoder();
        
        // 바이트배열로 인코딩 후 String 으로 출력
        byte[] encodedBytes = encoder.encode(targetBytes);
        System.out.println(new String(encodedBytes));
        
        // 바로 String 으로 인코딩
        String encodedString = encoder.encodeToString(targetBytes);
        System.out.println(encodedString);
        
        // Base64 디코더 생성
        Decoder decoder = Base64.getDecoder();
        
        // 바이트 배열로 인코딩 된 데이터 디코딩 
        byte[] decodedBytes1 = decoder.decode(encodedBytes);
        // String 으로 인코딩 된 데이터 디코딩
        byte[] decodedBytes2 = decoder.decode(encodedString);
        
        // 디코딩한 문자열을 표시
        String decodedString = new String(decodedBytes1, "UTF-8");
        System.out.println(decodedString);
        System.out.println(new String(decodedBytes2, "UTF-8"));
    }

}

 

DEV

 

728x90