x/crypto

最後更新


golang.org/x/crypto 提供標準庫 crypto 沒有收錄的演算法與協定,本頁介紹密碼雜湊(bcrypt、argon2)、ChaCha20-Poly1305 加密與 SSH 用戶端。
  • Module:golang.org/x/crypto
  • 本書使用版本:v0.59.0(需要 Go 1.26 以上)

這個庫做什麼


標準庫已經有 AES、SHA-256、TLS 等常用密碼學工具(見 crypto),但有些常見需求不在其中:
子套件用途為什麼不用標準庫
bcrypt儲存使用者密碼標準庫沒有專門的密碼雜湊
argon2儲存使用者密碼、從密碼衍生金鑰同上,argon2id 是目前推薦的演算法
chacha20poly1305對稱式認證加密沒有 AES 硬體加速的裝置上比 AES-GCM 快
sshSSH 用戶端與伺服器標準庫沒有 SSH

先分清楚兩件事:雜湊密碼是單向的,只能比對、不能還原,用來存登入密碼;加密是雙向的,有金鑰就能解回原文,用來保護要再讀出來的資料。一般的 SHA-256 太快,攻擊者每秒能猜數十億次,不適合存密碼;bcrypt 與 argon2 是刻意設計得很慢的雜湊。

安裝


  1. go get golang.org/x/crypto@v0.59.0

本頁範例需要金鑰或鹽(salt)時都用 crypto/rand 產生,每次執行都不同,所以輸出只印長度、驗證結果等不受影響的內容。crypto/rand.Read 保證填滿且不會回傳錯誤(見 crypto/rand),範例因此省略錯誤檢查。

bcrypt:最常見的密碼雜湊


GenerateFromPassword 與 CompareHashAndPassword


bcrypt 把密碼轉成 60 字元的字串,裡面已經包含演算法版本、成本(cost)與隨機鹽,存進資料庫時只要一個欄位。
  • GenerateFromPassword(password, cost):產生雜湊。cost 每加 1,計算時間約加倍;bcrypt.DefaultCost 是 10
  • CompareHashAndPassword(hash, password):比對,相符回傳 nil
  • Cost(hash):讀出雜湊使用的 cost,可用來判斷舊資料是否需要升級

簽名:
  1. func GenerateFromPassword(password []byte, cost int) ([]byte, error)
  2. func CompareHashAndPassword(hashedPassword, password []byte) error
  3. func Cost(hashedPassword []byte) (int, error)

範例:
  1. package main
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "golang.org/x/crypto/bcrypt"
  7. )
  8. func main() {
  9. password := []byte("correct horse battery staple")
  10. hash, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
  11. if err != nil {
  12. fmt.Println("hash:", err)
  13. return
  14. }
  15. fmt.Println("length:", len(hash))
  16. fmt.Println("prefix:", string(hash[:7]))
  17. cost, _ := bcrypt.Cost(hash)
  18. fmt.Println("cost:", cost)
  19. fmt.Println("correct password:", bcrypt.CompareHashAndPassword(hash, password) == nil)
  20. err = bcrypt.CompareHashAndPassword(hash, []byte("wrong"))
  21. fmt.Println("wrong password:", errors.Is(err, bcrypt.ErrMismatchedHashAndPassword))
  22. again, _ := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
  23. fmt.Println("same hash twice:", string(hash) == string(again))
  24. _, err = bcrypt.GenerateFromPassword([]byte(strings.Repeat("a", 73)), bcrypt.DefaultCost)
  25. fmt.Println("73 bytes:", err)
  26. }

輸出:
  1. length: 60
  2. prefix: $2a$10$
  3. cost: 10
  4. correct password: true
  5. wrong password: true
  6. same hash twice: false
  7. 73 bytes: bcrypt: password length exceeds 72 bytes

