# 加密

> SSE-C 与静态密钥 SSE-S3，以及它们保护什么。

---

LLMS 索引： [llms.txt](/zh/llms.txt)

---

本教程在网关与桶上配置静态密钥 `SSE-S3`（`AES256`），随后使用客户端提供的 `SSE-C` 客户密钥完成加密上传与读取。开始前请先完成[安装](/zh/docs/s3/operations/install/)与[使用 S3 SDK](/zh/docs/s3/tutorial/sdk/)。

## 配置静态密钥 SSE-S3 {#static-key-sse-s3}

在网关主机上生成一次 32 字节密钥文件（以下命令拒绝覆盖已存在的文件）：

```bash
sudo sh -c 'set -eu; umask 027; test ! -e /etc/silo/kms.key; set -C; { printf "silo-key-1:"; openssl rand -base64 32; } > /etc/silo/kms.key; chown root:silo /etc/silo/kms.key; chmod 0640 /etc/silo/kms.key'
```

请在数据库之外独立备份完整的密钥 ID（`silo-key-1`）与原始密钥字节，并将相同的 `/etc/silo/kms.key` 安全分发到连接该 PostgreSQL 数据库的所有网关。

在 `/etc/default/silo` 中添加 `MINIO_KMS_SECRET_KEY_FILE`（不要同时设置 `MINIO_KMS_SECRET_KEY`）：

```ini
MINIO_KMS_SECRET_KEY_FILE="/etc/silo/kms.key"
```

重启网关，在新桶 `encrypted-demo` 上开启默认 `AES256` 加密，并验证上传与下载：

```bash
sudo systemctl restart silo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api create-bucket --bucket encrypted-demo
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-bucket-encryption \
  --bucket encrypted-demo \
  --server-side-encryption-configuration '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"}}]}'
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api put-object \
  --bucket encrypted-demo --key hello.txt --body "$SILO_TUTORIAL_DIR/hello.txt"
aws --profile silo-admin --endpoint-url "$SILO_ENDPOINT" --region us-east-1 s3api get-object \
  --bucket encrypted-demo --key hello.txt "$SILO_TUTORIAL_DIR/encrypted.download.txt"
cmp "$SILO_TUTORIAL_DIR/hello.txt" "$SILO_TUTORIAL_DIR/encrypted.download.txt"
```

当静态密钥缺失或错误时，加解密请求会直接失败，网关绝不会退回明文存储。一旦丢失外部密钥，数据库中加密保存的对象将无法恢复，详见[备份与恢复](/zh/docs/s3/operations/backup/)。

当前不支持外部 KMS 与 `SSE-KMS`（`aws:kms`）。`silo_api` SQL 接口无法解密 `SSE-S3` 或 `SSE-C` 对象正文，且开启默认加密的桶会拒绝来自 SQL `put_object` 的明文写入。

## 使用客户端持有密钥的 SSE-C {#sse-c}

使用 `SSE-C` 时，客户端在每次 HTTPS 写入和读取请求中都必须传入同一个 32 字节客户密钥。将以下脚本保存为 `~/.local/share/silo-tutorial/sse-c.py`：

```python
import base64
import hashlib
import os
from pathlib import Path

import boto3
from botocore.config import Config

key_path = Path.home() / ".local/share/silo-tutorial/sse-c.key"
key_path.parent.mkdir(parents=True, exist_ok=True)
if key_path.exists():
    key = key_path.read_bytes()
else:
    key = os.urandom(32)
    descriptor = os.open(key_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "wb") as output:
        output.write(key)
if len(key) != 32:
    raise ValueError("SSE-C key must contain exactly 32 bytes")

session = boto3.Session(profile_name="silo-admin", region_name="us-east-1")
s3 = session.client(
    "s3",
    endpoint_url=os.environ["SILO_ENDPOINT"],
    verify=os.environ["AWS_CA_BUNDLE"],
    config=Config(signature_version="s3v4", s3={"addressing_style": "path"}),
)
customer_headers = {
    "SSECustomerAlgorithm": "AES256",
    "SSECustomerKey": base64.b64encode(key).decode("ascii"),
    "SSECustomerKeyMD5": base64.b64encode(
        hashlib.md5(key, usedforsecurity=False).digest()
    ).decode("ascii"),
}
s3.create_bucket(Bucket="customer-key-demo")
s3.put_object(
    Bucket="customer-key-demo",
    Key="private.txt",
    Body=b"protected by a client-held key\n",
    **customer_headers,
)
response = s3.get_object(
    Bucket="customer-key-demo", Key="private.txt", **customer_headers
)
try:
    assert response["Body"].read() == b"protected by a client-held key\n"
    print("SSE-C round trip succeeded")
finally:
    response["Body"].close()
```

运行 `"$HOME/.local/share/silo-tutorial/venv/bin/python" "$HOME/.local/share/silo-tutorial/sse-c.py"`，输出为 `SSE-C round trip succeeded`。

`SSE-C` 请求必须通过校验证书的 HTTPS 发送，明文 HTTP 下的 `SSE-C` 请求会被拒绝。请独立备份 `sse-c.key` 中的 32 字节原始密钥——网关的静态 `SSE-S3` 密钥无法解密 `SSE-C` 对象。

---

反链：

- [配置](/zh/docs/s3/reference/configuration/)
- [教程](/zh/docs/s3/tutorial/)
