Tuesday 28 June 2022

SAP CPI - Generate signature with signed URL with HMAC_SHA1 using groovy script


SAP CPI - Generate signature with signed URL with HMAC_SHA1 using groovy script


Groovy script for signed URL for Google API's -Geolocation etc.,


Groovy script:

import com.sap.gateway.ip.core.customdev.util.Message

import java.io.*

import com.microsoft.azure.storage.*;

import com.microsoft.azure.storage.file.*;

import com.microsoft.azure.storage.common.*;

import com.microsoft.*;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;

import java.util.Formatter;

import java.net.URL;

import java.io.BufferedReader;

import java.io.InputStreamReader;




def Message processData(Message message) {

def body = message.getBody(java.lang.String) as String



def map = message.getHeaders();

def inputurl = map.get("inputurl");


//String inputurl = "http://maps.googleapis.com/maps/api/geocode/json?address=10005+NY&sensor=false";

String Crypto_Code__c = "<secret_code>";

String Client_Key__c = "<client_ID>";

inputurl=inputurl +'&client='+Client_Key__c;

String privateKey = Crypto_Code__c;




//def path = url.getPath()

def urlpath = inputurl.toURL();

def Path = urlpath.getPath();

def Query = urlpath.getQuery();


def resource = Path+ '?' +Query


privateKey = privateKey.replace('-', '+');

privateKey = privateKey.replace('_', '/');


//def decoded = privateKey.bytes.decodeBase64().toString()

byte[] decoded = privateKey.decodeBase64()

// get an hmac_sha1 key from the raw key bytes

SecretKeySpec signingKey = new SecretKeySpec(decoded, "HmacSHA1")

// get an hmac_sha1 Mac instance and initialize with the signing key

Mac mac = Mac.getInstance("HmacSHA1")

mac.init(signingKey)

// compute the hmac on input data bytes

byte[] rawHmac = mac.doFinal(resource.getBytes());

//String hash = Base64.encodeBase64String(mac.doFinal(url.getBytes()));

String signature = Base64.getEncoder().encodeToString(rawHmac);



signature = signature.replace('+', '-');

signature = signature.replace('/', '_');

def endURL = inputurl + "&signature=" + signature;

def (url1, qquery) = endURL.tokenize( '?' )


message.setProperty("Path", Path);

message.setProperty("url1", url1);

message.setProperty("qquery", qquery);

message.setBody("OK")



return message;

}



No comments:

Post a Comment