同一個密碼雜湊兩次結果不同,因為每次的鹽都是隨機的,所以不能用「再雜湊一次後比較字串」的方式驗證,一律用 CompareHashAndPassword。
注意:bcrypt 只看密碼的前 72 個位元組,超過時 GenerateFromPassword 回傳 ErrPasswordTooLong。中文一字佔 3 個位元組,長密碼可能比想像中更快碰到上限;需要更長的輸入時改用 argon2。

argon2:推薦的新選擇


IDKey


Argon2 是密碼雜湊競賽的優勝者,argon2.IDKey 實作其中的 argon2id 變體,同時抵抗 GPU 暴力破解與旁通道攻擊,是新專案的建議選擇。它除了耗時,還會佔用大量記憶體,讓攻擊者難以大量平行猜測。
簽名:
  1. func IDKey(password, salt []byte, time, memory uint32, threads uint8, keyLen uint32) []byte

參數意思
time走訪記憶體的次數
memory記憶體用量,單位 KiB(64*1024 是 64 MiB)
threads平行執行緒數
keyLen輸出位元組數

官方文件引用 RFC 9106 的兩組建議:記憶體充足時 time=1, memory=2*1024*1024(約 2 GiB);記憶體較少時 time=3, memory=64*1024,兩者都是 threads=4。
和 bcrypt 不同,IDKey 只回傳原始位元組,鹽與參數要自己保存。常見做法是編成 $argon2id$v=19$m=...,t=...,p=...$鹽$雜湊 格式的字串。範例第一行用固定的鹽,所以結果可重現;後面示範實際儲存與驗證的流程。
範例:
  1. package main
  2. import (
  3. "crypto/rand"
  4. "crypto/subtle"
  5. "encoding/base64"
  6. "fmt"
  7. "strings"
  8. "golang.org/x/crypto/argon2"
  9. )
  10. const (
  11. argonTime = 3
  12. argonMemory = 64 * 1024
  13. argonThreads = 4
  14. argonKeyLen = 32
  15. )
  16. func hashPassword(password string) string {
  17. salt := make([]byte, 16)
  18. rand.Read(salt)
  19. key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
  20. return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
  21. argon2.Version, argonMemory, argonTime, argonThreads,
  22. base64.RawStdEncoding.EncodeToString(salt),
  23. base64.RawStdEncoding.EncodeToString(key))
  24. }
  25. func verify(encoded, password string) bool {
  26. parts := strings.Split(encoded, "$")
  27. if len(parts) != 6 {
  28. return false
  29. }
  30. salt, err := base64.RawStdEncoding.DecodeString(parts[4])
  31. if err != nil {
  32. return false
  33. }
  34. want, err := base64.RawStdEncoding.DecodeString(parts[5])
  35. if err != nil {
  36. return false
  37. }
  38. got := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, uint32(len(want)))
  39. return subtle.ConstantTimeCompare(got, want) == 1
  40. }
  41. func main() {
  42. fixed := argon2.IDKey([]byte("password"), []byte("fixed-salt-16byt"), 1, 64*1024, 4, 16)
  43. fmt.Printf("fixed salt key: %x\n", fixed)
  44. encoded := hashPassword("s3cret")
  45. fmt.Println("prefix:", strings.Join(strings.Split(encoded, "$")[:4], "$"))
  46. fmt.Println("verify s3cret:", verify(encoded, "s3cret"))
  47. fmt.Println("verify guess:", verify(encoded, "guess"))
  48. }

輸出:
  1. fixed salt key: 95eeb46afae29640eb1c79928a204f1b
  2. prefix: $argon2id$v=19$m=65536,t=3,p=4
  3. verify s3cret: true
  4. verify guess: false

注意:比較雜湊要用 crypto/subtle.ConstantTimeCompare,不要用 bytes.Equal;後者遇到第一個不同的位元組就返回,攻擊者可以從回應時間推測內容。鹽每個密碼都要用 crypto/rand 另外產生,至少 16 個位元組。

chacha20poly1305:認證加密


New、Seal 與 Open


