Skip to main content

c. Decryption Operation Guide

This guide details how to decrypt encrypted response data obtained from WaaS APIs.

i. Decryption Process Step-by-Step Explanation

The following are the steps for decryption operations:
  1. Obtain encrypted data from the API response
  2. Perform Base64 decoding of the data
  3. Decrypt using the RSA public key
  4. Parse the decrypted result into the business object

ii. Decryption Code Examples

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. Get API response =====================
            // Send API request and get response
            APIResult<String> response = restTemplate.postForObject(
                "https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress",
                httpEntity,
                APIResult.class
            );

            // Extract encrypted data (ensure response format matches API)
            String encryptedData = response.getData();

            // ===================== 2. Base64 decoding =====================
            // Decode using Base64 utility class (implementation reference utility classes)
            byte[] decodedBytes = Base64Util.decodeString(encryptedData);

            // ===================== 3. RSA public key decryption =====================
            // Use the same public key as for requests
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ...";

            // Perform RSA decryption
            byte[] decryptedBytes = RSAUtils.decryptByPublicKey(
                decodedBytes,
                publicKey
            );

            // ===================== 4. Parse business object =====================
            // Convert decrypted JSON data to business object
            AddressVO address = JsonUtils.fromJson(
                new String(decryptedBytes, StandardCharsets.UTF_8),
                AddressVO.class
            );

            // ===================== 5. Use decrypted data =====================
            System.out.println("Parsed address information:");
            System.out.println("Merchant user ID: " + address.getTenantUserId());
            System.out.println("Chain name: " + address.getChainName());
            System.out.println("Wallet address: " + address.getAddress());

        } catch (Exception e) {
            System.err.println("\nError occurred during decryption: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
const RSAUtils = require('./RSAUtils');
const JsonUtils = require('./JsonUtils');
const Base64Util = require('./Base64Util');

/**
* Decryption Response Example
*
* Demonstrates how to decrypt and parse responses from WaaS API
*/
class DecryptionExample {
  /**
   * Decrypts and parses API response
   * @param {string} encryptedResponse - Base64 encoded encrypted response
   * @param {string} publicKey - Base64 encoded public key
   * @returns {Object} Parsed business object
   */
  static decryptResponse(encryptedResponse, publicKey) {
      try {
          console.log('Starting decryption response example...');

          // ===================== 1. Base64 Decoding =====================
          console.log('Base64 decoding response...');
          const decodedBytes = Base64Util.decodeString(encryptedResponse);

          // ===================== 2. RSA Public Key Decryption =====================
          console.log('RSA decrypting response...');
          const decryptedBytes = RSAUtils.decryptByPublicKey(
              decodedBytes,
              publicKey
          );

          // ===================== 3. Parse Business Object =====================
          console.log('Parsing JSON response...');
          const responseObj = JsonUtils.fromJson(decryptedBytes.toString('utf8'));

          // ===================== 4. Validate and Output Results =====================
          if (!responseObj.address || typeof responseObj.address !== 'string') {
              throw new Error('API returned invalid address information');
          }

          console.log('\n✅ Successfully retrieved wallet address information:');
          console.log('------------------------');
          console.log('Tenant User ID:', responseObj.tenantUserId);
          console.log('Chain Name:   ', responseObj.chainName);
          console.log('Wallet Address:', responseObj.address);
          console.log('------------------------');

          return responseObj;
      } catch (error) {
          throw new Error(`Decryption failed: ${error.message}`);
      }
  }

  /**
   * Executes the complete example
   */
  static executeExample() {
      try {
          // Configuration parameters
          const config = {
              PUBLIC_KEY: `YOUR_PUBLIC_KEY`
          };

          // Sample encrypted response from EncryptionExample
          const encryptedResponse = 'BOvLMndpkzbXuESD5nysm7YYMYGamewDpszbfnHxVFVsllzKvaib/BlJ9Z7gxRpLqZ2O1bIg0oTPwVLqbi2pPqlAtb2cICa4rIrv80mXDoxs9ErP6DkFDDExzo6O/5ZVSd++RMDtYhXLyD6HmTSeJeZ94T34t+G1s/gYL1E0i6R0x9AyrzL7hEja0wiqobc5HVd2KjHhhVH2mxGcTGOMup/4s/3U3fd5xLBGX3pGfI4ljVLoTBITAMssG/adn5/iT0S58EcRU4GOLjMaNumh0ZxYd1fBQLNoqJ/htonmmOdV6KhO9XpvyRhMx4iXZRogNCdN+XeWFJ57HT5bLKHQ7g==';

          console.log('Starting WaaS API decryption process...');

          // Decrypt and parse response
          const responseObj = this.decryptResponse(
              encryptedResponse,
              config.PUBLIC_KEY
          );

          return responseObj;
      } catch (error) {
          console.error('\n❌ Decryption failed:', error.message);
          throw error;
      }
  }
}

if (require.main === module) {
  (async () => {
      try {
          await DecryptionExample.executeExample();
      } catch (error) {
          console.error('Decryption example execution failed:', error.message);
      }
  })();
}

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

def main():
try:
    # ===================== 1. Simulate getting API response =====================
    # Assume request was sent and response received
    response = requests.post(
        'https://waas2-out-api.powersafe-rel.cc/api/v1/api/user/getUserAddress',
        data={},
        headers={'X-API-KEY': 'MERCHANT_123456'}
    )

    # Parse JSON response and get encrypted data
    response_data = response.json()
    encrypted_data = response_data['data']

    # ===================== 2. Base64 decoding =====================
    decoded_bytes = Base64Util.decode_string(encrypted_data)

    # ===================== 3. RSA public key decryption =====================
    public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQ..."
    decrypted_bytes = RSAUtils.decrypt_by_public_key(
        decoded_bytes,
        public_key
    )

    # Convert to string
    decrypted_text = decrypted_bytes.decode('utf-8')

    # ===================== 4. Parse business object =====================
    # Deserialize to AddressVO instance using JsonUtils
    address_data = JsonUtils.from_json(decrypted_text)
    address = AddressVO(address_data)

    # ===================== 5. Use decrypted data =====================
    print("\nParsed address information:")
    print("Merchant user ID:", address.get_tenant_user_id())
    print("Chain name:", address.get_chain_name())
    print("Wallet address:", address.get_address())

except Exception as e:
    print("\nError occurred during decryption:", str(e))
    import traceback
    traceback.print_exc()

if __name__ == "__main__":
main();