반응형
Base64
- 바이너리 데이터를 문자 코드에 영향을 받지 않는 공통 ASCII 문자(A-Z, a-z, 0-9)로 표현하기 만들어진 인코딩이다.
- ASCII 문자 하나가 64진법의 숫자 하나를 의미하기 때문에 BASE64라는 이름을 가졌다.
- 시스템 간의 데이터 전달시 데이터에 지원하지 못하는 문자 코드가 포함되거나 시스템 별로 다른 문자 코드(ex. Line Ending)가 포함될 경우 문제가 발생할 수 있다.
- 이러한 문제를 방지하기 위해 데이터를 안전한 문자(ASCII 영역의 문자)로만 변환할 때 사용한다.
Base64WithJavaUtilTest
- java.util.Base64를 활용하는 방법
import org.junit.jupiter.api.Test;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Base64WithJavaUtilTest {
@Test
public void testBase64() {
assertEquals("SGVsbG8gV29ybGQ=", encode("Hello World"));
assertEquals("Hello World", decode("SGVsbG8gV29ybGQ="));
}
private static String encode(String decodedText) {
Base64.Encoder encoder = Base64.getEncoder();
byte[] encodedBytes = encoder.encode(decodedText.getBytes());
return new String(encodedBytes);
}
private static String decode(String encodedText) {
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedBytes = decoder.decode(encodedText.getBytes());
return new String(decodedBytes);
}
}
undefinedcopy
Base64WithCommonCodecTest
- apache commons codec을 활용하는 방법
dependencies {
implementation 'commons-codec:commons-codec:1.15'
...
}
undefinedcopy
import org.apache.commons.codec.binary.Base64;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Base64WithCommonCodecTest {
@Test
public void testBase64() {
assertEquals("SGVsbG8gV29ybGQ=", encode("Hello World"));
assertEquals("Hello World", decode("SGVsbG8gV29ybGQ="));
}
private static String encode(String decodedText) {
byte[] encodedBytes = Base64.encodeBase64(decodedText.getBytes());
return new String(encodedBytes);
}
private static String decode(String encodedText) {
byte[] decodedBytes = Base64.decodeBase64(encodedText.getBytes());
return new String(decodedBytes);
}
}
undefinedcopy
참고
반응형
'Development > Java' 카테고리의 다른 글
[Java] Random (0) | 2022.06.21 |
---|---|
[Java] Cipher(RSA, AES) (0) | 2022.04.27 |
[Java] Singleton Pattern (0) | 2022.01.07 |
[Java] JUnit5 (0) | 2021.12.08 |
[Java] JUnit4 (0) | 2021.11.23 |