ChaCha20-Poly1305 是一種 AEAD(Authenticated Encryption with Associated Data,附帶認證的加密):加密的同時產生驗證標籤,解密時若密文被改過一個位元就會失敗。它實作標準庫的 cipher.AEAD 介面,用法和 AES-GCM 相同。
  • 金鑰:32 個位元組(chacha20poly1305.KeySize)
  • nonce:12 個位元組,同一把金鑰絕對不能重複使用同一個 nonce
  • 附加資料(additional data):不加密但受保護的資料,例如訊息編號;解密時必須提供相同內容

簽名:
  1. func New(key []byte) (cipher.AEAD, error)
  2. Seal(dst, nonce, plaintext, additionalData []byte) []byte
  3. Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)

範例:
  1. package main
  2. import (
  3. "crypto/rand"
  4. "fmt"
  5. "golang.org/x/crypto/chacha20poly1305"
  6. )
  7. func main() {
  8. key := make([]byte, chacha20poly1305.KeySize)
  9. rand.Read(key)
  10. aead, err := chacha20poly1305.New(key)
  11. if err != nil {
  12. fmt.Println("new:", err)
  13. return
  14. }
  15. nonce := make([]byte, aead.NonceSize())
  16. rand.Read(nonce)
  17. plaintext := []byte("轉帳 1000 元給 Bob")
  18. header := []byte("msg-id:42")
  19. ciphertext := aead.Seal(nil, nonce, plaintext, header)
  20. fmt.Println("nonce size:", aead.NonceSize(), "overhead:", aead.Overhead())
  21. fmt.Println("plaintext:", len(plaintext), "ciphertext:", len(ciphertext))
  22. opened, err := aead.Open(nil, nonce, ciphertext, header)
  23. fmt.Println("open:", string(opened), err)
  24. ciphertext[0] ^= 1
  25. _, err = aead.Open(nil, nonce, ciphertext, header)
  26. fmt.Println("tampered:", err)
  27. ciphertext[0] ^= 1
  28. _, err = aead.Open(nil, nonce, ciphertext, []byte("msg-id:43"))
  29. fmt.Println("wrong header:", err)
  30. }

輸出:
  1. nonce size: 12 overhead: 16
  2. plaintext: 22 ciphertext: 38
  3. open: 轉帳 1000 元給 Bob <nil>
  4. tampered: chacha20poly1305: message authentication failed
  5. wrong header: chacha20poly1305: message authentication failed

密文比明文多 16 個位元組,那就是驗證標籤(Overhead())。不論是密文被改、還是附加資料不符,Open 都回傳同一個錯誤,不會透露是哪裡出錯。

NewX:用隨機 nonce 的 XChaCha20-Poly1305


12 位元組的 nonce 用隨機產生,加密次數一多就有重複的風險。NewX 建立 XChaCha20-Poly1305,nonce 加長到 24 個位元組,隨機產生也不必擔心碰撞,是最省心的寫法。慣例是把 nonce 放在密文前面一起存。
簽名:
  1. func NewX(key []byte) (cipher.AEAD, error)

範例:
  1. package main
  2. import (
  3. "crypto/rand"
  4. "fmt"
  5. "golang.org/x/crypto/chacha20poly1305"
  6. )
  7. func encrypt(key, plaintext []byte) ([]byte, error) {
  8. aead, err := chacha20poly1305.NewX(key)
  9. if err != nil {
  10. return nil, err
  11. }
  12. nonce := make([]byte, aead.NonceSize(), aead.NonceSize()+len(plaintext)+aead.Overhead())
  13. rand.Read(nonce)
  14. return aead.Seal(nonce, nonce, plaintext, nil), nil
  15. }
  16. func decrypt(key, message []byte) ([]byte, error) {
  17. aead, err := chacha20poly1305.NewX(key)
  18. if err != nil {
  19. return nil, err
  20. }
  21. if len(message) < aead.NonceSize() {
  22. return nil, fmt.Errorf("message too short")
  23. }
  24. nonce, ciphertext := message[:aead.NonceSize()], message[aead.NonceSize():]
  25. return aead.Open(nil, nonce, ciphertext, nil)
  26. }
  27. func main() {
  28. key := make([]byte, chacha20poly1305.KeySize)
  29. rand.Read(key)
  30. msg, err := encrypt(key, []byte("hello"))
  31. if err != nil {
  32. fmt.Println("encrypt:", err)
  33. return
  34. }
  35. fmt.Println("nonce size:", chacha20poly1305.NonceSizeX, "message length:", len(msg))
  36. plain, err := decrypt(key, msg)
  37. fmt.Println("decrypt:", string(plain), err)
  38. _, err = chacha20poly1305.NewX([]byte("short key"))
  39. fmt.Println("bad key:", err)
  40. }

