DevToolBox무료
블로그

Base64 인코딩 & 디코딩 완전 가이드: 코드 예제 포함

12분 읽기by DevToolBox

Base64 인코딩은 컴퓨팅에서 가장 기본적인 데이터 인코딩 체계 중 하나입니다. 매일 수백만 명의 개발자가 base64 encodebase64 decode 작업을 사용하여 HTML에 이미지를 임베드하고, 텍스트 기반 프로토콜로 바이너리 데이터를 전송하며, 인증 토큰을 처리합니다. 이 종합 가이드는 6비트 매핑 알고리즘부터 JavaScript, Python, Bash, PowerShell의 실용적인 코드 예제까지 모든 것을 다룹니다.

무료 온라인 Base64 인코딩/디코딩 도구를 사용해 보세요.

Base64 인코딩이란?

Base64는 64개의 인쇄 가능한 ASCII 문자를 사용하여 바이너리 데이터를 표현하는 바이너리-텍스트 인코딩 체계입니다. 알파벳은 A-Z(26), a-z(26), 0-9(10), +/로 구성됩니다. =는 패딩에 사용됩니다. 인코더는 입력을 3바이트(24비트) 그룹으로 처리하여 4개의 Base64 문자로 변환합니다.

알고리즘은 3바이트 입력을 4개의 6비트 그룹으로 분할합니다. 각 6비트 값(0-63)은 Base64 알파벳의 한 문자에 매핑됩니다. 입력 길이가 3의 배수가 아닌 경우 = 패딩 문자가 추가됩니다.

Base64 인코딩은 데이터 크기를 약 33% 증가시킵니다. 이 오버헤드는 텍스트 전용 채널을 통해 바이너리 데이터를 안전하게 전송하기 위한 대가입니다.

Base64 인코딩/디코딩 작동 원리

ASCII 문자열 Man을 Base64로 변환하는 과정을 단계별로 살펴보겠습니다:

  1. ASCII 바이트로 변환: M=77, a=97, n=110.
  2. 비트 연결: 총 24비트.
  3. 6비트 그룹으로 분할: 4개 그룹.
  4. 10진수로 변환: 19, 22, 5, 46.
  5. Base64 문자에 매핑: T, W, F, u.

결과는 TWFu입니다. 디코딩하려면 프로세스를 역으로 수행합니다.

패딩 예제: Ma(2바이트)를 인코딩하면 TWE=이 됩니다. 단일 바이트 MTQ==가 됩니다.

일반적인 Base64 사용 사례

Base64 인코딩은 현대 소프트웨어 개발 곳곳에 존재합니다:

데이터 URI(Base64 이미지 인코딩): data:image/png;base64,...로 HTML/CSS에 이미지를 직접 임베드하여 추가 HTTP 요청을 제거합니다.

이메일 첨부파일(MIME): MIME 표준은 이메일의 바이너리 첨부파일을 Base64로 인코딩합니다.

API 인증(HTTP Basic Auth): HTTP 기본 인증은 사용자:비밀번호를 Base64로 인코딩합니다.

JSON Web Token(JWT): JWT는 Base64URL로 인코딩된 3개 세그먼트로 구성됩니다.

URL 안전 데이터 전송: Base64는 데이터가 안전한 ASCII 문자만 포함하도록 보장합니다.

Base64 인코딩/디코딩 코드 예제

JavaScript Base64 인코딩/디코딩

브라우저에서 btoa()로 인코딩, atob()로 디코딩합니다. Node.js에서는 Buffer를 사용합니다:

// ===== Browser: btoa() and atob() =====

// Base64 encode a string
const encoded = btoa('Hello World');
console.log(encoded); // "SGVsbG8gV29ybGQ="

// Base64 decode a string
const decoded = atob('SGVsbG8gV29ybGQ=');
console.log(decoded); // "Hello World"

