logo hsb.horse
← 블로그 목록으로 돌아가기

블로그

age-tar로 디렉터리 단위 암호화 백업 자동화하기

age와 tar를 조합해 하위 디렉터리마다 암호화 아카이브를 만드는 셸 스크립트. 일본어 디렉터리명을 포함한 운영에서도 CLI 호환성을 유지할 수 있다.

게시일: 수정일:

로컬 파일을 클라우드 스토리지에 백업할 때는 평문 상태로 업로드하는 운영을 피하고 싶다.

그래서 agetar를 조합해 “디렉터리 단위로 암호화 아카이브를 만드는” age-tar 스크립트를 만들었다.

무엇을 해결하고 싶은가

백업 운영에서는 다음 두 가지가 자주 병목이 된다.

  1. 디렉터리마다 tar로 묶고 age로 암호화하는 과정을 수작업으로 하기 번거롭다
  2. 일본어나 공백이 포함된 디렉터리 이름은 CLI에서 다루기 불편하다

age-tar는 이 두 가지를 한 번에 처리한다.

이 스크립트로 할 수 있는 것

  • 지정한 디렉터리 바로 아래의 하위 디렉터리를 각각 tar + age로 암호화
  • 출력 파일명은 base64URL로 인코딩해 CLI 친화성을 확보
  • 복호화 시 원래 디렉터리 이름으로 되돌려서 압축 해제
  • --dryrun으로 실제 파일 조작 없이 실행 내용만 확인

전제

age 설치

Terminal window
# macOS
brew install age
# Ubuntu/Debian
apt install age
# 또는 공식 릴리스 사용
# https://github.com/FiloSottile/age/releases

키 생성

Terminal window
# 비밀 키 생성
age-keygen -o ~/.age/key.txt
# 공개 키 추출
age-keygen -y ~/.age/key.txt > ~/.age/key.pub

사용법

암호화

Terminal window
age-tar -R ~/.age/key.pub -i /path/to/backup/target

/path/to/backup/target 바로 아래의 각 디렉터리가 .tar.age 파일이 된다.

target/
├── 日本語フォルダ/
├── my documents/
└── projects/

암호화 후에도 원래 디렉터리는 그대로 남는다.

target/
├── 5pel5pys6Kqe44OV44Kp44Or44OA.tar.age
├── bXkgZG9jdW1lbnRz.tar.age
├── cHJvamVjdHM.tar.age
├── 日本語フォルダ/
├── my documents/
└── projects/

복호화

Terminal window
age-tar -d -I ~/.age/key.txt -i /path/to/encrypted/target

.tar.age 파일을 복호화해서 원래 이름의 디렉터리로 다시 풀어낸다.

드라이런

Terminal window
# Encrypt
age-tar -R ~/.age/key.pub -i /path/to/target --dryrun
# Decrypt
age-tar -d -I ~/.age/key.txt -i /path/to/target --dryrun

실행될 명령만 출력하고 실제 파일 작업은 하지 않는다.

운영 예시