輸出:
  1. nonce size: 24 message length: 45
  2. decrypt: hello <nil>
  3. bad key: chacha20poly1305: bad key length

訊息長度 45 = nonce 24 + 明文 5 + 標籤 16。Seal 的第一個參數 dst 傳入 nonce,結果就會接在 nonce 後面,不必另外複製。
注意:金鑰長度不是 32 位元組時 New、NewX 回傳錯誤。不要把密碼字串直接當金鑰,要先用 argon2.IDKey 衍生出 32 位元組。

ssh:SSH 用戶端


Dial、NewSession 與 Output


ssh 套件可以寫出連到遠端主機、執行指令的程式,例如部署工具。流程是:
  1. 準備 ssh.ClientConfig:使用者、認證方式、主機金鑰驗證
  2. ssh.Dial 建立連線,得到 *ssh.Client
  3. client.NewSession() 開一個工作階段(session),一個 session 只能執行一個指令
  4. session.Output(cmd) 執行並取得標準輸出

認證方式常用 ssh.PublicKeys(signer)(金鑰)或 ssh.Password(...)(密碼)。實際讀取私鑰檔的寫法是 ssh.ParsePrivateKey(pemBytes) 取得 Signer。
簽名:
  1. func Dial(network, addr string, config *ClientConfig) (*Client, error)
  2. func (c *Client) NewSession() (*Session, error)
  3. func (s *Session) Output(cmd string) ([]byte, error)
  4. func PublicKeys(signers ...Signer) AuthMethod
  5. func FixedHostKey(key PublicKey) HostKeyCallback