// Handle Unicode strings (btoa only supports Latin-1)
function base64EncodeUnicode(str) {
  return btoa(encodeURIComponent(str).replace(
    /%([0-9A-F]{2})/g,
    (_, p1) => String.fromCharCode(parseInt(p1, 16))
  ));
}

function base64DecodeUnicode(str) {
  return decodeURIComponent(
    Array.from(atob(str))
      .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
      .join('')
  );
}

base64EncodeUnicode('Hello 🌍');  // "SGVsbG8g8J+MjQ=="
base64DecodeUnicode('SGVsbG8g8J+MjQ=='); // "Hello 🌍"

// ===== Node.js: Buffer =====

// Encode
const buf = Buffer.from('Hello World', 'utf-8');
const b64 = buf.toString('base64');
console.log(b64); // "SGVsbG8gV29ybGQ="

// Decode
const original = Buffer.from(b64, 'base64').toString('utf-8');
console.log(original); // "Hello World"

// URL-safe Base64 in Node.js
const urlSafe = buf.toString('base64url');
console.log(urlSafe); // "SGVsbG8gV29ybGQ"

Python Base64 인코딩/디코딩

Python에서는 내장 base64 모듈을 사용합니다:

import base64

# Standard Base64 encode
text = "Hello World"
encoded = base64.b64encode(text.encode('utf-8'))
print(encoded)          # b'SGVsbG8gV29ybGQ='
print(encoded.decode())  # "SGVsbG8gV29ybGQ="

# Standard Base64 decode
decoded = base64.b64decode(encoded)
print(decoded.decode('utf-8'))  # "Hello World"

# URL-safe Base64 (replaces + with - and / with _)
url_encoded = base64.urlsafe_b64encode(text.encode('utf-8'))
print(url_encoded.decode())  # "SGVsbG8gV29ybGQ="

url_decoded = base64.urlsafe_b64decode(url_encoded)
print(url_decoded.decode('utf-8'))  # "Hello World"

# Encode a file (e.g., an image)
with open('image.png', 'rb') as f:
    image_b64 = base64.b64encode(f.read()).decode('utf-8')
    data_uri = f"data:image/png;base64,{image_b64}"

# Decode Base64 back to file
with open('output.png', 'wb') as f:
    f.write(base64.b64decode(image_b64))

Bash / Linux Base64 인코딩/디코딩

Linux/macOS에서는 base64 명령을 사용합니다:

# Base64 encode a string (Linux)
echo -n "Hello World" | base64
# Output: SGVsbG8gV29ybGQ=

# Base64 decode a string (Linux)
echo "SGVsbG8gV29ybGQ=" | base64 --decode
# Output: Hello World

# macOS uses -D instead of --decode
echo "SGVsbG8gV29ybGQ=" | base64 -D
# Output: Hello World

# Base64 encode a file
base64 image.png > image_b64.txt

# Base64 decode a file
base64 --decode image_b64.txt > restored_image.png

# Encode and use inline (e.g., for curl auth header)
AUTH=$(echo -n "user:password" | base64)
curl -H "Authorization: Basic $AUTH" https://api.example.com/data

# Pipe from/to files
cat document.pdf | base64 > document_b64.txt
cat document_b64.txt | base64 --decode > restored.pdf

# Wrap lines at 76 characters (MIME standard)
echo -n "Long text..." | base64 -w 76

PowerShell Base64 인코딩/디코딩

PowerShell에서는 .NET [Convert] 클래스를 사용합니다:

# PowerShell Base64 encode (UTF-16LE by default)
$text = "Hello World"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($text)
$encoded = [Convert]::ToBase64String($bytes)
Write-Output $encoded
# Output: SGVsbG8gV29ybGQ=

# PowerShell Base64 decode
$decoded = [Convert]::FromBase64String($encoded)
$original = [System.Text.Encoding]::UTF8.GetString($decoded)
Write-Output $original
# Output: Hello World