Terminal window
# 1. 로컬에서 암호화
age-tar -R ~/.age/key.pub -i ~/important-data
# 2. 암호화된 파일 업로드
rclone copy ~/important-data/*.tar.age remote:backup/
# 3. 복원
rclone copy remote:backup/ ~/restore/
age-tar -d -I ~/.age/key.txt -i ~/restore

전체 스크립트

#!/bin/bash
set -euo pipefail
usage() {
cat <<EOF
Usage:
Encrypt: $(basename "$0") -R <public_key_path> -i <target_directory> [--dryrun]
Decrypt: $(basename "$0") -d -I <identity_path> -i <target_directory> [--dryrun]
Options:
-R <path> Path to the age public key file (for encryption)
-I <path> Path to the age identity/secret key file (for decryption)
-i <path> Path to the target directory (required)
-d Decrypt mode
--dryrun Simulation mode - show commands without executing
Description:
Encrypt mode:
Archives each subdirectory under the target directory into a tar file,
then encrypts it using age with the specified public key.
The output filename is the directory name encoded in base64URL format.
Decrypt mode:
Decrypts each .tar.age file in the target directory,
extracts the tar archive, and restores the original directory name
from the base64URL encoded filename.
EOF
exit 1
}
# Encode string to base64URL format
to_base64url() {
local str="$1"
# base64URL: replace + with -, / with _, remove = padding
echo -n "$str" | base64 | tr -d '\n' | tr '+/' '-_' | tr -d '='
}
# Decode base64URL format to string
from_base64url() {
local str="$1"
# Restore standard base64: replace - with +, _ with /
local base64_str
base64_str=$(echo -n "$str" | tr '_' '/' | tr '\-' '+')
# Add padding if necessary
local padding=$((4 - ${#base64_str} % 4))
if [[ $padding -ne 4 ]]; then
base64_str="${base64_str}$(printf '=%.0s' $(seq 1 $padding))"
fi
echo -n "$base64_str" | base64 -d
}
# Parse arguments
PUBLIC_KEY=""
IDENTITY=""
TARGET_DIR=""
DRYRUN=false
DECRYPT_MODE=false
while [[ $# -gt 0 ]]; do
case "$1" in
-R)
if [[ -z "${2:-}" ]]; then
echo "Error: -R requires a path argument" >&2
exit 1
fi
PUBLIC_KEY="$2"
shift 2
;;
-I)
if [[ -z "${2:-}" ]]; then
echo "Error: -I requires a path argument" >&2
exit 1
fi
IDENTITY="$2"
shift 2
;;
-i)
if [[ -z "${2:-}" ]]; then
echo "Error: -i requires a path argument" >&2
exit 1
fi
TARGET_DIR="$2"
shift 2
;;
-d)
DECRYPT_MODE=true
shift
;;
--dryrun)
DRYRUN=true
shift
;;
-h|--help)
usage
;;
*)
echo "Error: Unknown option: $1" >&2
usage
;;
esac
done
# Validate required arguments
if [[ -z "$TARGET_DIR" ]]; then
echo "Error: -i <target_directory> is required" >&2
usage
fi
if $DECRYPT_MODE; then
if [[ -z "$IDENTITY" ]]; then
echo "Error: -I <identity_path> is required for decryption" >&2
usage
fi
if [[ ! -f "$IDENTITY" ]]; then
echo "Error: Identity file not found: $IDENTITY" >&2
exit 1
fi
else
if [[ -z "$PUBLIC_KEY" ]]; then
echo "Error: -R <public_key_path> is required for encryption" >&2
usage
fi
if [[ ! -f "$PUBLIC_KEY" ]]; then
echo "Error: Public key file not found: $PUBLIC_KEY" >&2
exit 1
fi
fi
if [[ ! -d "$TARGET_DIR" ]]; then
echo "Error: Target directory not found: $TARGET_DIR" >&2
exit 1
fi
# Check if age command exists
if ! command -v age &> /dev/null; then
echo "Error: 'age' command not found. Please install age first." >&2
exit 1
fi
TARGET_DIR="${TARGET_DIR%/}" # Remove trailing slash if present
# Decrypt mode
if $DECRYPT_MODE; then
found_files=false
for encrypted_file in "$TARGET_DIR"/*.tar.age; do
# Skip if no files found (glob didn't match)
[[ -f "$encrypted_file" ]] || continue
found_files=true
filename=$(basename "$encrypted_file")
encoded_name="${filename%.tar.age}"
original_dirname=$(from_base64url "$encoded_name")
tarfile="${TARGET_DIR}/${encoded_name}.tar"
echo "Processing: $filename"
echo " Decoded name: $original_dirname"
if $DRYRUN; then
echo " [dryrun] age -d -i \"$IDENTITY\" -o \"$tarfile\" \"$encrypted_file\""
echo " [dryrun] tar -xf \"$tarfile\" -C \"$TARGET_DIR\""
echo " [dryrun] rm \"$tarfile\""
else
# Decrypt with age
echo " Decrypting: $tarfile"
age -d -i "$IDENTITY" -o "$tarfile" "$encrypted_file"
# Extract tar archive
echo " Extracting: $original_dirname"
tar -xf "$tarfile" -C "$TARGET_DIR"
# Remove the tar file
echo " Removing tar: $tarfile"
rm "$tarfile"
fi
echo " Done: $original_dirname"
echo
done
if ! $found_files; then
echo "Warning: No .tar.age files found in $TARGET_DIR" >&2
exit 0
fi
echo "All files decrypted successfully."
exit 0
fi
# Encrypt mode
found_dirs=false
for dir in "$TARGET_DIR"/*/; do
# Skip if no directories found (glob didn't match)
[[ -d "$dir" ]] || continue
found_dirs=true
dir="${dir%/}" # Remove trailing slash
dirname=$(basename "$dir")
encoded_name=$(to_base64url "$dirname")
tarfile="${TARGET_DIR}/${encoded_name}.tar"
encrypted_file="${TARGET_DIR}/${encoded_name}.tar.age"
echo "Processing: $dirname"
echo " Encoded name: $encoded_name"
if $DRYRUN; then
echo " [dryrun] tar -cf \"$tarfile\" -C \"$TARGET_DIR\" \"$dirname\""
echo " [dryrun] age --armor -R \"$PUBLIC_KEY\" -o \"$encrypted_file\" \"$tarfile\""
echo " [dryrun] rm \"$tarfile\""
else
# Create tar archive
echo " Creating tar archive: $tarfile"
tar -cf "$tarfile" -C "$TARGET_DIR" "$dirname"
# Encrypt with age
echo " Encrypting: $encrypted_file"
age --armor -R "$PUBLIC_KEY" -o "$encrypted_file" "$tarfile"
# Remove the unencrypted tar file
echo " Removing unencrypted tar: $tarfile"
rm "$tarfile"
fi
echo " Done: $encrypted_file"
echo
done
if ! $found_dirs; then
echo "Warning: No subdirectories found in $TARGET_DIR" >&2
exit 0
fi
echo "All directories processed successfully."

설치

Terminal window
curl -o ~/.local/bin/age-tar <YOUR_GIST_URL>
chmod +x ~/.local/bin/age-tar
# ~/.bashrc or ~/.zshrc
export PATH="$HOME/.local/bin:$PATH"

보충 메모

  • 이 구현은 대상 디렉터리 바로 아래의 하위 디렉터리만 처리한다
  • 암호화 후에도 원본 디렉터리는 남아 있으므로, 삭제 정책은 별도로 정해야 한다
  • 복호화 시 .tar.age에서 임시 .tar를 만든 뒤 압축을 풀고, 이후 그 임시 tar 파일을 삭제한다

정리

age-tar를 쓰면 디렉터리 단위 암호화 백업을 반복 가능한 절차로 만들 수 있다.

age 암호화와 base64URL 기반 파일명 정규화를 조합하면 일본어 이름이 포함된 데이터도 CLI에서 다루기 쉬워진다.