為了讓範例不依賴外部主機,startTestServer 用同一個套件在本機起一個只會回覆指令字串的迷你 SSH 伺服器;連真實主機時只需要 main 裡的用戶端部分,把位址換成 "host:22"。
範例:
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "encoding/binary"
  7. "fmt"
  8. "net"
  9. "time"
  10. "golang.org/x/crypto/ssh"
  11. )
  12. func startTestServer(authorized ssh.PublicKey) (addr string, hostKey ssh.PublicKey, err error) {
  13. _, hostPriv, err := ed25519.GenerateKey(rand.Reader)
  14. if err != nil {
  15. return "", nil, err
  16. }
  17. hostSigner, err := ssh.NewSignerFromKey(hostPriv)
  18. if err != nil {
  19. return "", nil, err
  20. }
  21. config := &ssh.ServerConfig{
  22. PublicKeyCallback: func(meta ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
  23. if meta.User() == "gopher" && bytes.Equal(key.Marshal(), authorized.Marshal()) {
  24. return nil, nil
  25. }
  26. return nil, fmt.Errorf("unknown key for %s", meta.User())
  27. },
  28. }
  29. config.AddHostKey(hostSigner)
  30. ln, err := net.Listen("tcp", "127.0.0.1:0")
  31. if err != nil {
  32. return "", nil, err
  33. }
  34. go func() {
  35. for {
  36. conn, err := ln.Accept()
  37. if err != nil {
  38. return
  39. }
  40. go serveConn(conn, config)
  41. }
  42. }()
  43. return ln.Addr().String(), hostSigner.PublicKey(), nil
  44. }
  45. func serveConn(conn net.Conn, config *ssh.ServerConfig) {
  46. _, chans, reqs, err := ssh.NewServerConn(conn, config)
  47. if err != nil {
  48. return
  49. }
  50. go ssh.DiscardRequests(reqs)
  51. for newCh := range chans {
  52. if newCh.ChannelType() != "session" {
  53. newCh.Reject(ssh.UnknownChannelType, "only session")
  54. continue
  55. }
  56. ch, requests, err := newCh.Accept()
  57. if err != nil {
  58. continue
  59. }
  60. go func() {
  61. defer ch.Close()
  62. for req := range requests {
  63. if req.Type != "exec" || len(req.Payload) < 4 {
  64. req.Reply(false, nil)
  65. continue
  66. }
  67. cmd := string(req.Payload[4:])
  68. req.Reply(true, nil)
  69. fmt.Fprintf(ch, "you ran %q\n", cmd)
  70. status := make([]byte, 4)
  71. binary.BigEndian.PutUint32(status, 0)
  72. ch.SendRequest("exit-status", false, status)
  73. return
  74. }
  75. }()
  76. }
  77. }
  78. func main() {
  79. _, clientPriv, err := ed25519.GenerateKey(rand.Reader)
  80. if err != nil {
  81. fmt.Println("keygen:", err)
  82. return
  83. }
  84. clientSigner, err := ssh.NewSignerFromKey(clientPriv)
  85. if err != nil {
  86. fmt.Println("signer:", err)
  87. return
  88. }
  89. addr, hostKey, err := startTestServer(clientSigner.PublicKey())
  90. if err != nil {
  91. fmt.Println("server:", err)
  92. return
  93. }
  94. config := &ssh.ClientConfig{
  95. User: "gopher",
  96. Auth: []ssh.AuthMethod{ssh.PublicKeys(clientSigner)},
  97. HostKeyCallback: ssh.FixedHostKey(hostKey),
  98. Timeout: 5 * time.Second,
  99. }
  100. client, err := ssh.Dial("tcp", addr, config)
  101. if err != nil {
  102. fmt.Println("dial:", err)
  103. return
  104. }
  105. defer client.Close()
  106. session, err := client.NewSession()
  107. if err != nil {
  108. fmt.Println("session:", err)
  109. return
  110. }
  111. defer session.Close()
  112. out, err := session.Output("uname -s")
  113. fmt.Printf("output: %serr: %v\n", out, err)
  114. config.User = "intruder"
  115. _, err = ssh.Dial("tcp", addr, config)
  116. fmt.Println("wrong user:", err)
  117. }

輸出:
  1. output: you ran "uname -s"
  2. err: <nil>
  3. wrong user: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

注意:HostKeyCallback 是必填欄位,用來確認連到的真的是你的主機,防止中間人攻擊。ssh.InsecureIgnoreHostKey() 會接受任何主機金鑰,官方文件註明不應用於正式環境;正式程式請用下一節的 knownhosts。

knownhosts:驗證主機金鑰


golang.org/x/crypto/ssh/knownhosts 讀取 OpenSSH 格式的 known_hosts 檔,產生可以直接放進 ClientConfig.HostKeyCallback 的函式。實務上路徑通常是 ~/.ssh/known_hosts。
簽名:
  1. func New(files ...string) (ssh.HostKeyCallback, error)
  2. func Line(addresses []string, key ssh.PublicKey) string

驗證失敗時回傳 *knownhosts.KeyError:Want 不為空表示主機金鑰變了(可能是攻擊,也可能是主機重灌);Want 為空表示這台主機還沒登錄過。
範例:
  1. package main
  2. import (
  3. "crypto/ed25519"
  4. "crypto/rand"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "golang.org/x/crypto/ssh"
  11. "golang.org/x/crypto/ssh/knownhosts"
  12. )
  13. func newHostKey() ssh.PublicKey {
  14. pub, _, _ := ed25519.GenerateKey(rand.Reader)
  15. key, _ := ssh.NewPublicKey(pub)
  16. return key
  17. }
  18. func main() {
  19. dir, err := os.MkdirTemp("", "knownhosts")
  20. if err != nil {
  21. fmt.Println("mkdir:", err)
  22. return
  23. }
  24. defer os.RemoveAll(dir)
  25. trusted := newHostKey()
  26. path := filepath.Join(dir, "known_hosts")
  27. line := knownhosts.Line([]string{"git.example.com"}, trusted) + "\n"
  28. if err := os.WriteFile(path, []byte(line), 0o600); err != nil {
  29. fmt.Println("write:", err)
  30. return
  31. }
  32. callback, err := knownhosts.New(path)
  33. if err != nil {
  34. fmt.Println("knownhosts:", err)
  35. return
  36. }
  37. remote := &net.TCPAddr{IP: net.IPv4(192, 0, 2, 10), Port: 22}
  38. fmt.Println("trusted key:", callback("git.example.com:22", remote, trusted))
  39. err = callback("git.example.com:22", remote, newHostKey())
  40. var keyErr *knownhosts.KeyError
  41. if errors.As(err, &keyErr) {
  42. fmt.Println("changed key: mismatch, known entries =", len(keyErr.Want))
  43. }
  44. err = callback("new.example.com:22", remote, newHostKey())
  45. if errors.As(err, &keyErr) {
  46. fmt.Println("unknown host: known entries =", len(keyErr.Want))
  47. }
  48. }

輸出:
  1. trusted key: <nil>
  2. changed key: mismatch, known entries = 1
  3. unknown host: known entries = 0

範例把檔案建在 os.MkdirTemp 的暫存目錄並在結束時刪除。

不要使用的子套件


下列子套件或 API 在 v0.59.0 原始碼中標記為 Deprecated,新程式不要使用:
子套件/API原因與替代
blowfish、cast5、tea、xtea老舊分組密碼,改用標準庫 crypto/aes(搭配 crypto/cipher 的 GCM)或 chacha20poly1305
twofish舊式密碼,改用 crypto/aes
md4、ripemd160雜湊已被破解或過時,改用 crypto/sha256、crypto/sha3
bn256安全強度已降低
poly1305低階 MAC,容易誤用,改用 chacha20poly1305
salsa20/salsa暴露不安全的低階運算,改用 chacha20poly1305
curve25519.ScalarMult改用 curve25519.X25519 或標準庫 crypto/ecdh
ssh/terminal已搬到 golang.org/x/term
ssh/test僅供內部測試
ssh 的 DSA 金鑰與憑證演算法常數不再支援 DSA
acme 中 RFC 8555 之前的舊版 API改用 CreateCertFromOrder 等新流程

另外有幾個子套件沒有標記 Deprecated,但說明中寫明只是標準庫的包裝且已凍結(frozen,不再加新功能):ed25519、sha3、hkdf、pbkdf2、curve25519。新程式直接用標準庫的 crypto/ed25519、crypto/sha3、crypto/hkdf、crypto/pbkdf2、crypto/ecdh 即可。

重點整理


  • 存使用者密碼用 bcrypt 或 argon2id,不要用 SHA-256;驗證 bcrypt 一律用 CompareHashAndPassword
  • bcrypt 只看前 72 個位元組;argon2 要自己保存鹽與參數,比對用 subtle.ConstantTimeCompare
  • chacha20poly1305 是 AEAD:同一把金鑰不可重複 nonce,想隨機產生 nonce 就用 NewX
  • SSH 用戶端要設定 HostKeyCallback,正式環境用 knownhosts,不要用 InsecureIgnoreHostKey
  • 依原始碼的 Deprecated 標記避開舊演算法;已有標準庫版本的子套件直接用標準庫

資料來源