# 媒体流加密 (/zh-CN/realtime-media/rtc-server-sdk/build/encryption)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

## 功能描述 [#功能描述]

在实时音视频互动过程中，你需要对媒体流加密，从而保障用户的数据安全。RTC 服务端 SDK 提供内置加密方案。

## 实现方法 [#实现方法]

自 3.8.200 版本起，声网推荐使用 `AES_128_GCM2` 或 `AES_256_GCM2` 加密模式，并设置密钥和盐。3.8.200 之前的版本仅支持 128-bit SM4, ECB 模式。

参考以下步骤分别生成并设置密钥和盐。

:::warning[注意]
- 同一频道内所有用户必须使用相同的加密模式、密钥和盐。
- 相比于其他加密模式，`GCM2` 加密模式使用了安全性更高的密钥派生函数且支持盐。如果你选择其他加密模式，则只需设置加密模式和密钥。
:::

### 生成并设置密钥 [#生成并设置密钥]

1. 在你的服务端，参考以下命令通过 OpenSSL 随机生成 String 型、32 字节的密钥。

  ``` shell
  # 随机生成一个 string 型、32 字节的密钥，并将该密钥传入 enableEncryption 的 encryptionKey 参数。
  openssl rand -hex 32
  dba643c8ba6b6dc738df43d9fd624293b4b12d87a60f518253bd10ba98c48453
  ```

2. 客户端从服务端获取 String 型密钥，并在调用 `enableEncryption` 时传入 SDK。

### 生成并设置盐 [#生成并设置盐]

1. 在你的服务端，参考以下命令通过 OpenSSL 随机生成 Base64 编码、32 字节的盐。你也可以参考声网在 GitHub 上提供的 [C++ 示例代码](https://github.com/AgoraIO/Tools/blob/master/DynamicKey/AgoraDynamicKey/cpp/sample/RtcChannelEncryptionSaltSample.cpp)，在服务端随机生成 byte array 型的盐，然后转换成 Base64 编码。

  ``` shell
  # 随机生成一个 Base64 编码、32 字节的盐，并将该盐传入 enableEncryption 的 encryptionKdfSalt 参数。
  openssl rand -base64 32
  X5w9T+50kzxVOnkJKiY/lUk82/bES2kATOt3vBuGEDw=
  ```

2. 客户端从服务端获取 Base64 编码的盐。

3. 客户端将盐值从 Base64 编码解码为长度为 32 的 uint8_t 数组，然后在调用 `enableEncryption` 时传入 SDK。

#### 调用 enableEncryption 开启加密 [#调用-enableencryption-开启加密]

连接频道之前，调用 `enableEncryption` 开启内置加密。你还需要设置加密模式和秘钥。在同一频道的用户必须使用相同的加密模式和秘钥。

```cpp tab="C++" tabGroup="zh-cn-realtime-media-rtc-server-sdk-build-implement-core-features-encryption-1"
// Create EncryptionConfig object
agora::rtc::EncryptionConfig Config;
// 256-bit AES, GCM2 mode
Config.encryptionMode = agora::rtc::AES_256_GCM2;
// Set encryption key
Config.encryptionKey = options.encryptionKey.c_str();
// Set encryption salt
Config.encryptionKdfSalt = options.encryptionKdfSalt;
// Enable built-in encryption
if (connection->enableEncryption(options.encryptionMode, Config) < 0) {
    AG_LOG(ERROR, "Failed to enable encryption!");
}
AG_LOG(INFO, "Enable encryption successfully");
```

```java tab="Java" tabGroup="zh-cn-realtime-media-rtc-server-sdk-build-implement-core-features-encryption-1"
EncryptionConfig encryptionConfig = new EncryptionConfig();
encryptionConfig.setEncryptionMode(Constants.ENCRYPTION_MODE_AES_256_GCM);
encryptionConfig.setEncryptionKey(encryptionKey);
encryptionConfig.setEncryptionKdfSalt(encryptionKdfSalt);
int ret = conn.enableEncryption(encryptionMode, encryptionConfig);
if ( ret < 0) {
    System.out.printf("Failed to enable encryption!  \n" + ret);
    return;
}
System.out.printf("Enable encryption successfully!\n");
```
