> ## 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.

# Encryption Operation Guide

### i. Encryption Process Step-by-Step Explanation

The following are the steps for encryption operations:

1. Prepare <span className="text-blue-600 font-semibold"> business request parameters </span>.(All field definitions refer to the Pre-encryption Request Parameters section)
2. Serialize into a <span className="text-blue-600 font-semibold"> JSON </span> string.
3. Encrypt the JSON data using the <span className="text-blue-600 font-semibold"> RSA public key </span> provided by WaaS.
4. Perform <span className="text-blue-600 font-semibold"> Base64 </span> encoding of the encryption result.

### ii. Encryption Code Examples

The following are code examples for implementing encryption:

<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 {
      public static void main(String[] args) {
          try {
              // ===================== 1. Prepare business parameters =====================
              Map<String, Object> requestParams = new HashMap<>();
              requestParams.put("tenantUserId", "tenant_001");
              requestParams.put("chainName", "ETH");
              requestParams.put("symbol", "USDT");

              // ===================== 2. JSON serialization =====================
              // Perform serialization using JSON utility class, implementation can refer to sample code in relevant utility classes
              String jsonData = JsonUtils.toJson(requestParams);

              // ===================== 3. RSA public key encryption =====================
              // Use the public key provided by WaaS
              String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...";

              // Use RSA utility class for encryption, implementation can refer to sample code in relevant utility classes
              byte[] encryptedData = RSAUtils.encryptByPublicKey(
                  jsonData.getBytes(),
                  publicKey
              );

              // ===================== 4. Base64 encoding =====================
              // Perform encoding using Base64 utility class, implementation can refer to sample code in relevant utility classes
              String base64Data = Base64Util.encodeByte(encryptedData);

              // ===================== 5. Prepare HTTP request =====================
              // Create HTTP request headers
              HttpHeaders headers = new HttpHeaders();
              headers.add("X-API-KEY", "MERCHANT_123456"); // Merchant credentials
              headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); // Form format

              // Package request body
              MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
              body.add("data", base64Data); // Parameter name must be "data"

              // ===================== 6. Send API request =====================
              // Create and configure RestTemplate
              RestTemplate restTemplate = new RestTemplate();
              restTemplate.getMessageConverters().add(new FormHttpMessageConverter());

              // Send request and get response
              APIResult response = restTemplate.postForObject(
                  "https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress",
                  new HttpEntity<>(body, headers),
                  APIResult.class
              );

              // Process response, content can refer to response examples
              System.out.println("\nAPI response result:");
              System.out.println(response);

          } catch (Exception e) {
              System.err.println("\nError occurred during processing: " + 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');

  /**
  * Encrypted Request Example
  *
  * Demonstrates how to prepare request data, encrypt it, and send to WaaS API
  */
  class EncryptionExample {
    /**
     * Executes the complete encrypted request process
     * @param {Object} requestParams - Business request data
     * @param {string} publicKey - Base64 encoded public key
     * @param {string} apiKey - API key
     * @param {string} apiHost - API hostname
     * @param {string} apiPath - API path
     * @returns {Promise<string>} Encrypted API response data (Base64 string)
     */
    static async sendEncryptedRequest(requestParams, publicKey, apiKey, apiHost, apiPath) {
        try {
            console.log('Starting encrypted request example...');

            // ===================== 1. JSON Serialization =====================
            const jsonData = JsonUtils.toJson(requestParams);
            console.log('JSON data:', jsonData);

            // ===================== 2. RSA Public Key Encryption =====================
            console.log('Encrypting data with public key...');
            const encryptedData = RSAUtils.encryptByPublicKey(
                Buffer.from(jsonData, 'utf8'),
                publicKey
            );

            // ===================== 3. Base64 Encoding =====================
            const base64Data = Base64Util.encodeByte(encryptedData);
            console.log('Base64 encoding completed');

            // ===================== 4. Send API Request =====================
            console.log('Sending API request...');
            return await this._sendApiRequest(
                base64Data,
                apiKey,
                apiHost,
                apiPath
            );
        } catch (error) {
            throw new Error(`Encrypted request failed: ${error.message}`);
        }
    }

    /**
     * Sends HTTPS request to WaaS API
     * @param {string} base64Data - Base64 encoded encrypted data
     * @param {string} apiKey - API key
     * @param {string} apiHost - API hostname
     * @param {string} apiPath - API path
     * @returns {Promise<string>} Encrypted API response data
     */
    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 request failed, status code: ${res.statusCode}`));
                        }

                        const jsonResponse = JSON.parse(responseData);

                        if (!jsonResponse || typeof jsonResponse !== 'object') {
                            return reject(new Error('Invalid API response format'));
                        }

                        if (!jsonResponse.data) {
                            return reject(new Error('API response missing "data" field'));
                        }

                        resolve(jsonResponse.data);
                    } catch (error) {
                        reject(new Error(`Failed to parse API response: ${error.message}`));
                    }
                });
            });

            req.on('error', (error) => {
                reject(new Error(`Network request failed: ${error.message}`));
            });

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

    /**
     * Executes the complete example
     */
    static async executeExample() {
        try {
            // Configuration parameters
            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'
            };

            // Business request data
            const requestParams = {
                tenantUserId: "tenant_001",
                chainName: "TRON",
                symbol: "USDT"
            };

            console.log('Starting WaaS API encrypted request process...');

            // 1. Encrypt and send request
            const encryptedResponse = await this.sendEncryptedRequest(
                requestParams,
                config.PUBLIC_KEY,
                config.API_KEY,
                config.API_HOST,
                config.API_PATH
            );

            console.log('\n✅ Encrypted request successful!');
            console.log('Encrypted response data (Base64):');
            console.log(encryptedResponse);

            return encryptedResponse;
        } catch (error) {
            console.error('\n❌ Encrypted request failed:', error.message);
            throw error;
        }
    }
  }

  if (require.main === module) {
    (async () => {
        try {
            await EncryptionExample.executeExample();
        } catch (error) {
            console.error('Encrypted request example execution failed:', 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. Prepare business parameters =====================
      request_params = {
          "tenantUserId": "tenant_001",
          "chainName": "ETH",
          "symbol": "USDT"
      }

      # ===================== 2. JSON serialization =====================
      json_data = JsonUtils.to_json(request_params)

      # ===================== 3. RSA public key encryption =====================
      public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ..."

      # JSON data in Python is a string, needs to be converted to bytes
      json_bytes = json_data.encode('utf-8')

      # Encrypt using RSAUtils
      encrypted_data = RSAUtils.encrypt_by_public_key(
          json_bytes,
          public_key
      )

      # ===================== 4. Base64 encoding =====================
      base64_data = Base64Util.encode_byte(encrypted_data)

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

      payload = {'data': base64_data}

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

      # ===================== 7. Process response result =====================
      # Ensure API returned valid response
      response.raise_for_status()

      # Parse JSON response (assume returned format is JSON)
      api_result = response.json()

      print('\nAPI response result:')
      print(api_result)

  except Exception as e:
      print('\nError occurred during processing:')
      print(str(e))
      import traceback
      traceback.print_exc()

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