# crypto/rsa

`crypto/rsa` 實作 RSA 公開金鑰演算法，用來做非對稱加密（OAEP）與數位簽章（PSS）。

## 這個套件做什麼

RSA 是一種「非對稱（asymmetric）」演算法：金鑰成對出現，一把是可以公開給任何人的公鑰（public key），一把是只有自己持有的私鑰（private key）。

可以把它想成一個掛鎖：你把打開的掛鎖（公鑰）發給大家，任何人都能把東西鎖進箱子，但只有你手上的鑰匙（私鑰）打得開。反過來，用私鑰「蓋章」（簽章）的文件，任何人都能用公鑰確認真的是你蓋的。

| 用途 | 誰用哪把金鑰 | 本套件的函式 |
| --- | --- | --- |
| 加密 | 傳送方用對方的公鑰加密，接收方用私鑰解密 | `EncryptOAEP`、`DecryptOAEP` |
| 簽章 | 簽署者用私鑰簽章，任何人用公鑰驗證 | `SignPSS`、`VerifyPSS` |

什麼時候用：

- 需要和既有系統（舊版 TLS、JWT 的 RS256／PS256、SSH 金鑰）互通時
- 只需要加密少量資料，例如一把隨機產生的對稱金鑰

和相近套件的差別：

- 新系統要做簽章，[crypto/ed25519](/pkg-crypto-ed25519) 或 [crypto/ecdsa](/pkg-crypto-ecdsa) 的金鑰更短、速度更快
- RSA 一次只能加密很短的資料（2048 位元金鑰配 SHA-256 最多 190 位元組）。大量資料應該用 [crypto/aes](/pkg-crypto-aes) 與 [crypto/cipher](/pkg-crypto-cipher) 的對稱加密，RSA 只負責保護那把對稱金鑰
- 要把金鑰存成檔案（PEM）或從檔案讀回，用 [crypto/x509](/pkg-crypto-x509) 與 [encoding/pem](/pkg-encoding-pem)

注意：套件裡的 PKCS #1 v1.5 加密（`EncryptPKCS1v15`、`DecryptPKCS1v15`）已被官方標記為棄用（Deprecated），有已知攻擊手法，新程式一律用 OAEP。簽章方面也優先選 PSS。

## 匯入

```go
import "crypto/rsa"
```

範例中常一起用到 [crypto/rand](/pkg-crypto-rand)（亂數來源）與 [crypto/sha256](/pkg-crypto-sha256)（雜湊函式）。

由於每次執行產生的金鑰都不同，以下範例只印長度與驗證結果這類不受金鑰影響的值。

## 常用 API

### GenerateKey

產生一把新的 RSA 私鑰，私鑰裡面已經內嵌對應的公鑰（`priv.PublicKey`）。`bits` 是金鑰長度，現在建議至少 2048，長期保存的資料可用 3072 或 4096。

Go 1.26 起，`random` 參數會被忽略，一律使用安全的系統亂數；仍然慣例傳入 `crypto/rand.Reader`。

簽名：
```go
func GenerateKey(random io.Reader, bits int) (*PrivateKey, error)
```

範例：
```go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("模數位元數:", priv.N.BitLen())
	fmt.Println("公開指數:", priv.E)
	fmt.Println("質因數個數:", len(priv.Primes))
	fmt.Println("金鑰有效:", priv.Validate() == nil)

	_, err = rsa.GenerateKey(rand.Reader, 512)
	fmt.Println("512 位元:", err)
}
```

輸出：
```text
模數位元數: 2048
公開指數: 65537
質因數個數: 2
金鑰有效: true
512 位元: crypto/rsa: 512-bit keys are insecure (see https://go.dev/pkg/crypto/rsa#hdr-Minimum_key_size)
```

注意：要求小於 1024 位元的金鑰會直接回傳錯誤；所有加解密、簽章函式遇到小於 1024 位元的金鑰也會回傳錯誤。

### PublicKey.Size

回傳模數的位元組數，也就是這把金鑰產生的密文與簽章長度。用來事先配置緩衝區或計算可加密的上限。

簽名：
```go
func (pub *PublicKey) Size() int
```

範例：
```go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"
)

func main() {
	for _, bits := range []int{2048, 3072} {
		priv, err := rsa.GenerateKey(rand.Reader, bits)
		if err != nil {
			fmt.Println("error:", err)
			return
		}
		pub := &priv.PublicKey
		fmt.Printf("%d 位元金鑰: Size() = %d 位元組\n", bits, pub.Size())
	}
}
```

輸出：
```text
2048 位元金鑰: Size() = 256 位元組
3072 位元金鑰: Size() = 384 位元組
```

### EncryptOAEP

用公鑰以 RSA-OAEP 加密一段短訊息。參數說明：

