git-crypt 小记
版权声明:署名-非商业性使用-相同方式共享
@@ Tags: git-crypt
@@ Date: 2026-01-07
git-crypt 是一个用于git仓库中文件加密的工具,支持 git 仓库中的文件进行透明的加密和解密。
git-crypt 允许选择某些文件在 提交(commit) 时加密,在 检出(checkout) 时解密。
git-crypt 也会优雅地降级,因此没有秘钥的开发人员仍然可以克隆并提交到包含加密文件的存储库中。这允许您将秘密资料(如密钥或密码)存储在与代码相同的存储库中,而不需要锁定整个存储库。
安装
git clone https://github.com/AGWA/git-crypt.git
cd git-crypt
make
报错如下:
g++ -Wall -pedantic -Wno-long-long -O2 -std=c++11 -c -o util.o util.cpp
In file included from util.cpp:156:
util-unix.cpp: In member function ‘void temp_fstream::open(std::ios_base::openmode)’:
util-unix.cpp:79:38: 错误:‘mkstemp’ was not declared in this scope; did you mean ‘mkdtemp’?
79 | int fd = mkstemp(path);
| ^~~~~~~
| mkdtemp
util-unix.cpp: In function ‘std::string our_exe_path()’:
util-unix.cpp:135:51: 错误:‘realpath’在此作用域中尚未声明
135 | char* resolved_path_p = realpath(argv0, nullptr);
| ^~~~~~~~
make: *** [<内置>:util.o] 错误 1
参考: https://github.com/AGWA/git-crypt/issues/152
增加 -U__STRICT_ANSI__ 单独编译 util.cpp
g++ -Wall -pedantic -Wno-long-long -O2 -std=c++11 -U__STRICT_ANSI__ -c -o util.o util.cpp
make
# 安装到 /usr/local/bin
make install
# 安装到 /bin
make install PREFIX=
注意: 在 cygwin 下编译并在 windows 下运行时, 存在 bug.
使用
# 配置仓库以使用 git-crypt
# 此时会生成秘钥: .git/git-crypt/key/default
cd repo
git-crypt init
# 通过创建 .gitattributes 文件来指定要加密的文件:
echo "*.key filter=git-crypt diff=git-crypt" >> .gitattributes
echo "*.pem filter=git-crypt diff=git-crypt" >> .gitattributes
echo "secretdir/** filter=git-crypt diff=git-crypt" >> .gitattributes
# 使用 GPG 与他人(或自己)共享存储库
git-crypt add-gpg-user <USERID>
# 或者,您可以导出对称密钥 (.git/git-crypt/key/default)
# 如果不导出, 则一旦锁住存储库, 则无法解锁(令人深刻的教训😭)
git-crypt export-key /path/to/key
# 克隆包含加密文件的存储库后,使用 GPG 解锁
git-crypt unlock
# 或者使用对称密钥
git-crypt unlock /path/to/key
局限性
git-crypt 依赖于 Git 过滤器,而这些过滤器在设计之初并未考虑加密。
因此,对于需要加密仓库中大部分或全部文件的情况,git-crypt 并非最佳工具。
git-crypt 真正擅长的场景是:你的仓库大部分内容是公开的,但你需要加密少数几个文件(例如名为 *.key 的私钥文件,或包含 API 凭据的文件)。如果需要加密整个仓库,请考虑使用像 git-remote-gcrypt 这样的系统。
Comments ()