跳转到主要内容

c. 解密操作指南

本指南详细说明了如何解密从 WaaS API 获取的加密响应数据。

i. 解密流程步骤说明

以下是解密操作的步骤说明:
  1. 从 API 响应中获取 加密数据
  2. 对数据进行 Base64 解码
  3. 使用 RSA公钥 进行解密
  4. 将解密结果解析为 业务对象

ii.解密代码实例

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

        // TODO: Add getter and setter methods
    }
    public static void main(String[] args) {
        try {
            // ===================== 1. 获取API响应 =====================
            // 发送API请求并获取响应
            APIResult<String> response = restTemplate.postForObject(
                "https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress",
                httpEntity,
                APIResult.class
            );

            // 提取加密数据(确保响应格式与API一致)
            String encryptedData = response.getData();

            // ===================== 2. Base64解码 =====================
            // 使用Base64工具类进行解码(具体实现参考工具类)
            byte[] decodedBytes = Base64Util.decodeString(encryptedData);

            // ===================== 3. RSA公钥解密 =====================
            // 使用与请求相同的公钥
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...";

            // 执行RSA解密
            byte[] decryptedBytes = RSAUtils.decryptByPublicKey(
                decodedBytes,
                publicKey
            );

            // ===================== 4. 解析业务对象 =====================
            // 将解密后的JSON数据转换为业务对象
            AddressVO address = JsonUtils.fromJson(
                new String(decryptedBytes, StandardCharsets.UTF_8),
                AddressVO.class
            );

            // ===================== 5. 使用解密数据 =====================
            System.out.println("解析得到的地址信息:");
            System.out.println("商户用户ID: " + address.getTenantUserId());
            System.out.println("链名称: " + address.getChainName());
            System.out.println("钱包地址: " + address.getAddress());

        } catch (Exception e) {
            System.err.println("\n解密过程中发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
const RSAUtils = require('./RSAUtils');
const JsonUtils = require('./JsonUtils');
const Base64Util = require('./Base64Util');

/**
* 解密响应示例
*
* 演示如何解密并解析 WaaS API 的响应
*/
class DecryptionExample {
  /**
   * 解密并解析 API 响应
   * @param {string} encryptedResponse - Base64 编码的加密响应
   * @param {string} publicKey - Base64 编码的公钥
   * @returns {Object} 解析后的业务对象
   */
  static decryptResponse(encryptedResponse, publicKey) {
      try {
          console.log('开始执行解密响应示例...');

          // ===================== 1. Base64 解码 =====================
          console.log('Base64 解码响应...');
          const decodedBytes = Base64Util.decodeString(encryptedResponse);

          // ===================== 2. RSA 公钥解密 =====================
          console.log('RSA 解密响应...');
          const decryptedBytes = RSAUtils.decryptByPublicKey(
              decodedBytes,
              publicKey
          );

          // ===================== 3. 解析业务对象 =====================
          console.log('解析 JSON 响应...');
          const responseObj = JsonUtils.fromJson(decryptedBytes.toString('utf8'));

          // ===================== 4. 验证并输出结果 =====================
          if (!responseObj.address || typeof responseObj.address !== 'string') {
              throw new Error('API 返回了无效的地址信息');
          }

          console.log('\n✅ 成功获取钱包地址信息:');
          console.log('------------------------');
          console.log('商户用户ID:', responseObj.tenantUserId);
          console.log('链名称:   ', responseObj.chainName);
          console.log('钱包地址:  ', responseObj.address);
          console.log('------------------------');

          return responseObj;
      } catch (error) {
          throw new Error(`解密响应失败: ${error.message}`);
      }
  }

  /**
   * 执行完整示例
   */
  static executeExample() {
      try {
          // 配置参数
          const config = {
              PUBLIC_KEY: `YOUR_PUBLIC_KEY`
          };

          // 假设这是从EncryptionExample获得的加密响应
          const encryptedResponse = 'BOvLMndpkzbXuESD5nysm7YYMYGamewDpszbf4ljVLoTBQLNoqJ/htonmmOdV6KhO9XpvyRhMx4iXZRogNCdN+XeWFJ57HT5bLKHQ7g==...';

          console.log('开始 WaaS API 解密响应流程...');

          // 解密并解析响应
          const responseObj = this.decryptResponse(
              encryptedResponse,
              config.PUBLIC_KEY
          );

          return responseObj;
      } catch (error) {
          console.error('\n❌ 解密响应失败:', error.message);
          throw error;
      }
  }
}

if (require.main === module) {
  (async () => {
      try {
          await DecryptionExample.executeExample();
      } catch (error) {
          console.error('解密响应示例执行失败:', error.message);
      }
  })();
}

module.exports = DecryptionExample;
import requests
from JsonUtils import JsonUtils
from RSAUtils import RSAUtils
from Base64Util import Base64Util

def main():
  try:
      # ===================== 1. 获取API响应 =====================
      # 假设已发送请求并获取到响应
      response = requests.post(
          'https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress',
          data={},
          headers={'X-API-KEY': 'MERCHANT_123456'}
      )

      # 解析JSON响应并获取加密数据
      response_data = response.json()
      encrypted_data = response_data['data']

      # ===================== 2. Base64解码 =====================
      decoded_bytes = Base64Util.decode_string(encrypted_data)

      # ===================== 3. RSA公钥解密 =====================
      public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ..."
      decrypted_bytes = RSAUtils.decrypt_by_public_key(
          decoded_bytes,
          public_key
      )

      # 转为字符串
      decrypted_text = decrypted_bytes.decode('utf-8')

      # ===================== 4. 解析业务对象 =====================
      # 使用JsonUtils反序列化为AddressVO实例
      address_data = JsonUtils.from_json(decrypted_text)
      address = AddressVO(address_data)

      # ===================== 5. 使用解密数据 =====================
      print("\n解析得到的地址信息:")
      print("商户用户ID:", address.get_tenant_user_id())
      print("链名称:", address.get_chain_name())
      print("钱包地址:", address.get_address())

  except Exception as e:
      print("\n解密过程中发生错误:", str(e))
      import traceback
      traceback.print_exc()

if __name__ == "__main__":
  main()