git-secret 使用教程

以下是一份详细的 git-secret 使用教程,包含常见场景的 Bash 代码示例:


1. 安装 git-secret

bash 复制代码
# Ubuntu/Debian
sudo apt-get install git-secret

# macOS (Homebrew)
brew install git-secret

# 其他 Linux (Snap)
sudo snap install git-secret

# 验证安装
git secret --version

2. 初始化仓库

bash 复制代码
cd your-git-repo
git secret init  # 创建 .gitsecret 目录

3. 生成 GPG 密钥(如果尚未生成)

bash 复制代码
gpg --gen-key  # 按提示生成密钥
gpg --list-secret-keys  # 查看生成的密钥

4. 基本场景:个人加密/解密

bash 复制代码
# 添加自己为可信用户(需使用GPG邮箱)
git secret tell your-email@example.com

# 添加要加密的文件
git secret add api-keys.txt

# 加密文件(生成 api-keys.txt.secret)
git secret hide

# 解密文件(需GPG私钥)
git secret reveal

5. 团队协作场景

bash 复制代码
# 添加团队成员(需他们的GPG公钥)
# 先导入对方的公钥
gpg --import teammate.pub

# 然后添加到git-secret
git secret tell teammate@company.com

# 重新加密所有文件
git secret hide

6. CI/CD 自动解密

bash 复制代码
# 在 CI 环境中设置 GPG 私钥
echo "$GPG_PRIVATE_KEY" | gpg --import
echo "passphrase" > /tmp/passphrase.txt

# 解密文件(非交互模式)
git secret reveal -p /tmp/passphrase.txt

# 安全清理
shred -u /tmp/passphrase.txt

7. 管理多个文件

bash 复制代码
# 添加多个文件
git secret add config/*.env

# 加密所有已添加文件
git secret hide

# 查看被管理的文件列表
git secret list

# 移除某个文件
git secret remove api-keys.txt

8. 用户权限管理

bash 复制代码
# 查看所有有权限的用户
git secret whoknows

# 移除用户权限
git secret killperson old-teammate@company.com

# 更新所有文件权限
git secret hide

9. 高级用法:修改密码

bash 复制代码
# 生成新密钥对
gpg --gen-key

# 添加新密钥到git-secret
git secret tell new-email@example.com

# 重新加密文件
git secret hide

10. 最佳实践

  1. .gitignore 配置 : 确保在 .gitignore 中添加:

    bash 复制代码
    echo "*.secret" >> .gitignore
    echo "!*.secret" >> .gitsecret/keys
  2. 密钥备份: 导出备份密钥:

    bash 复制代码
    gpg --export-secret-keys -a your-email@example.com > backup-private.key
  3. 审计日志: 查看加密历史:

    bash 复制代码
    git log --oneline --graph --decorate --name-only -- **/*.secret

常见问题排查

bash 复制代码
# 解密失败时检查密钥匹配
gpg --list-secret-keys

# 清除 GPG 代理缓存
gpgconf --kill gpg-agent

# 强制重新加密所有文件
git secret hide -f

记得在协作场景中定期更换密钥!