How to Generate Hash

Updated 

The hash is a Hash-based Message Authentication Code (HMAC) generated using the SHA-256 algorithm. Live Chat supports a timestamp-based HMAC signature that:

  • Validates a user's identity securely

  • Expires after a defined period (default: 1 minutes)

  • Prevents signature reuse

Let’s take an example of the following user:

user: {     userId: '12345',     firstName: 'John',     lastName: 'Doe',     phoneNo: '9876543210',     email: 'John.Doe@example.com',     profileImageUrl: 'https://example.com/profilePic.jpg',     hash: 'f30c3b0835ecd378a134c74bce8cea866df8c5b6e12a8c219c9bb288f7270e22',   hashCreationTime: 1754565280133 } ​

Steps to Generate a Hash

1. Concatenate specific user details in the following order, separating each with an underscore (_) to create a string:

userId_firstName_lastName_profileImageUrl_phoneNo_email_hashCreationTime

For example, the resulting string to generate the hash would be:

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com_1754565280133

Note: If some user details are missing, omit their values but retain the underscores to preserve the field order. For example, if profileImageUrl is unavailable, include consecutive underscores after lastName, as shown below:

userId_firstName_lastName__phoneNo_email_hashCreationTime

2. Pass the string and API key provided by Sprinklr to the hash function.

Sample function to generate hash in Java:

import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.security.NoSuchAlgorithmException;import java.security.InvalidKeyException;import javax.xml.bind.DatatypeConverter;class Main {public static void main(String[] args) { try {      String key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";      long hashCreationTime = System.currentTimeMillis();      String message = "12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example_hashCreationTime";      Mac hasher = Mac.getInstance("HmacSHA256");      hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));      byte[] hash = hasher.doFinal(message.getBytes());         System.out.println((DatatypeConverter.printHexBinary(hash)).toLowerCase());   }   catch (NoSuchAlgorithmException e) {}   catch (InvalidKeyException e) {} }}

Note: The UserID, Hash and hashCreationTime parameters are mandatory parameters and hash should be generated for every change in user object. The hashCreationTime must be included at the end of the string in epoch timestamp format.

The secret key which is used in HMAC for your application can be found in the Dev Tools section of the Live Chat Builder.

Sample function to generate hash in Swift

import Foundationimport CommonCryptofunc hmac(message: String, key: String) -> String? {    guard let messageData = message.data(using: .utf8),          let keyData = key.data(using: .utf8) else {        return nil    }    var hmacContext = CCHmacContext()    let digest = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH))    defer { digest.deallocate() }    CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), (keyData as NSData).bytes, keyData.count)    CCHmacUpdate(&hmacContext, (messageData as NSData).bytes, messageData.count)    CCHmacFinal(&hmacContext, digest)    let result = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))    let hexEncodedString = result.map { String(format: "%02hhx", $0) }.joined()    return hexEncodedString}// Example usage:let delimiter = "_"// Sample data — normally this would come from your user objectlet id = "12345"let firstName = "John"let lastName = "Doe"let profileImageUrl = "https://example.com/profilePic.jpg"let phoneNo = "9876543210"let email = "John.Doe@example.com"let hashCreationTime: Int64 = 1723549800 // example epoch timelet message = [    id,    firstName,    lastName,    profileImageUrl,    phoneNo,    email,    String(hashCreationTime)].joined(separator: delimiter)let key = "1f5fb9bd-27a6-4057-823c-94a23be1d2a2"if let hmacResult = hmac(message: message, key: key) {    print("HMAC: \(hmacResult)")}

Note: The UserID, Hash and hashCreationTime parameters are mandatory parameters and hash should be generated for every change in user object. The hashCreationTime must be included at the end of the string in epoch timestamp format.

The secret key which is used in HMAC for your application can be found in the Dev Tools section of the Live Chat Builder.

Hash Expiry and Storage Considerations

In our system, each hash is associated with a creation timestamp (hashCreationTime). A hash is considered valid only for a limited duration from the time it is created. Once this time period passes, the hash automatically expires and cannot be used for authentication or authorization purposes.

Note: Consider the following points:

  • Expiry Duration: The system uses the hashCreationTime to calculate the validity of a hash. Any operation that relies on a hash beyond this expiry period will fail.

  • Local Storage/Caching: If your application stores hashes in storage medium like local storage, or any persistent cache, you must remove or invalidate them after they expire. Continuing to use an expired hash may lead to failed requests or security issues.

Sample code to generate HMAC is mentioned in Sample code for hash generation.

Note: Ensure you have the required dependency installed, and the version must be within the specified range:

"crypto-js": "<= 3.3.0"

For more information, refer to crypto-js documentation.