在無圖形介面的 Linux 伺服器/CI 環境中,Git 僅能透過 HTTPS 協定存取遠端倉庫。為避免每次輸入帳密,並保護明文憑證不落盤,本文建立一套 .netrc + GPG 加密 + Git credential helper 的安全認證體系。

vim ~/.netrc
# 內容 (權限務必 600)
machine git.example.com
login your@email.com
password your_strong_password
chmod 600 ~/.netrc
gpg --full-generate-key
# 選擇: (1) RSA and RSA → 3072 bits → 1y → 確認
# 輸入真實姓名、Email、註解、Passphrase (強建議設定)
gpg --list-keys
# 記下 pub 金鑰 ID (如 ABCD1234)
gpg -o ~/.netrc.gpg -e -r ABCD1234 ~/.netrc
# -e 加密, -r 指定接收者金鑰 ID
# 驗證解密
gpg -d ~/.netrc.gpg
# 輸入 Passphrase 後應顯示明文內容
# 刪除明文檔
shred -u ~/.netrc
# 方式一: 純記憶體快取 (預設 15 分鐘)
git config --global credential.helper 'cache --timeout=900'
# 方式二: 使用加密 .netrc.gpg (需 git-credential-netrc 腳本)
git config --global credential.helper 'netrc -f ~/.netrc.gpg -d'
# -d: 解密後刪除記憶體副本
注意:git-credential-netrc 需放置於 Git libexec/git-core/ 目錄 (通常 /usr/lib/git-core/),Git 2.2.2+ 內建支援。
[user]
name = Your Name
email = your@email.com
[core]
excludesfile = ~/.gitignore_global
[credential]
helper = netrc -f ~/.netrc.gpg -d
# helper = cache --timeout=900
git clone https://git.example.com:port/project/repo.git
# 首次會提示 GPG Passphrase (若使用 netrc helper)
# 後續操作無需輸入帳密
# ~/.netrc 可包含多組 machine
machine github.com
login user1
password ghp_xxx
machine gitlab.company.com
login user2
password glpat_yyy
# GPG 加密同樣處理,Git 會自動匹配 machine 對應憑證
gpg-agent 快取 (預設 10 分鐘)~/.netrc.gpg 權限設為 600,目錄 700git config --global credential.useHttpPath true 區分同主機不同路徑憑證此方案在「無法使用 SSH 金鑰」的受限環境 (企業防火牆僅開 443、代理伺服器、舊版 Git 伺服器) 下,提供兼具便利性與安全性的 HTTPS 認證解決方案。