| 參數 | 說明 |
| --- | --- |
| `hash` | OAEP 內部使用的雜湊函式，`sha256.New()` 是合理預設；解密時必須用同一個 |
| `random` | 亂數來源，讓同一訊息每次加密的密文都不同 |
| `label` | 不加密、但會綁定在密文上的附加資料，用來區分用途；不需要可傳 `nil` |

可加密的最大長度是「`pub.Size()` − 2 × 雜湊長度 − 2」。

簽名：
```go
func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) ([]byte, error)
```

範例：
```go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"errors"
	"fmt"
	"strings"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	pub := &priv.PublicKey

	msg := []byte("訂單編號 A-1024")
	label := []byte("orders")

	c1, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, msg, label)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	c2, _ := rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, msg, label)

	fmt.Println("密文長度:", len(c1))
	fmt.Println("同一訊息加密兩次相同:", string(c1) == string(c2))

	maxLen := pub.Size() - 2*sha256.Size - 2
	fmt.Println("可加密的最大長度:", maxLen)

	_, err = rsa.EncryptOAEP(sha256.New(), rand.Reader, pub, []byte(strings.Repeat("x", maxLen+1)), nil)
	fmt.Println("超過上限:", errors.Is(err, rsa.ErrMessageTooLong))
}
```

輸出：
```text
密文長度: 256
同一訊息加密兩次相同: false
可加密的最大長度: 190
超過上限: true
```

注意：訊息超過上限會回傳 `rsa.ErrMessageTooLong`。需要加密較長的資料時，先用 AES-GCM 加密資料，再用 RSA 加密那把 AES 金鑰。

### DecryptOAEP

用私鑰解密 `EncryptOAEP` 產生的密文。`hash` 與 `label` 必須和加密時相同。`random` 參數是舊介面留下的，已被忽略，可以傳 `nil`。

簽名：
```go
func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) ([]byte, error)
```

範例：
```go
package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"errors"
	"fmt"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, &priv.PublicKey, []byte("訂單編號 A-1024"), []byte("orders"))
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	plain, err := rsa.DecryptOAEP(sha256.New(), nil, priv, ciphertext, []byte("orders"))
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("解密結果:", string(plain))

	_, err = rsa.DecryptOAEP(sha256.New(), nil, priv, ciphertext, []byte("invoices"))
	fmt.Println("label 不符:", err)
	fmt.Println("是 ErrDecryption:", errors.Is(err, rsa.ErrDecryption))
}
```

輸出：
```text
解密結果: 訂單編號 A-1024
label 不符: crypto/rsa: decryption error
是 ErrDecryption: true
```

注意：任何解密失敗（金鑰不對、密文被改、label 不符）都只回傳同一個籠統的 `rsa.ErrDecryption`，這是刻意不透露細節，避免攻擊者從錯誤訊息推敲資訊。

### SignPSS

用私鑰對「雜湊值」產生 RSA-PSS 簽章。簽章前要先自己把訊息雜湊（例如 `sha256.Sum256`），並把用的雜湊演算法（`crypto.SHA256`）一起傳入。`opts` 傳 `nil` 會使用合理的預設值。

PSS 簽章帶有隨機鹽值（salt），同一訊息每次簽出來都不同，但都能通過驗證。

簽名：
```go
func SignPSS(random io.Reader, priv *PrivateKey, hash crypto.Hash, digest []byte, opts *PSSOptions) ([]byte, error)
```

範例：
```go
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"fmt"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	digest := sha256.Sum256([]byte("轉帳 500 元給 Bob"))

	sig, err := rsa.SignPSS(rand.Reader, priv, crypto.SHA256, digest[:], nil)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	sig2, _ := rsa.SignPSS(rand.Reader, priv, crypto.SHA256, digest[:], nil)

	fmt.Println("簽章長度:", len(sig))
	fmt.Println("兩次簽章相同:", string(sig) == string(sig2))
}
```

輸出：
```text
簽章長度: 256
兩次簽章相同: false
```

### VerifyPSS

用公鑰驗證 PSS 簽章。回傳 `nil` 代表簽章有效；訊息被竄改或簽章不符時回傳 `rsa.ErrVerification`。驗證端要用和簽章端相同的雜湊演算法重新計算訊息的雜湊值。

簽名：
```go
func VerifyPSS(pub *PublicKey, hash crypto.Hash, digest []byte, sig []byte, opts *PSSOptions) error
```

範例：
```go
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"fmt"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	pub := &priv.PublicKey

	digest := sha256.Sum256([]byte("轉帳 500 元給 Bob"))
	sig, err := rsa.SignPSS(rand.Reader, priv, crypto.SHA256, digest[:], nil)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	err = rsa.VerifyPSS(pub, crypto.SHA256, digest[:], sig, nil)
	fmt.Println("原訊息驗證:", err == nil)

	tampered := sha256.Sum256([]byte("轉帳 5000 元給 Bob"))
	err = rsa.VerifyPSS(pub, crypto.SHA256, tampered[:], sig, nil)
	fmt.Println("竄改後驗證:", err)
}
```

