How to use GlideCertificateEncryption.generateMac method to encrypt the data in SN side and decrypt the same in another servicenow/different application.

Alex Pandian1
Tera Expert

We want to data encryption in the rest based integration. I found this GlideCertificateEncryption.generateMac api and method to do key based encryption. But it didnt have any example on how to use this in our scripted rest api.It would be great if some one share with sample code on how to encode and decode the data using HmacSHA256 algorithm. 

4 REPLIES 4

Nidhi30
Tera Contributor

I had a similar requirement to authenticate the request with HmacSha256 and i was able to implement it by using the code below.

You can pass the HMAC signature in the headers which should be generated with the payload and system defined HMAC secret key(only source and your app have access to the secret HMAC key).

Eg to verify the signatures:

  1. Extract the text of the UTF-8 payload as a string. The entire body of the POST request is used, including line endings.
  2. Compute a SHA256 HMAC digest for the strigified payload.
  3. Compare the base64 digest to the value of the x-hmac-signature header. Computed digest must exactly match its corresponding header value. If there is no match, then the request may be compromised and it should not be trusted

 

Example Outbound data with the HMAC key -

var body ='sample_data';
var mac = new GlideCertificateEncryption;
var key = "sample_key";                              //can be defined in a property
key = GlideStringUtil.base64Encode(key);
var hash = mac.generateMac(key, "HmacSHA256", body);
 

var request = new sn_ws.RESTMessageV2();
request.setEndpoint('https://{instance_name}/api/rao/testapi');         //Scripted rest api
request.setHttpMethod('POST');
request.setRequestHeader("x-hmac-signature",hash);

request.setRequestBody(body);
request.setRequestHeader("Accept","application/json");

var response = request.execute();

 

Inbound Scripted rest Api to authenticate the request with HmacSHA256 -

var requestBody = JSON.stringify(request.body.data);
var requestHeaders = request.headers;


var mac = new GlideCertificateEncryption;
var key = 'sample_key';                       //should match the source system
key = GlideStringUtil.base64Encode(key);
var signature = mac.generateMac(key, "HmacSHA256", requestBody);

if (requestHeaders["x-hmac-signature"] === signature) {

//Process the request


} else {

gs.info("Authentication failed ");


}

Thanks Nidhi. can you share sample code for other application?

Hi Nidhi,

I have tried the above code for hmacsha1 but getting error as below.

hashvalue cannot be converted to byte array as attached below could you please help here

HI @Nidhi30 

Is the body mandatory to generate mac? Without he 3rd parameter I see the codei s always the same.

 

Thanks