LoginSignup
13

More than 5 years have passed since last update.

git管理対象のファイルを暗号化して利用する

Last updated at Posted at 2015-12-24

一部のファイルのみ暗号化した状態でgit管理したい要件があったのでメモ

ほとんどこちらを参考にしています。
https://gist.github.com/shadowhand/873637

フィルタ処理用のファイルを作成する。

$ mkdir ~/.gitencrypt  
$ cd !$
$ touch clean_filter_openssl smudge_filter_openssl diff_filter_openssl  
$ chmod 755 *  

各ファイルの中身

<your-passphrase>は適宜書き換えること
※確認でアップロードしたリポジトリはpass:<your-passphrase>のままで実行しています。

clean_filter_openssl
#!/bin/bash
PASS_FIXED='pass:<your-passphrase>'
SALT_FIXED='XXXXX'
openssl enc -base64 -aes-256-cbc -pass $PASS_FIXED -S $SALT_FIXED

※2016/01/14 -saltを追加
単なる暗号化だけであれば自動でランダムなsaltにしてくれるので-S指定は不要だけど、-Sがないと新規にcheckoutした場合やindexを作り直した際にdiffはないのにmodifiedな状態になってしまうので、saltを固定しておいたほうがよさそう。

smudge_filter_openssl
#!/bin/bash
PASS_FIXED='pass:<your-passphrase>'
openssl enc -d -base64 -aes-256-cbc -pass $PASS_FIXED 2> /dev/null || cat
diff_filter_openssl
#!/bin/bash
PASS_FIXED='pass:<your-passphrase>'
openssl enc -d -base64 -aes-256-cbc -pass $PASS_FIXED -in "$1" 2> /dev/null || cat "$1"

フィルタ適用対象の設定を行う

今回は encrypy/*.yml というパターンにマッチするファイルに対して、checkin/checkout時とdiff時に
opensslフィルタを利用する設定をします。

cd \<repository\>  
touch .gitattributes  
echo 'encrypt/*.yml filter=openssl diff=openssl' >> .gitattributes

gitconfigにフィルタの設定をする

cd \<repository\>  
git config --add merge.renormalize true
git config --add filter.openssl.smudge ~/.gitencrypt/smudge_filter_openssl  
git config --add filter.openssl.clean ~/.gitencrypt/clean_filter_openssl  
git config --add diff.openssl.textconv ~/.gitencrypt/diff_filter_openssl  

確認する

上記をて起用してpushしたリポジトリを作成してpushしておく。

cloneすると暗号化されたままの状態でワーキングツリーにチェックアウトされる。

$ git clone https://github.com/ikeisuke/encrypted-sample  
$ cd encrypted-sample  
$ cat encrypt/encrypt.yml  
U2FsdGVkX1/Sw8ihiaafq7xpSrWqAWMSBXLexo8gw7Ciho2GRvcaF0f9uV12SwhE

フィルタ設定はリポジトリローカルの設定だったので、フィルタが適用されていない。
再度git configコマンドを利用してフィルタを追加する。

$ git config --add merge.renormalize true
$ git config --add filter.openssl.smudge ~/.gitencrypt/smudge_filter_openssl  
$ git config --add filter.openssl.clean ~/.gitencrypt/clean_filter_openssl  
$ git config --add diff.openssl.textconv ~/.gitencrypt/diff_filter_openssl  

git reset --hardでワーキングツリーをリセットすると暗号化解除されたファイルに書きかわる。

$ git reset --hard  
$ cat encrypt/encrypt.yml  
encrypted:
  - yml
  - encrypt

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13