輸出：
```text
原訊息驗證: true
竄改後驗證: crypto/rsa: verification error
```

### PrivateKey.Sign（crypto.Signer 介面）

`*rsa.PrivateKey` 實作了 [crypto](/pkg-crypto) 套件的 `crypto.Signer` [介面](/interfaces-basics)。寫成接收 `crypto.Signer` 的函式，就能同時支援 RSA、ECDSA、Ed25519 金鑰，這也是 `crypto/tls` 與 `crypto/x509` 內部的做法。

傳入 `*rsa.PSSOptions` 時會產生 PSS 簽章，此時 `Hash` 欄位必填。`SaltLength` 可設為 `rsa.PSSSaltLengthEqualsHash`（鹽值長度等於雜湊長度，相容性最好）或 `rsa.PSSSaltLengthAuto`。

簽名：
```go
func (priv *PrivateKey) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error)
```

範例：
```go
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"fmt"
)

func signWith(s crypto.Signer, msg []byte) ([]byte, error) {
	digest := sha256.Sum256(msg)
	return s.Sign(rand.Reader, digest[:], &rsa.PSSOptions{
		SaltLength: rsa.PSSSaltLengthEqualsHash,
		Hash:       crypto.SHA256,
	})
}

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	msg := []byte("release v1.2.0")
	sig, err := signWith(priv, msg)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	pub := priv.Public().(*rsa.PublicKey)
	digest := sha256.Sum256(msg)
	err = rsa.VerifyPSS(pub, crypto.SHA256, digest[:], sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
	fmt.Println("透過 crypto.Signer 簽章、驗證:", err == nil)
	fmt.Println("公鑰相同:", pub.Equal(&priv.PublicKey))
}
```

輸出：
```text
透過 crypto.Signer 簽章、驗證: true
公鑰相同: true
```

注意：若傳入的 `opts` 不是 `*rsa.PSSOptions`（例如直接傳 `crypto.SHA256`），產生的是 PKCS #1 v1.5 簽章，而不是 PSS。

### EncryptOAEPWithOptions 與 PrivateKey.Decrypt

Go 1.26 起提供 `EncryptOAEPWithOptions`，用 `OAEPOptions` 分別指定 OAEP 雜湊（`Hash`）與 MGF1 遮罩雜湊（`MGFHash`）。只有在要和「兩者使用不同雜湊」的外部系統互通時才需要它，一般情況用 `EncryptOAEP` 即可。

解密端用 `PrivateKey.Decrypt`（`crypto.Decrypter` 介面）搭配同一個 `*rsa.OAEPOptions`。

簽名：
```go
func EncryptOAEPWithOptions(random io.Reader, pub *PublicKey, msg []byte, opts *OAEPOptions) ([]byte, error)
func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
```

範例：
```go
package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	_ "crypto/sha256"
	_ "crypto/sha512"
	"fmt"
)

func main() {
	priv, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	opts := &rsa.OAEPOptions{
		Hash:    crypto.SHA512,
		MGFHash: crypto.SHA256,
		Label:   []byte("backup"),
	}

	ciphertext, err := rsa.EncryptOAEPWithOptions(rand.Reader, &priv.PublicKey, []byte("資料庫密碼"), opts)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	plain, err := priv.Decrypt(nil, ciphertext, opts)
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("解密結果:", string(plain))
}
```

輸出：
```text
解密結果: 資料庫密碼
```

注意：用 `crypto.SHA512` 這類 `crypto.Hash` 常數時，對應的雜湊套件必須被匯入（範例中以 `_` 空白匯入），否則執行時會 panic。

## 重點整理

- RSA 是非對稱演算法：公鑰加密、私鑰解密；私鑰簽章、公鑰驗證
- 加密用 `EncryptOAEP`／`DecryptOAEP`，簽章用 `SignPSS`／`VerifyPSS`；PKCS #1 v1.5 加密已棄用
- 金鑰至少 2048 位元；小於 1024 位元會直接回傳錯誤
- RSA 只能加密很短的資料，大量資料用 AES 加密、RSA 只保護 AES 金鑰
- 簽章前要先雜湊訊息，並把同一個雜湊演算法傳給簽章與驗證函式
- 金鑰的檔案格式（PEM、PKCS #8）由 [crypto/x509](/pkg-crypto-x509) 處理

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：crypto/rsa](https://pkg.go.dev/crypto/rsa)
- [Go 1.26.0 原始碼：src/crypto/rsa](https://github.com/golang/go/tree/go1.26.0/src/crypto/rsa)