# Encode a file to Base64
$fileBytes = [IO.File]::ReadAllBytes("C:\image.png")
$fileBase64 = [Convert]::ToBase64String($fileBytes)

# Decode Base64 to file
$decodedBytes = [Convert]::FromBase64String($fileBase64)
[IO.File]::WriteAllBytes("C:\restored.png", $decodedBytes)

# One-liner for encoding strings (UTF-8)
[Convert]::ToBase64String(
  [Text.Encoding]::UTF8.GetBytes("Hello World")
)

# Using UTF-16LE (default Windows encoding)
$utf16 = [Convert]::ToBase64String(
  [Text.Encoding]::Unicode.GetBytes("Hello World")
)
# Note: UTF-16LE produces different output than UTF-8

Base64 인코딩 테이블

완전한 Base64 알파벳은 각 6비트 값(0-63)을 인쇄 가능한 ASCII 문자에 매핑합니다(RFC 4648):

ValueCharValueCharValueCharValueChar
0A16Q32g48w
1B17R33h49x
2C18S34i50y
3D19T35j51z
4E20U36k520
5F21V37l531
6G22W38m542
7H23X39n553
8I24Y40o564
9J25Z41p575
10K26a42q586
11L27b43r597
12M28c44s608
13N29d45t619
14O30e46u62+
15P31f47v63/

Padding: =

Base64 URL 안전 인코딩

표준 Base64는 URL에서 특별한 의미를 가진 +/를 사용합니다. Base64URL은 이를 -_로 대체하고, = 패딩을 보통 생략합니다.

Base64URL은 RFC 4648 섹션 5에 정의되어 있으며, JWT, OAuth 2.0 PKCE, 많은 최신 API에서 사용됩니다.

표준 Base64와 Base64URL 비교:

// Standard Base64 vs Base64URL comparison

// Standard Base64 (RFC 4648 Section 4)
// Alphabet: A-Z, a-z, 0-9, +, /
// Padding:  = (required)
"Hello World?" → "SGVsbG8gV29ybGQ/"   // contains /
"subjects?"    → "c3ViamVjdHM/"       // contains /
"<<???>>"     → "PDw/Pz8+Pg=="        // contains + and =

// Base64URL (RFC 4648 Section 5)
// Alphabet: A-Z, a-z, 0-9, -, _
// Padding:  omitted (optional)
"Hello World?" → "SGVsbG8gV29ybGQ_"   // / replaced with _
"subjects?"    → "c3ViamVjdHM_"       // / replaced with _
"<<???>>"     → "PDw_Pz8-Pg"          // + → -, / → _, no padding

// JavaScript conversion between formats
function base64ToBase64Url(base64) {
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

function base64UrlToBase64(base64url) {
  let base64 = base64url
    .replace(/-/g, '+')
    .replace(/_/g, '/');
  // Add padding
  while (base64.length % 4 !== 0) {
    base64 += '=';
  }
  return base64;
}

Base64 이미지 인코딩

Base64의 가장 인기 있는 용도 중 하나는 데이터 URI를 사용하여 HTML/CSS에 이미지를 직접 임베드하는 것입니다. 형식: data:[미디어타입];base64,[데이터].

일반적인 사용 사례: HTML 이메일의 인라인 이미지, CSS의 작은 아이콘, JSON API 응답의 이미지, SPA의 자산 번들링.

성능 고려사항: Base64 이미지는 약 33% 더 큽니다. 수 KB 이상의 이미지는 별도 파일로 제공하는 것이 효율적입니다. Base64는 작은 이미지(10KB 이하)에 최적입니다.

HTML에서 Base64 이미지 사용:

<!-- Inline Base64 image in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAADElEQVQI12P4//8/AwAI/AL+hc2rNAAAAABJRU5E
rkJggg==" alt="Red dot" width="5" height="5" />

<!-- Base64 SVG in HTML -->
<img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDov
L3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAiIGhlaWdodD0iMT
AwIj48Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI0MCIgZmlsbD0icmVk
Ii8+PC9zdmc+" alt="Red circle" />

<!-- Base64 favicon -->
<link rel="icon" href="data:image/x-icon;base64,AAABAA..." />

CSS에서 Base64 이미지 사용:

/* Base64 background image in CSS */
.icon-check {
  background-image: url('data:image/svg+xml;base64,PHN2ZyB4bW...');
  background-size: contain;
  width: 24px;
  height: 24px;
}

/* Base64 cursor in CSS */
.custom-cursor {
  cursor: url('data:image/png;base64,iVBORw0KGgo...'), auto;
}

/* Base64 font in CSS (@font-face) */
@font-face {
  font-family: 'CustomFont';
  src: url('data:font/woff2;base64,d09GMgABAAAAAD...') format('woff2');
}

JavaScript에서 이미지를 Base64로 변환:

// Convert image file to Base64 data URI (browser)
function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

// Usage with file input
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', async (e) => {
  const file = e.target.files[0];
  const dataUri = await imageToBase64(file);
  console.log(dataUri);
  // "data:image/png;base64,iVBORw0KGgo..."
});

