Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Signature Verification

Updated on 2024-12-30 GMT+08:00

When OneAccess synchronizes data to an enterprise application, the application must identify and confirm the synchronization event to check the security and reliability of the event source and to safeguard that data is exchanged in a secure environment.

Signature Verification/Encryption and Decryption Terms

Table 1 Terms

Term

Description

signature

Message signature, which is used to verify whether a request is from OneAccess to prevent attackers from forging the request. The signature algorithm is HMAC-SHA256 + Base64.

AESKey

Key of the AES algorithm. The encryption algorithm is AES/GCM/NoPadding + Base64.

msg

Plaintext message body in JSON format.

encrypt _msg

Encrypted and Base64-encoded ciphertext of the plaintext message 'msg'.

Signature Verification

To ensure that the event is pushed by OneAccess, the request body includes a request signature, identified by the signature parameter, when OneAccess pushes the event to the enterprise application callback service. The enterprise application must verify this parameter before decryption. The verification procedure is as follows:

  1. Calculating signatures
    The signature consists of the signature key, nonce, timestamp, eventType, and data, all concatenated using ampersands (&). The HMAC-SHA256 + Base64 algorithms are used for encryption. The following is an example of the Java signature:
    String message = nonce + "&" + timestamp + "&" + eventType + "&" + data; 
    Mac mac = Mac.getInstance("HmacSHA256"); 
    SecretKeySpec secretKey = new SecretKeySpec(Signature key.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); 
    mac.init(secretKey); 
    String newSignature = Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes(StandardCharsets.UTF_8)));
  2. Check whether the calculated signature cal_signature is the same as signature in the request parameter. If they are the same, the verification is successful.
  3. The response message returned by the enterprise application needs to use the required format.

Encrypting a Plaintext

  1. Concatenate plaintext strings, which consist of a 16-byte random characters and a plaintext msg, and are separated by ampersands (&). The following is an example written in Java:
    String dataStr = RandomStringUtils.random(16, true, false) + "&" + data;
  2. Use the AESkey to encrypt the concatenated plaintext string and encode it using Base64 to obtain the ciphertext encrypt_msg. The following is an example written in Java:
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 
    SecretKeySpec secretKey = new SecretKeySpec(Encryption key.getBytes(StandardCharsets.UTF_8), "AES"); 
    cipher.init(1, secretKey); 
    byte[] bytes = dataStr.getBytes(StandardCharsets.UTF_8); 
    String ecnryptStr = Base64.getEncoder().encodeToString(cipher.doFinal(bytes));

Decrypting Ciphertext

  1. Decode the ciphertext using Base64.
    byte[] encryptStr = Base64.getDecoder().decode(data);
  2. Use the AESKey for decryption.
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 
    SecretKeySpec secretKey = new SecretKeySpec(Encryption key.getBytes(StandardCharsets.UTF_8), "AES"); 
    cipher.init(2, secretKey); 
    byte[] bytes = cipher.doFinal(encryptStr);
  3. Remove the 16 random bytes from the rand_msg header. The remaining part is the plaintext msg.
    String dataStr = StringUtils.split(new String(bytes, StandardCharsets.UTF_8), "&")[1];

