Forum Discussion

VirtualTechie's avatar
VirtualTechie
New Contributor
10 years ago

Need to generate hmac-sha1 signature to send it part of REST request header. Any help??

Hi Team,      We are trying to analyse soapUI as an automation tool to automate our RESTful API regression tests. But while doing a prototype we are faing an issue in setting up the headers for REST...
  • VirtualTechie's avatar
    VirtualTechie
    10 years ago

    Hi Rao,

         I couldn't find a solution from those discussions. But I got it resolved using some groovy scripts.

     

    Pasting it down here, if somebody feels helpful.

     

     

    *****************************

    import java.nio.charset.StandardCharsets;
    import java.security.SignatureException
    import java.security.spec.EncodedKeySpec;
    import com.eviware.soapui.support.types.StringToStringMap 
    import javax.crypto.Mac
    import javax.crypto.spec.SecretKeySpec
    import java.sql.Date.*;
    
      def now = new Date()
      def timestamp = ""+Math.round(now.getTime()/1000);
            //Parameters used to generate the signature
    		String username = "username";
    		String secret = "secret"
    		String parameter2 = "param2"
    		log.info "Timestamp Genereated : "+timestamp
    		String signature=""
    		try {
    		
    			// get an hmac_sha1 key from the raw key bytes
    			
    			SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    			
    			// get an hmac_sha1 Mac instance and initialize with the signing key
    			Mac mac = Mac.getInstance("HmacSHA256");
    			mac.init(signingKey);
    			
    			// compute the hmac on input data bytes
    			
    		String message = new StringBuilder().append (username).append (parameter2).append (timestamp).toString ();
    			
    		   byte [] signatureBytes = mac.doFinal (message.getBytes(StandardCharsets.UTF_8));
    		   log.info signatureBytes
    		   signature = signatureBytes.encodeHex()
    	   
    		
    		} catch (Exception e) {
    			throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    		}
    	 
    		def headers = new StringToStringMap()
              headers.put("X-E2-HMAC-Signature",signature)
              headers.put("X-E2-HMAC-Timestamp",timestamp)
              headers.put("X-E2-Username",username)
              headers.put("X-E2-Parameter2",parameter2)
    //Set the headers for that the teststep testRunner.testCase.getTestStepByName("Step1").testRequest.setRequestHeaders(headers)

    *****************************

     

    Thanks,

    VT