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

# 加密操作指南

### i. 加密流程步骤说明

以下是加密操作的步骤：

1. 准备<span className="text-blue-600 font-semibold"> 业务请求参数 </span>。（所有字段定义见加密前请求参数部分）
2. 序列化为 <span className="text-blue-600 font-semibold"> JSON </span> 字符串。
3. 使用 WaaS 提供的<span className="text-blue-600 font-semibold"> RSA公钥 </span> 加密 JSON 数据。
4. 对加密结果进行 <span className="text-blue-600 font-semibold"> Base64 </span> 编码。

### ii. 加密代码实例

以下是实现加密的代码示例：

<CodeGroup>
  ```java EncryptionExample.java theme={null}
  import org.springframework.util.LinkedMultiValueMap;
  import org.springframework.web.client.RestTemplate;
  import java.nio.charset.StandardCharsets;
  import java.util.HashMap;
  import java.util.Map;
  import org.springframework.http.HttpEntity;
  import org.springframework.http.HttpHeaders;
  import org.springframework.http.MediaType;
  import org.springframework.util.MultiValueMap;
  import org.springframework.http.converter.FormHttpMessageConverter;

  class EncryptionExample {

      class AddressVO {
          private String tenantUserId;
          private String chainName;
          private String address;

          // TODO: 补充 getter 和 setter 方法
          }

      public static void main(String[] args) {
          try {
              // ===================== 1. 准备业务参数 =====================
              Map<String, Object> requestParams = new HashMap<>();
              requestParams.put("tenantUserId", "tenant_001");
              requestParams.put("chainName", "ETH");
              requestParams.put("symbol", "USDT");

              // ===================== 2. JSON序列化 =====================
              // 使用 JSON 工具类进行序列化，具体实现可参考相关工具类中的示例代码。
              String jsonData = JsonUtils.toJson(requestParams);

              // ===================== 3. RSA公钥加密 =====================
              // 使用WaaS提供的公钥
              String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...";

              // 使用 RSA 工具类进行加密，具体实现可以参考相关工具类中的示例代码。
              byte[] encryptedData = RSAUtils.encryptByPublicKey(
                  jsonData.getBytes(),
                  publicKey
              );

              // ===================== 4. Base64编码 =====================
              // 使用Base64工具类进行编码，具体实现可以参考相关工具类中的示例代码。
              String base64Data = Base64Util.encodeByte(encryptedData);

              // ===================== 5. 准备HTTP请求 =====================
              // 创建HTTP请求头
              HttpHeaders headers = new HttpHeaders();
              headers.add("X-API-KEY", "MERCHANT_123456"); // 商户身份凭证
              headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // 表单格式

              // 封装请求体
              MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
              body.add("data", base64Data); // 参数名必须为"data"

              // ===================== 6. 发送API请求 =====================
              // 创建并配置RestTemplate
              RestTemplate restTemplate = new RestTemplate();
              restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

              // 发送请求并获取响应
              APIResult response = restTemplate.postForObject(
                  "https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress",
                  new HttpEntity<>(body, headers),
                  APIResult.class
              );

              // 处理响应，具体内容可参考响应示例。
              System.out.println("\nAPI响应结果:");
              System.out.println(response);

          } catch (Exception e) {
              System.err.println("\n处理过程中发生错误: " + e.getMessage());
              e.printStackTrace();
          }
      }
  }
  ```

  ```javascript EncryptionExample.js theme={null}
  const RSAUtils = require('./RSAUtils');
  const JsonUtils = require('./JsonUtils');
  const Base64Util = require('./Base64Util');
  const https = require('https');
  const querystring = require('querystring');

  /**
  * 加密请求示例
  *
  * 演示如何准备请求数据、加密并发送到 WaaS API
  */
  class EncryptionExample {
    /**
     * 执行完整的加密请求流程
     * @param {Object} requestParams - 业务请求数据
     * @param {string} publicKey - Base64 编码的公钥
     * @param {string} apiKey - API 密钥
     * @param {string} apiHost - API 主机名
     * @param {string} apiPath - API 路径
     * @returns {Promise<string>} 加密的 API 响应数据（Base64 字符串）
     */
    static async sendEncryptedRequest(requestParams, publicKey, apiKey, apiHost, apiPath) {
        try {
            console.log('开始执行加密请求示例...');

            // ===================== 1. JSON 序列化 =====================
            const jsonData = JsonUtils.toJson(requestParams);
            console.log('JSON 数据:', jsonData);

            // ===================== 2. RSA 公钥加密 =====================
            console.log('使用公钥加密数据...');
            const encryptedData = RSAUtils.encryptByPublicKey(
                Buffer.from(jsonData, 'utf8'),
                publicKey
            );

            // ===================== 3. Base64 编码 =====================
            const base64Data = Base64Util.encodeByte(encryptedData);
            console.log('Base64 编码完成');

            // ===================== 4. 发送 API 请求 =====================
            console.log('发送 API 请求...');
            return await this._sendApiRequest(
                base64Data,
                apiKey,
                apiHost,
                apiPath
            );
        } catch (error) {
            throw new Error(`加密请求失败: ${error.message}`);
        }
    }

    /**
     * 发送 HTTPS 请求到 WaaS API
     * @param {string} base64Data - Base64 编码的加密数据
     * @param {string} apiKey - API 密钥
     * @param {string} apiHost - API 主机名
     * @param {string} apiPath - API 路径
     * @returns {Promise<string>} API 响应的加密数据
     */
    static _sendApiRequest(base64Data, apiKey, apiHost, apiPath) {
        return new Promise((resolve, reject) => {
            const postData = querystring.stringify({ data: base64Data });

            const options = {
                hostname: apiHost,
                port: 443,
                path: apiPath,
                method: 'POST',
                headers: {
                    'X-API-KEY': apiKey,
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Content-Length': Buffer.byteLength(postData)
                }
            };

            const req = https.request(options, (res) => {
                let responseData = '';

                res.on('data', (chunk) => {
                    responseData += chunk;
                });

                res.on('end', () => {
                    try {
                        if (res.statusCode !== 200) {
                            return reject(new Error(`API 请求失败，状态码: ${res.statusCode}`));
                        }

                        const jsonResponse = JSON.parse(responseData);

                        if (!jsonResponse || typeof jsonResponse !== 'object') {
                            return reject(new Error('无效的 API 响应格式'));
                        }

                        if (!jsonResponse.data) {
                            return reject(new Error('API 响应缺少 data 字段'));
                        }

                        resolve(jsonResponse.data);
                    } catch (error) {
                        reject(new Error(`解析 API 响应失败: ${error.message}`));
                    }
                });
            });

            req.on('error', (error) => {
                reject(new Error(`网络请求失败: ${error.message}`));
            });

            req.write(postData);
            req.end();
        });
    }

    /**
     * 执行完整示例
     */
    static async executeExample() {
        try {
            // 配置参数
            const config = {
                PUBLIC_KEY: `YOUR_PUBLIC_KEY`,
                API_KEY: 'YOUR_API_KEY',
                API_HOST: 'waas2-out-api.powersafe-rel.cc',
                API_PATH: '/api/v1/api/user/getUserAddress'
            };

            // 业务请求数据
            const requestParams = {
                tenantUserId: "tenant_001",
                chainName: "TRON",
                symbol: "USDT"
            };

            console.log('开始 WaaS API 加密请求流程...');

            // 1. 加密并发送请求
            const encryptedResponse = await this.sendEncryptedRequest(
                requestParams,
                config.PUBLIC_KEY,
                config.API_KEY,
                config.API_HOST,
                config.API_PATH
            );

            console.log('\n✅ 加密请求成功！');
            console.log('加密响应数据 (Base64):');
            console.log(encryptedResponse);

            return encryptedResponse;
        } catch (error) {
            console.error('\n❌ 加密请求失败:', error.message);
            throw error;
        }
    }
  }


  if (require.main === module) {
    (async () => {
        try {
            await EncryptionExample.executeExample();
        } catch (error) {
            console.error('加密请求示例执行失败:', error.message);
        }
    })();
  }

  module.exports = EncryptionExample;
  ```

  ```python EncryptionExample.py theme={null}
  import requests
  from urllib.parse import urlencode
  from JsonUtils import JsonUtils
  from RSAUtils import RSAUtils
  from Base64Util import Base64Util

  def main():
    try:
        # ===================== 1. 准备业务参数 =====================
        request_params = {
            "tenantUserId": "tenant_001",
            "chainName": "ETH",
            "symbol": "USDT"
        }

        # ===================== 2. JSON序列化 =====================
        json_data = JsonUtils.to_json(request_params)

        # ===================== 3. RSA公钥加密 =====================
        public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ..."

        # Python中的JSON数据是字符串，需要转为bytes
        json_bytes = json_data.encode('utf-8')

        # 使用RSAUtils加密
        encrypted_data = RSAUtils.encrypt_by_public_key(
            json_bytes,
            public_key
        )

        # ===================== 4. Base64编码 =====================
        base64_data = Base64Util.encode_byte(encrypted_data)

        # ===================== 5. 准备HTTP请求 =====================
        headers = {
            'X-API-KEY': 'MERCHANT_123456',
            'Content-Type': 'application/x-www-form-urlencoded'
        }

        payload = {'data': base64_data}

        # ===================== 6. 发送API请求 =====================
        response = requests.post(
            'https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress',
            data=urlencode(payload),
            headers=headers
        )

        # ===================== 7. 处理响应结果 =====================
        # 确保API返回了有效响应
        response.raise_for_status()

        # 解析JSON响应（假设返回的是JSON格式）
        api_result = response.json()

        print('\nAPI响应结果:')
        print(api_result)

    except Exception as e:
        print('\n处理过程中发生错误:')
        print(str(e))
        import traceback
        traceback.print_exc()

  if __name__ == "__main__":
    main()
  ```
</CodeGroup>
