Signature Verification
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
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:
- 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)));
- 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.
- The response message returned by the enterprise application needs to use the required format.
Encrypting a Plaintext
- 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;
- 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
- Decode the ciphertext using Base64.
byte[] encryptStr = Base64.getDecoder().decode(data);
- 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);
- 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 ()); } }
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot