シェルによる自己解凍風暗号化ファイル

目次

1. このメモについて

自己解凍型の暗号ファイルをシェルスクリプトとして実装するサンプル。

暗号化ファイルの作成と解凍には外部コマンドを利用しているので本当の自己解凍型ではない。

2. 前提条件

OpenBSD7.3 上で動作確認をしている。 外部コマンドの存在とその仕様に依存しているため別環境では動作しない可能性がある。

3. コード

要点は以下の通り。

  • コメントに記載した例のように、スクリプト末尾に暗号化処理を施したファイル追記しておく
  • 解凍失敗した場合は最低限エラーメッセージを出力し 0 でないステータスで終了する
  • 解凍されたファイルは標準出力に出力される
#!/bin/sh

### About this script.
# This script is intended to be executed on OpenBSD.
# In other environment, this script is not tested at all.

### Example pipeline creates a self-extracting archive
# (cd /some/directory; tar cf - .) | \
#     gzip \ |
#     openssl enc -aes256 -e -k $SELF_EXTRACT_PASSWORD | \
#     uuencode -m encrypted_file >> /path/to/this/script

{
    tail -n+21 $0 | (
        uudecode -mp | \
            openssl enc -d -aes256 -k $SELF_EXTRACT_PASSWORD | \
            gzip -d)
} || { echo error: failed to extract the contained file 1>&2; exit 1; }

exit 0