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;

}



Java code to sign the URL using the HMAC in SAP PI/SAP CPI

Google API/Google GeoLocation/Signature generation/ Validate signed URL 


Java code to sign the URL using the HMAC with encoding and decoding in SAP PI/CPI


Java code:

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URI;

import java.net.URISyntaxException;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.util.Base64; // JDK 1.8 only - older versions may need to use Apache Commons or similar.

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import java.net.URL;

import java.io.BufferedReader;

import java.io.InputStreamReader;




public class UrlSigner {




// Note: Generally, you should store your private key someplace safe

// and read them into your code




private static String keyString = "Crypto key/Private key";



// The URL shown in these examples is a static URL which should already

// be URL-encoded. In practice, you will likely have code

// which assembles your URL from user or web service input

// and plugs those values into its parameters.

private static String urlString = "http://maps.googleapis.com/maps/api/geocode/json?address=10006+NY&sensor=false&client=<Client ID>";


// This variable stores the binary key, which is computed from the string (Base64) key

private static byte[] key;

public static void main(String[] args) throws IOException,

InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {



BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

String inputUrl, inputKey = null;

// For testing purposes, allow user input for the URL.

// If no input is entered, use the static URL defined above.

/*System.out.println("Enter the URL (must be URL-encoded) to sign: ");

inputUrl = input.readLine();

if (inputUrl.equals("")) {

inputUrl = urlString;

}*/


// Convert the string to a URL so we can parse it

URL url = new URL(urlString);


// For testing purposes, allow user input for the private key.

// If no input is entered, use the static key defined above.

/* System.out.println("Enter the Private key to sign the URL: ");

inputKey = input.readLine();

if (inputKey.equals("")) {

inputKey = keyString;

}*/



UrlSigner signer = new UrlSigner(keyString);

String request = signer.signRequest(url.getPath(),url.getQuery());

System.out.println("Signed URL :" + url.getProtocol() + "://" + url.getHost() + request);

}

public UrlSigner(String keyString) throws IOException {

// Convert the key from 'web safe' base 64 to binary

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

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

// System.out.println("Key: " + keyString);

// Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.

this.key = Base64.getDecoder().decode(keyString);

}


public String signRequest(String path, String query) throws NoSuchAlgorithmException,

InvalidKeyException, UnsupportedEncodingException, URISyntaxException {


// Retrieve the proper URL components to sign

String resource = path + '?' + query;


// Get an HMAC-SHA1 signing key from the raw key bytes

SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");


// Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key

Mac mac = Mac.getInstance("HmacSHA1");

mac.init(sha1Key);

// compute the binary signature for the request

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


// base 64 encode the binary signature

// Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.

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


// convert the signature to 'web safe' base 64

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

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

return resource + "&signature=" + signature;

}

}



Thursday 16 June 2022

Run the multiple request from POSTMAN for checking the performance

 We want to try if the target system is getting timeout if there are parallel calls or multiple request hitting at the same time. Based on that we need to limit the frequency of interface trigger in SAP CI.

1. Go to Postman - create the collection and then create the request under the collection.

 2. Once after filling all the details in the request, like authentication, URL, request data for POST call.

3. Save this request.

4. Right click on the collection and select run collection.

5. Select the request which you want to run multiple times with entering iterations(no of times trigger to happen) , if we want a delay between these request we can add it.

6. Click on Run.


Hope this helps.





Thursday 9 June 2022

Error while posting IDOC data to S4 system from CI

 IDocs are not posted to S4Hana system and getting this below error:

Error Details in CI: (No further logs in CI)

org.apache.cxf.binding.soap.SoapFault: Unknown error occured in the IDoc inbound processing.

Check the mapping, it might be missing with the IDOC structure which is not populating all the fields

Example:

 IDOC @BEGIN="1"
 if missing to add this constant as "1" on mapping  that will not work.. Like wise SEGMENT aswell.

Hope this Helps!



Wednesday 8 June 2022

SAP CPI payload logging script





Groovy script:


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

import java.util.HashMap;

import com.sap.it.api.mapping.*;

import java.text.SimpleDateFormat;

import java.util.Calendar;


def Message processData(Message message) {


map = message.getProperties();

property_ENABLE_PAYLOAD_LOGGING = "TRUE";

if (property_ENABLE_PAYLOAD_LOGGING.toUpperCase().equals("TRUE")) {

// def header = message.getHeaders() as String;

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

String timeStamp = new SimpleDateFormat("HH:mm:ss.SSS").format(new Date());

// String logTitleH = timeStamp + " Request Headers ";

String logTitleB = timeStamp + " Request Body ";


def messageLog = messageLogFactory.getMessageLog(message);

if (messageLog != null) {

// messageLog.addAttachmentAsString(logTitleH, header, "text/xml");

messageLog.addAttachmentAsString(logTitleB, body, "text/xml");

}

}

return message;

}