> For the complete documentation index, see [llms.txt](https://docs.postgresql.tw/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.postgresql.tw/19/appendixes/contrib/pgcrypto/pgcrypto-password-hashing-funcs.md). Agents can also search and read this documentation through its [MCP server](https://docs.postgresql.tw/~gitbook/mcp).

# F.26.2. 密碼雜湊函式

## F.26.2. 密碼雜湊函式 [#](#pgcrypto-password-hashing-funcs) <a href="#pgcrypto-password-hashing-funcs" id="pgcrypto-password-hashing-funcs"></a>

函式 `crypt()` 與 `gen_salt()` 是專為雜湊密碼而設計的。`crypt()` 負責進行雜湊，`gen_salt()` 則為其準備演算法參數。

`crypt()` 中的演算法在以下幾個方面與一般的 MD5 或 SHA-1 雜湊演算法不同：

1. 它們很慢。由於資料量很小，這是讓暴力破解密碼變得困難的唯一方法。
2. 它們使用一個稱為*鹽值*（salt）的隨機值，讓密碼相同的使用者具有不同的加密後密碼。這也是防止演算法被反推的額外防禦。
3. 它們會在結果中包含演算法類型，因此以不同演算法雜湊的密碼可以並存。
4. 其中有些是可調適的——也就是說，當電腦變得更快時，你可以調整演算法使其變慢，而不會與現有密碼產生不相容。

[表 F.18](#pgcrypto-crypt-algorithms)列出 `crypt()` 函式所支援的演算法。

### 表 F.18. `crypt()` 支援的演算法 [#](#pgcrypto-crypt-algorithms) <a href="#pgcrypto-crypt-algorithms" id="pgcrypto-crypt-algorithms"></a>

| 演算法           | 密碼最大長度 | 可調適？ | 鹽值位元數 | 輸出長度 | 說明                                                                                            |
| ------------- | ------ | ---- | ----- | ---- | --------------------------------------------------------------------------------------------- |
| `bf`          | 72     | 是    | 128   | 60   | 以 Blowfish 為基礎，2a 變體                                                                          |
| `md5`         | 無限制    | 否    | 48    | 34   | 以 MD5 為基礎的 crypt                                                                              |
| `xdes`        | 8      | 是    | 24    | 20   | 擴充 DES                                                                                        |
| `des`         | 8      | 否    | 12    | 13   | 原始的 UNIX crypt                                                                                |
| `sha256crypt` | 無限制    | 是    | 最多 32 | 80   | 改編自公開的參考實作 [使用 SHA-256 與 SHA-512 的 Unix crypt](https://www.akkadia.org/drepper/SHA-crypt.txt) |
| `sha512crypt` | 無限制    | 是    | 最多 32 | 123  | 改編自公開的參考實作 [使用 SHA-256 與 SHA-512 的 Unix crypt](https://www.akkadia.org/drepper/SHA-crypt.txt) |

<br>

### F.26.2.1. `crypt()` [#](#pgcrypto-password-hashing-funcs-crypt) <a href="#pgcrypto-password-hashing-funcs-crypt" id="pgcrypto-password-hashing-funcs-crypt"></a>

```

crypt(password text, salt text) returns text
```

計算 *`password`* 的 crypt(3) 風格雜湊值。儲存新密碼時，你需要使用 `gen_salt()` 產生新的 *`salt`* 值。要檢查密碼時，請將儲存的雜湊值作為 *`salt`* 傳入，並測試結果是否與儲存的值相符。

設定新密碼的範例：

```

UPDATE ... SET pswhash = crypt('new password', gen_salt('md5'));
```

驗證的範例：

```

SELECT (pswhash = crypt('entered password', pswhash)) AS pswmatch FROM ... ;
```

若輸入的密碼正確，這會傳回 `true`。

### F.26.2.2. `gen_salt()` [#](#pgcrypto-password-hashing-funcs-gen-salt) <a href="#pgcrypto-password-hashing-funcs-gen-salt" id="pgcrypto-password-hashing-funcs-gen-salt"></a>

```

gen_salt(type text [, iter_count integer ]) returns text
```

產生新的隨機鹽值字串，供 `crypt()` 使用。鹽值字串也會告訴 `crypt()` 要使用哪一種演算法。

*`type`* 參數指定雜湊演算法。可接受的類型有：`des`、`xdes`、`md5`、`bf`、`sha256crypt` 與 `sha512crypt`。最後兩種 `sha256crypt` 與 `sha512crypt`，是以 `SHA-2` 為基礎的現代密碼雜湊。

對於具有迭代次數的演算法，*`iter_count`* 參數讓使用者指定迭代次數。次數越高，雜湊密碼所需的時間就越長，因此破解所需的時間也越長。不過，若次數過高，計算一次雜湊的時間可能長達數年——這有點不切實際。若省略 *`iter_count`* 參數，則使用預設的迭代次數。*`iter_count`* 的允許值取決於演算法，列於[表 F.19](#PGCRYPTO-ICFC-TABLE)。

**表 F.19. `crypt()` 的迭代次數**

| 演算法                        | 預設值  | 最小值  | 最大值       |
| -------------------------- | ---- | ---- | --------- |
| `xdes`                     | 725  | 1    | 16777215  |
| `bf`                       | 6    | 4    | 31        |
| `sha256crypt, sha512crypt` | 5000 | 1000 | 999999999 |

<br>

對於 `xdes`，還有一項額外限制：迭代次數必須是奇數。

要選擇適當的迭代次數，請考慮原始的 DES crypt 在設計上，是讓當時的硬體每秒執行 4 次雜湊。比每秒 4 次雜湊更慢，可能會降低可用性；比每秒 100 次雜湊更快，則可能太快了。

[表 F.20](#PGCRYPTO-HASH-SPEED-TABLE)概述不同雜湊演算法的相對緩慢程度。此表顯示，在假設密碼只包含小寫字母，或包含大小寫字母與數字的情況下，嘗試 8 個字元之密碼的所有字元組合需要多少時間。在 `crypt-bf` 項目中，斜線後面的數字是 `gen_salt` 的 *`iter_count`* 參數。

`sha256crypt` 與 `sha512crypt` 的預設 *`iter_count`* 為 `5000`，對現代硬體而言被認為過低，但可以調整以產生更強的密碼雜湊。除此之外，`sha256crypt` 與 `sha512crypt` 這兩種雜湊都被認為是安全的。

**表 F.20. 雜湊演算法速度**

| 演算法          | 每秒雜湊次數    | `[a-z]` 所需時間 | `[A-Za-z0-9]` 所需時間 | 相對於 `md5 hash` 的耗時 |
| ------------ | --------- | ------------ | ------------------ | ------------------ |
| `crypt-bf/8` | 1792      | 4 年          | 3927 年             | 100k               |
| `crypt-bf/7` | 3648      | 2 年          | 1929 年             | 50k                |
| `crypt-bf/6` | 7168      | 1 年          | 982 年              | 25k                |
| `crypt-bf/5` | 13504     | 188 天        | 521 年              | 12.5k              |
| `crypt-md5`  | 171584    | 15 天         | 41 年               | 1k                 |
| `crypt-des`  | 23221568  | 157.5 分鐘     | 108 天              | 7                  |
| `sha1`       | 37774272  | 90 分鐘        | 68 天               | 4                  |
| `md5`（雜湊）    | 150085504 | 22.5 分鐘      | 17 天               | 1                  |

<br>

附註：

* 所使用的機器為 Intel Mobile Core i3。
* `crypt-des` 與 `crypt-md5` 演算法的數據取自「John the Ripper」v1.6.38 的 `-test` 輸出。
* `md5 hash` 的數據來自 mdcrack 1.2。
* `sha1` 的數據來自 lcrack-20031130-beta。
* `crypt-bf` 的數據是使用一個對 1000 組 8 字元密碼執行迴圈的簡單程式測得的。如此便能呈現不同迭代次數下的速度。作為參考：`john -test` 顯示 `crypt-bf/5` 為每秒 13506 次迴圈。（結果之間的差異非常小，這與 `pgcrypto` 中的 `crypt-bf` 實作和「John the Ripper」所使用的是同一套實作相符。）

請注意，「嘗試所有組合」並不是符合實際的做法。密碼破解通常會借助字典進行，字典中既包含一般單字，也包含這些單字的各種變形。因此，即使是有點像單字的密碼，被破解的速度也可能遠比上述數字所示快得多；而一個 6 個字元、不像單字的密碼則可能逃過破解。也可能逃不過。

[返回 F.26. pgcrypto — 密碼學函式](https://docs.postgresql.tw/19/appendixes/contrib/pgcrypto.md#pgcrypto)

***

原文：[PostgreSQL 18.6 Documentation](https://www.postgresql.org/docs/18/pgcrypto.html)（原文版本：18.6；核對日期：2026-10-23）


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.postgresql.tw/19/appendixes/contrib/pgcrypto/pgcrypto-password-hashing-funcs.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
