# Encrypt Data

> 使用 AES 加密数据。

Source: https://docs.sommatic.ai/zh/nodes/crypto.encrypt/

- 标识: `crypto.encrypt`
- 类别: 身份
- 版本: 2.0.0
- 状态: 可用
- 执行方式: sync

使用 AES 加密数据。

## 配置

- `connection_id` (string, 可选): Sommatic AI credential resolved server-side (recommended). Accepts credentials of type `encryption-key`.
- `key` (string, 可选): 32 个字符的密钥
- `data` (any, 必填): 要加密的数据

## 输出端口

- `out` (默认): 加密后的数据
- `error`: 加密失败

## 输入契约

- `connection_id` (string, 可选)
- `key` (string, 可选)
- `data` (any, 必填)

## 输出契约

- `encrypted` (string, 可选): Hex 编码
- `algorithm` (string, 可选)

## 在表达式中

后续节点可通过 `$("Encrypt Data").item.json.<路径>` 读取此节点输出中的内容（请把 `Encrypt Data` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("Encrypt Data").item.json.encrypted` (string) = `"v1.sEZVicEyZQ3qzFNu.L_Y2ciTg_ZoET8aUKmDTuw.S…"`: Hex 编码
- `$("Encrypt Data").item.json.algorithm` (string) = `"aes-256-gcm"`


## 工作原理

使用 AES-256-GCM 加密任意 JSON 值，返回带版本的令牌 `v1.<iv>.<tag>.<ciphertext>`（base64url）。密钥来自 `encryption-key` 凭据（`connection_id`），也可使用字面量 `key`（不推荐）。

1. 解析配置。在 `data` 中使用纯表达式（如 `{{ $json.payment }}`）可保留值的类型；混合文本始终得到字符串。
2. 当 `data` 为 undefined、null 或空字符串时，以 `data is required` 从 `error` 输出。
3. 选择密钥：优先 `connection_id`，否则使用字面量 `key`。两者都没有时从 `error` 输出。
4. 将值包装为 `{ "v": data }`，使用随机 12 字节 IV 加密，并用点号连接版本、IV、认证标签和密文。
5. 从 `out` 返回 `{ encrypted, algorithm }`，`meta.crypto` 中为不含密钥的审计记录，`meta.warnings` 中为字面量密钥警告。

## 在工作流中

### 节点

```json
{
  "node_id": "node-encrypt-payment",
  "label": "Encrypt payment details",
  "operator_slug": "crypto.encrypt",
  "operator_version": "2.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "data": "{{ $json.payment }}"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "out",
  "data": {
    "encrypted": "v1.sEZVicEyZQ3qzFNu.L_Y2ciTg_ZoET8aUKmDTuw.SRzvsE_YNuaJMYT7_OF3xFIwECFqgqkxBnj3iyY",
    "algorithm": "aes-256-gcm"
  },
  "meta": {
    "crypto": {
      "op": "encrypt",
      "key_source": "credential",
      "alias": "connection",
      "credential_id": "pi-credential-xxxx",
      "algorithm": "aes-256-gcm",
      "ok": true
    },
    "warnings": []
  }
}
```

## 输出端口 (代码中的行为)

### `out`

值已加密。

```json
{
  "encrypted": "v1.sEZVicEyZQ3qzFNu.L_Y2ciTg_ZoET8aUKmDTuw.SRzvsE_YNuaJMYT7_OF3xFIwECFqgqkxBnj3iyY",
  "algorithm": "aes-256-gcm"
}
```

### `error`

缺少 `data`、未配置密钥，或凭据无法解析或没有可用密钥。

```json
{
  "error": "data is required"
}
```

## 代码中的行为

- `connection_id`: 优先于字面量 `key`。凭据在节点运行时于服务端解析，密钥不会出现在流程中。字符串密钥直接作为密钥使用；对象密钥必须包含 `key` 或 `secret`。
- `key`: 仅在 `connection_id` 为空时使用。接受 64 位十六进制字符、32 字节的 base64，其他文本则作为口令使用。字面量密钥可以使用，但会保存在流程、版本历史和 Git 中，并在 `meta.warnings` 中报告。
- `data`: 任意 JSON 值。对象、数组、数字和布尔值经 `crypto.decrypt` 解密后保持原类型。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `data is required` | `error` | `data` 为空，或其表达式未解析出任何值。`0` 和 `false` 是合法值。 |
| `A key is required: pass { credential: "<alias>" } (recommended) or { key }` | `error` | `connection_id` 和字面量密钥字段都未设置。请在 `connection_id` 中选择一个凭据。 |
| `credential binding 'connection' has no key usable for symmetric` | `error` | 凭据已解析，但其密钥为空，或是缺少可用字段的对象。请将密钥存为字符串，或存为包含本操作所读字段的对象（见 `connection_id`）。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据 id 不存在，或该工作流无权使用。请检查 id 和凭据类型。 |

## 说明与限制

- 每次运行都使用新的随机 IV，同一个值加密两次会得到不同的令牌。不要比较令牌是否相等，请改用 `crypto.hash`。
- 只有使用相同密钥的 `crypto.decrypt` 才能读取该令牌（`v1` 格式）。
- 从 `error` 端口输出不会使运行失败：引擎沿 `error` 上的连线继续；若没有连线，该分支直接结束。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "crypto.encrypt",
  "name": "Encrypt Data",
  "category": "identity",
  "version": "2.0.0",
  "description": "Encrypts data with AES-256-GCM (random IV, authenticated). Output: v1.<iv>.<tag>.<ciphertext>.",
  "capabilities": [
    "crypto",
    "encryption"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "Encryption key credential",
        "description": "Sommatic AI credential resolved server-side (recommended). Accepts credentials of type `encryption-key`.",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "encryption-key"
          ]
        }
      },
      "key": {
        "type": "string",
        "ui_widget": "password",
        "x-literal-secret": true,
        "description": "Encryption key (64 hex chars, base64 of 32 bytes, or a passphrase) as a literal. Allowed, but it is stored in the flow, its version history and Git: prefer connection_id."
      },
      "data": {
        "description": "Data to encrypt (any JSON value)"
      }
    },
    "required": [
      "data"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "key": {
        "type": "string"
      },
      "data": {}
    },
    "required": [
      "data"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "encrypted": {
        "type": "string",
        "description": "v1.<iv>.<tag>.<ciphertext> (base64url)"
      },
      "algorithm": {
        "type": "string"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Encrypted",
      "description": "Encrypted data",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Encryption failed",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "sync",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard"
  ],
  "tags": [
    "crypto",
    "security"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_veripass",
    "profile": {
      "name": "Veripass",
      "verified": true,
      "url": "https://me.veripass.com/veripass",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "Encryption key credential",
      "description": "Sommatic AI credential resolved server-side (recommended). Accepts credentials of type `encryption-key`.",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "encryption-key"
        ]
      }
    },
    "key": {
      "type": "string",
      "ui_widget": "password",
      "x-literal-secret": true,
      "description": "Encryption key (64 hex chars, base64 of 32 bytes, or a passphrase) as a literal. Allowed, but it is stored in the flow, its version history and Git: prefer connection_id."
    },
    "data": {
      "description": "Data to encrypt (any JSON value)"
    }
  },
  "required": [
    "data"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "key": {
      "type": "string"
    },
    "data": {}
  },
  "required": [
    "data"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "encrypted": {
      "type": "string",
      "description": "v1.<iv>.<tag>.<ciphertext> (base64url)"
    },
    "algorithm": {
      "type": "string"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Encrypted",
    "description": "Encrypted data",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Encryption failed",
    "is_default": false,
    "supports_condition": false
  }
]
```