Examples of Data Signature & Encryption/Decryption

  • The following is an example of data signature and AES/GCM/NOPadding encryption and decryption written in Java:
    package com.example.demo.controller;
    import com.alibaba.fastjson.JSONObject;
    import java.nio.charset.Charset;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.Mac;
    import javax.crypto.spec.GCMParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.lang3.RandomStringUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.Assert;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @RequestMapping
    @Controller
    public class GcmController {
        private static final Logger log = LoggerFactory.getLogger(com.example.demo.controller.GcmController.class);
        private static final String SEPARATOR = "&";
    
       //region. The following three parameters are 32-bit strings randomly generated by a third party (case-sensitive letters and digits). Do not use the example in the formal environment.
        /**
         * Security token
         */
        private static final String TOKEN = "4JV**********NCE";
    
        /**
         * Signature key
         */
        private static final String SIGN_KEY = "wGt**********Rrs";
    
        /**
         * Encryption key
         */
        private static final String ENCRYPTION_KEY = "ZJI**********FQo";
        //endregion
    
        /**
         * Encryption algorithm
         */
        private static final String HMAC_SHA256 = "HmacSHA256";
        private static final String ENCRYPT_ALGORITHM = "AES/GCM/NoPadding";
        private static final String ENCRYPT_KEY_ALGORITHM = "AES";
        private static final int AES_KEY_SIZE = 128;
        private static final Charset CHARSET = StandardCharsets.UTF_8;
    
        @ResponseBody
        @RequestMapping({"/gcm/callback"})
        public JSONObject demo(HttpServletRequest httpRequest, @RequestBody String body) {
            log.info("Receive event callback information data. Original packet:" + body);
            JSONObject result = new JSONObject();
            result.put("code", "200");
            result.put("message", "success");
            String authorization = httpRequest.getHeader("Authorization");
            if (!StringUtils.join((Object[]) new String[]{"Bearer ", TOKEN}).equals(authorization)) {
                result.put("code", "401");
                result.put("message", "Invalid request!");
                printResult(result);
                return result;
            }
            JSONObject request = JSONObject.parseObject(body);
            String signature = request.getString("signature");
            String eventType = request.getString("eventType");
            log.info("Event type" + eventType);
            String data = request.getString("data");
            if (StringUtils.isNotEmpty(SIGN_KEY))
                try {
                    log.info("Start to verify signature");
                    String message = request.getString("nonce") + "&" + request.getLong("timestamp") + "&" + eventType + "&" + data;
                    Mac mac = Mac.getInstance(HMAC_SHA256);
                    SecretKeySpec secretKey = new SecretKeySpec(SIGN_KEY.getBytes(CHARSET), HMAC_SHA256);
                    mac.init(secretKey);
                    String newSignature = Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes(CHARSET)));
                    Assert.isTrue(newSignature.equals(signature), "Signature inconsistency");
                    log.info("Signature verified");
                } catch (Exception e) {
                      log.error("Verify signature failed", e);
                    result.put("code", "401");
                    result.put("message", "Verify signature failed");
                    printResult(result);
                    return result;
                }
            if (StringUtils.isNotEmpty(ENCRYPTION_KEY)) {
                log.info("Start to decrypt data" + data);
                try {
                    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
                    SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY.getBytes(CHARSET), ENCRYPT_KEY_ALGORITHM);
                    byte[] iv = decodeFromBase64(data.substring(0, 24));
                    data = data.substring(24);
                    cipher.init(2, secretKey, new GCMParameterSpec(AES_KEY_SIZE, iv));
                    byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(data));
                    data = new String(bytes, CHARSET);
                    log.info("Data decrypted. Decrypted data:" + data);
                } catch (Exception e) {
                    log.error("Decrypt data failed", e);
                    result.put("code", "401");
                    result.put("message", "Decrypt data failed");
                    printResult(result);
                    return result;
                }
            }
            JSONObject eventData = JSONObject.parseObject(data);
            JSONObject returnData = new JSONObject(1);
            String dataStr = null;
            switch (eventType) {
                case "CREATE_USER":
                    // Create downstream data based on the unique username. If the downstream data already exists, update it and return the downstream ID.
                    returnData.put("id", eventData.getString("username"));
                    break;
                case "CREATE_ORGANIZATION":
                    // Create downstream data based on the unique code. If the downstream data already exists, update it and return the downstream ID.
                    returnData.put("id", eventData.getString("code"));
                    break;
                case "UPDATE_USER":
                case "UPDATE_ORGANIZATION":
                    // When data is updated, the fields that are not modified are empty.
                    returnData.put("id", eventData.getString("id"));
                    break;
                case "DELETE_ORGANIZATION":
                case "DELETE_USER":
                    // Perform the deletion operation based on the downstream service logic. No fields need to be returned.
                    break;
                default:
                    result.put("code", "400");
                    result.put("message", "Unsupported event type");
                    printResult(result);
                    return result;
            }
            if (dataStr == null && returnData.size() > 0)
                dataStr = returnData.toJSONString();
            if (StringUtils.isNotEmpty(ENCRYPTION_KEY) && dataStr != null) {
                String random = RandomStringUtils.random(24, true, true);
                log.info("Start to encrypt data" + dataStr);
                try {
                    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
                    SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY.getBytes(CHARSET), ENCRYPT_KEY_ALGORITHM);
                    byte[] iv = decodeFromBase64(random);
                    cipher.init(1, secretKey, new GCMParameterSpec(AES_KEY_SIZE, iv));
                    byte[] bytes = dataStr.getBytes(CHARSET);
                    dataStr = Base64.getEncoder().encodeToString(cipher.doFinal(bytes));
                    dataStr = random + dataStr;
                    log.info("Data encrypted. Encrypted data:" + dataStr);
                } catch (Exception e) {
                    log.error("Encrypt data failed", e);
                    result.put("code", "500");
                    result.put("message", "Encrypt data failed");
                    printResult(result);
                    return result;
                }
            }
            result.put("data", dataStr);
            printResult(result);
            return result;
        }
    
        private static byte[] decodeFromBase64(String data) {
            return Base64.getDecoder().decode(data);
        }
    
        private void printResult(JSONObject result) {
            log.info("" + result.toJSONString());
        }
    }
  • The following is an example of data signature and AES/ECB/PKCS5Padding encryption and decryption written in Java:
    package com.example.demo.controller;
    import com.alibaba.fastjson.JSONObject;
    import java.nio.charset.Charset;
    import java.nio.charset.StandardCharsets;
    import java.util.Base64;
    import java.util.UUID;
    import javax.crypto.Cipher;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import javax.servlet.http.HttpServletRequest;
    import org.apache.commons.lang3.RandomStringUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Controller;
    import org.springframework.util.Assert;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @RequestMapping
    @Controller
    public class DemoController {
      private static final Logger log = LoggerFactory.getLogger(com.example.demo.controller.DemoController.class);
    
      /** Signature concatenation operator **/
      private static final String SEPARATOR = "&";
    
      /** Signature key **/
      private static final String SIGN_KEY = "wGt**********Rrs";
    
      /** Encryption key **/
      private static final String ENCRYPTION_KEY = "ZJI**********FQo";
    
      /** Security token **/
      private static final String TOKEN = "4JV**********NCE";
    
      /** Signature algorithm **/
      private static final String HMAC_SHA256 = "HmacSHA256";
    
      /** Encryption algorithm **/
      private static final String ENCRYPT_ALGORITHM = "AES/ECB/PKCS5Padding";
    
      /** **/
      private static final String ENCRYPT_KEY_ALGORITHM = "AES";
    
      /** Character encoding **/
      private static final Charset CHARSET = StandardCharsets.UTF_8;
    
      @ResponseBody
      @RequestMapping({"/callback"})
      public JSONObject demo(HttpServletRequest httpRequest, @RequestBody String body) {
        JSONObject result = new JSONObject();
        result.put("code", "200");
        result.put("message", "success");
        log.info ("Receive event callback message data. Original packet:" + body);
        String authorization = httpRequest.getHeader("Authorization");
        if (!StringUtils.join("Bearer ", TOKEN).equals(authorization)) {
          result.put("code", "401");
          result.put ("message", "Invalid request!");
          printResult(result);
          return result;
        }
        JSONObject request = JSONObject.parseObject(body);
        String signature = request.getString("signature");
        String eventType = request.getString("eventType");
        log.info("Event type:" + eventType);
        String data = request.getString("data");
        if (StringUtils.isNotEmpty(SIGN_KEY)) {
          try {
            log.info ("Start to verify signature");
            String message = request.getString("nonce") + SEPARATOR + request.getLong("timestamp") + SEPARATOR + eventType + SEPARATOR + data;
            Mac mac = Mac.getInstance(HMAC_SHA256);
            SecretKeySpec secretKey = new SecretKeySpec(SIGN_KEY.getBytes(CHARSET), HMAC_SHA256);
            mac.init(secretKey);
            String newSignature = Base64.getEncoder().encodeToString(mac.doFinal(message.getBytes(CHARSET)));
            Assert.isTrue (newSignature.equals (signature), "Signature inconsistency");
            log.info ("Signature verified");
          } catch (Exception e) {
            log.info ("Verify signature failed");
            log.error ("Verify signature failed", e);
            result.put("code", "401");
            result.put ("message", "Verify signature failed");
            printResult(result);
            return result;
          }
        }
        if (StringUtils.isNotEmpty(ENCRYPTION_KEY)) {
          log.info ("Start to decrypt data:" + data);
          try {
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY.getBytes(CHARSET), ENCRYPT_KEY_ALGORITHM);
            cipher.init(2, secretKey);
            byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(data));
            data = StringUtils.split(new String(bytes, CHARSET), SEPARATOR)[1];
            log.info ("Data decrypted. Decrypted data:" + data);
          } catch (Exception e) {
            log.info ("Decrypt data failed");
            log.error ("Data decryption error", e);
            result.put("code", "401");
            result.put ("message", "Decrypt data failed");
            printResult(result);
            return result;
          }
        }
        JSONObject eventData = JSONObject.parseObject(data);
        JSONObject returnData = new JSONObject(1);
        String dataStr = null;
        switch (eventType) {
          case "CREATE_USER":
            returnData.put("id", eventData.getString("username"));
            break;
          case "CREATE_ORGANIZATION":
            returnData.put("id", eventData.getString("code"));
            break;
          case "UPDATE_USER":
          case "UPDATE_ORGANIZATION":
            returnData.put("id", eventData.getString("id"));
            break;
          case "DELETE_ORGANIZATION":
          case "DELETE_USER":
            break;
          case "CHECK_URL":
            dataStr = UUID.randomUUID().toString().replaceAll("-", "");
            break;
          default:
            result.put("code", "400");
            result.put ("message", "Unsupported event type");
            printResult(result);
            return result;
        }
        if (dataStr == null && returnData.size() > 0) {
          dataStr = returnData.toJSONString();
        }
        if (StringUtils.isNotEmpty(ENCRYPTION_KEY) && dataStr != null) {
          dataStr = RandomStringUtils.random(16, true, false) + SEPARATOR + dataStr;
          log.info ("Start to encrypt data:" + dataStr);
          try {
            Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(ENCRYPTION_KEY.getBytes(CHARSET), ENCRYPT_KEY_ALGORITHM);
            cipher.init(1, secretKey);
            byte[] bytes = dataStr.getBytes(CHARSET);
            dataStr = Base64.getEncoder().encodeToString(cipher.doFinal(bytes));
            log.info ("Data encrypted. Encrypted data:" + dataStr);
          } catch (Exception e) {
            log.info ("Encrypt data failed");
            log.error ("Data encryption error:", e);
            result.put("code", "500");
            result.put ("message", "Encrypt data failed");
            printResult(result);
            return result;
          }
        }
        result.put("data", dataStr);
        printResult(result);
        return result;
      }
    
      private void printResult(JSONObject result) {
        log.info ("Returned data:" + result.toJSONString ());
      }
    }

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback