> ## Documentation Index
> Fetch the complete documentation index at: https://docs.projectreal.gg/llms.txt
> Use this file to discover all available pages before exploring further.

# crypt.encrypt

> 使用从 Base64 解码的 key，通过 AES CBC、ECB 或 CTR 加密 Lua string 字节，然后返回 Base64 ciphertext 和 IV 结果。

<div className="real-function-page">
  ```lua theme={null}
  crypt.encrypt(data: string, key: string, iv?: string, mode?: "CBC" | "ECB" | "CTR" | "AES-CBC" | "AES-ECB" | "AES-CTR"): string | string | nil
  ```

  ## 参数

  <ParamField path={"data"} type={"string"} required>
    从 Lua string 读取的 plaintext 字节。
  </ParamField>

  <ParamField path={"key"} type={"string"} required>
    传递给 AES 前会被解码的 Base64 key。
  </ParamField>

  <ParamField path={"iv"} type={"string"}>
    CBC 或 CTR 的可选 Base64 IV。CBC 或 CTR 省略时，会生成新的 AES block size IV。
  </ParamField>

  <ParamField path={"mode"} type={"\"CBC\" | \"ECB\" | \"CTR\" | \"AES-CBC\" | \"AES-ECB\" | \"AES-CTR\""}>
    AES mode。如果存在 AES- prefix，会将其移除。默认值是 AES-CBC。CBC 和 ECB 使用 crypto library DEFAULT\_PADDING；CTR 不使用 padding。
  </ParamField>

  ## 返回值

  <ResponseField name={"ciphertext"} type={"string"}>
    Base64-encoded ciphertext。
  </ResponseField>

  <ResponseField name={"initializationVector"} type={"string | nil"}>
    CBC 和 CTR 的 Base64-encoded IV；ECB 为 nil。
  </ResponseField>

  ## 示例

  加密一个 Lua string，并使用返回的 IV 解密返回的 ciphertext。

  ```lua theme={null}
  local key = crypt.generatekey()
  local ciphertext, iv = crypt.encrypt("hello world", key)

  local plaintext = crypt.decrypt(ciphertext, key, iv)

  print(ciphertext)
  print(iv)
  print(plaintext)
  ```
</div>