// Convert canvas to Base64
const canvas = document.getElementById('myCanvas');
const base64Image = canvas.toDataURL('image/png');
// "data:image/png;base64,iVBORw0KGgo..."

// Node.js: encode image file to Base64
const fs = require('fs');
const imageBuffer = fs.readFileSync('photo.jpg');
const base64String = imageBuffer.toString('base64');
const dataUri = `data:image/jpeg;base64,${base64String}`;

자주 묻는 질문

Base64 인코딩은 무엇에 사용되나요?

Base64는 바이너리 데이터를 ASCII 텍스트로 변환하여 텍스트 프로토콜을 통해 안전하게 전송합니다. 주요 용도: 데이터 URI, 이메일 첨부파일, JSON/XML API, HTTP Basic Auth, JWT, 텍스트 데이터베이스에 바이너리 저장.

JavaScript에서 문자열을 Base64로 인코딩하려면?

btoa("Hello World")는 "SGVsbG8gV29ybGQ="를 반환합니다. 디코딩: atob("SGVsbG8gV29ybGQ="). Unicode: btoa(unescape(encodeURIComponent(text))). Node.js: Buffer.from("Hello World").toString("base64").

Base64 인코딩은 암호화와 같은 건가요?

아닙니다. Base64는 키 없이 누구나 복원할 수 있는 가역적 인코딩입니다. 보안성이 전혀 없습니다. 데이터 보호에는 AES-256이나 RSA 같은 암호화를 사용하세요.

Base64 인코딩은 모든 개발자에게 필수적인 기술입니다. 무료 온라인 도구로 즉시 인코딩과 디코딩을 수행하세요.

무료 온라인 도구로 Base64를 즉시 인코딩하고 디코딩하세요.

𝕏 Twitterin LinkedIn
도움이 되었나요?

최신 소식 받기

주간 개발 팁과 새 도구 알림을 받으세요.

스팸 없음. 언제든 구독 해지 가능.

Try These Related Tools

B64Base64 Encoder/DecoderB→Base64 Encoder→BBase64 DecoderJWTJWT Decoder

Related Articles

Base64 인코딩 실전: 모든 개발자가 알아야 할 7가지 실제 활용

Base64의 7가지 실용 활용: HTML 이미지 삽입, Kubernetes 시크릿, JWT 토큰, Data URI.

Hex to RGB 변환기: 개발자를 위한 컬러 코드 가이드

무료 Hex to RGB 변환기와 가이드. 16진수 색상 코드의 작동 원리와 JavaScript, CSS, Python 변환 코드.

Base64 인코딩/디코딩 온라인 가이드: JavaScript, Python, CLI

Base64 인코딩/디코딩 완벽 가이드. JavaScript (btoa/atob, Buffer), Python, 커맨드라인, Data URI, JWT, API 인증, URL 안전 Base64.