concatenate & Hex 256sha Hash a Signature - postman

I am trying to create a request in postman that pulls some parameters and puts them in the proper order and then hashes in sha256 hex. I understand I need to use a pre-request script but am struggling with what to use and how to get parameters in the script.
Example of the concatenate string - hex_sha256('[session:Key][session:Password][session:Sent][session:UnitAgencyTypeId][session:UnitName][session:UserInit][session:UserName][session:UserSub][session:Secret]')")]
Any help would be really appreciated

The script sandbox provided by Postman includes crypto-js, which can be used to compute SHA256 hashes. This can be done as follows:
var SHA256 = require('crypto-js').SHA256,
hash = SHA256('your_content_goes_here');
As for the parameters, it is possible to use various parts of a request, as well as Postman variables to construct the input for your hashing needs. See https://www.getpostman.com/docs/v6/postman/scripts/postman_sandbox_api_reference for a complete reference on all helpers provided by the Postman sandbox.

Related

C++ Signing message on kucoin API

I'm building a multi-exchange bot in C++ and I'm having one small problem. KuCoin exchange has proven to be frustrating to say the least, one of the headers is a signature header where you encode the string with HMAC sha256 and then encode THAT with base64. However I'm not concerned with the encoding, I can do all that. What is stumping me is the string KuCoins API is expecting, I've scoured their documentation 100 times over and I still can't get it right, here are the instructions
For the header of KC-API-KEY:
Use API-Secret to encrypt the prehash string {timestamp+method+endpoint+body} with sha256 HMAC. The request body is a JSON string and need to be the same with the parameters passed by the API.
After that, use base64-encode to encrypt the result in step 1 again.
I've attempted to craft this string in every way possible, and the documentation provides no examples on what a good string should look like, here are the strings I've crafted BEFORE encoding that DO NOT work.
EXAMPLE 1: 1616096476134POST/api/v1/orders?clientOid=55be5&side=BUY&symbol=BTC-USDT&type=MARKET&funds=0.005000
EXAMPLE 2: 1616099932367POST/api/v1/orders{"clientOid":"55be5","side":"BUY","symbol":"BTC-USDT","type":"MARKET","funds":"0"}
As you can see, in the 2nd example I tried to make the body a JSON string with all the correct parameters, but still, I'm getting a bad signature error returned. Literally all I need is to know what the string is supposed to look like so I can craft it properly. Thanks.
I take the assumption that your code works for a private request without parameters (like getting the balance for instance).
I also struggled a bit for POST requests, but managed to get it right after a few attempts. You need to dump the parameters as a JSON string without spaces, exactly like in your example 2.
Since that time, have you managed to solve it ? I have a code on my application that works if you are interested.
Also, don't forget to add in the headers of the curl request:
Content-Type: application/json
Solved with Kucoin support and pythone example.
The "body" also must be included in POST request.
Was:
reply = netman->post(req, "");
Become:
tradereply = trademan->post(req, data);

How to add functions like generating random UUID in velocity template for request/response mapping in API gateway

I am creating a request mapping template for AWS API gateway. In that template I want to customize the request params based on certain conditions and apply operators.
#foreach($header in $input.params().header.keySet())
#if($header=="id")#set($idVal =
$util.escapeJavaScript($input.params().header.get($header)))
#if($idVal.matches("^[0-9a-f]{4}-[0-9A-Z]{3}$"))
"$header":"$idVal"
#else
#set($random = UUID.randomUUID())
"$header":"$random"
#end
#else
For example, in the above template based on if condition I want to generate randomUUID and add to the header. But when I test, the id value is set to empty string.
How can I use packages and java functions support in velocity template mapping api gateway? Also, please share any reference to wellformed template, it would be really useful to learn more.
VTL as used in API Gateway is not extensible with your own packages. Only the built-in variables and $util functions can be used.
You may find that $context.requestId contains a suitable UUID for your purpose, unique to each request. Note that if you are using a Lambda integration, this value differs from Lambda's context.requestId which only coincidentally has the same name.
Or, the rightmost 33 characters of $context.xrayTraceId should contain a 4 byte timestamp (8 hex digits) + '-' + a 96-bit unique value (24 hex digits) from which you could construct a serviceable UUID with some light string manipulation.
For AppSync users:
You can't use packages but you can use the $util helpers
For example you can use $util.autoId() to generate your UUID.

How to pass response values to Java API from Karate

How can I pass values from Karate API to Java class?
As mentioned in the documentation, I used the following code snippet to get the response from Java API. But its returning the response with un-formatted JSON content.
Map<String, Object> result = CucumberRunner.runClasspathFeature("demo/java/from-java.feature", args, true);
And then, I used the following script to print the response.
for(Map.Entry<String , Object> entry: getMbrWksMembershipDetailsResponse.entrySet())
{
if (entry.getKey().equalsIgnoreCase("response"))
{
System.out.println(entry.getValue());
}
}
It shows like,
{soap:Envelope={_={soap:Body={ns1:getMbrWksMembershipDetailsResponse={_={ns4:WksMembershipSummaryResponse={_={ns2:customerSummary={ns2:address={ns2:city=SOUTH CHESTERFIELD, ns2:country=USA, ns2:isoCountryCode=US, ns2:line1=9998, N. MICHIGAN ROAD., ns2:postalCode=23834, ns2:state=VA}, ns2:allowPasswordChange=true, ns2:arpMember=false, ns2:brandCode=RCI, ns2:brandId=1, ns2:companyCode=RCI, ns2:eliteMemberRewardStatus=false, ns2:eliteRewardStatus=true, ns2:europePointsClubMember=false, ns2:firstName=FRANK, ns2:homePhone=804/733-3004, ns2:isoCurrencyCode=USD, ns2:isoLanguageCode=EN, ns2:language=EN, ns2:lastName=BROWNING B, ns2:locale=en_US, ns2:memberDeveloperRenewed=false, ns2:memberEnrolledDate=2009-10-26T00:00:00-04:00, ns2:memberEnrolledForDirectDebit=false, ns2:memberEnrolledForPltDirectDebit=false, ns2:memberStatus=A, ns2:middleName=B, ns2:msgTranslationLanguageCode=EN, ns2:officePhone=0/-0, ns2:pointsCurrencyCode=0......
So it's little difficult to split the data based on the fields / tags from Map.
Please suggest what is the best option to get the values field wize / tag wise from Java API.
Thanks.
Yes, XML is internally held as a strange Map structure, refer to the section on type-conversion to understand more.
You have a simple way to do this. Just define a new variable that is the response converted to a string.
* xmlstring responseXml = response
After this you just need to get the responseXml out of the Map returned by the Java API which will be a string.
Note: don't use the Java API unless you are really trying to mix Karate with something else. The whole point of Karate is to avoid using Java for testing JSON and XML web-services.

URL encode Postman variable?

I use Postman for REST API testing and parametrize tests with global variables.
I should put a phone number into GET request: /path/get?phone={{phone}} but leading + sign in the phone number is interpreted as a space.
What is the syntax to URL encode global variables in Postman? Is it possible to run JS encodeURIComponent() on variable in URL?
I am late but still worth it:
Just highlight and right click the part of url you want to encode. Select encodeURIComponent
That's it.
Use the Pre-request scripts (it's next to body) for this:
var encoded = encodeURIComponent({{phone number}});
or
var encoded = encodeURIComponent(pm.environment.get("phone number"));
and to proceed, use:
pm.environment.set("encoded phone number", encoded);
And set your URL to /path/get?phone={{encoded phone number}}
Just a shortcut to Mohhamad Hasham' answer.
You can encode and decode direct in the Params Value field:
The trick is to get your environment variable in the pre-request script and then set it after encoding it
var encoded = encodeURIComponent(pm.environment.get("phone"));
pm.environment.set("encoded phone number", encoded);
This will work as well:
var encoded = encodeURIComponent(pm.request.url.query.get("phone"));
pm.request.url.query.remove("phone");
pm.request.url.query.insert("phone", encoded);
I came across this question looking for an answer to a similar question. For me, the variable was a JSON object. The endpoint I needed to hit was expecting an object list as a query parameter and I have no way to change that to be the request body.
As much as some of the answers helped, I ended up coming up with a combined solution. Also, some of the code given in other answers is outdated as Postman has updated their API over the years, so this uses methods that work on 7.22.1.
pm.environment.set("basicJSON", '[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]')
var encoded = encodedURIComponent(pm.environment.get("basicJSON"))
pm.environment.set("encodedJSON", encoded)
This solution requires that both basicJSON and encodedJSON exist as environment variables. But what was important for me was the ease of editing the object. I didn't want to have to decode/encode constantly to change values, and I didn't want to have to open the environment variables dialogue. Also, it's important to note the single-quotes around the object. Excluding them or using double-quotes would cause Postman to send something like "[object Object]" which is useless to an endpoint expecting actual JSON.
I had similar problem with braces { and } in query parameter.
By turning off the following setting it started working for me.
For the postman version 9.28.4 ==>
You can use 2 methods:
By selecting the part of the url in url bar -> right click -> EncodeURLComponent. (screenshot attached)
You can also use "pre-request script" tab of postman and write the script for the variable manually. (screenshot attached)
The problem with right-click => Encode URI Component is that it destroys the raw value of that parameter. You can use the following pre-request script to overcome this (which also works for cases where you have disabled that param):
// queryParam is of type https://www.postmanlabs.com/postman-collection/QueryParam.html
if ((queryParam = pm.request.url.query.one("name_of_your_query_param")) !== undefined
&& queryParam.disabled !== true) {
queryParam.value = encodeURIComponent(queryParam.value);
}
Click the Params button to open the data editor for URL parameters. When you add key-value pairs, Postman combines everything in the query string above. If your URL already has parameters - for example, if you are pasting a URL from some other source. Postman splits the URL into pairs automatically.
https://www.getpostman.com/docs/v6/postman/sending_api_requests/requests
POSTMAN's documentation on building requests in the section "sending parameters" is helpful here. You can encode path data by simply encoding the URL with a colon, listing the key name of the encoded element, and then a new section will appear below the query parameters allowing you to customize values and add a description, just as we do with query params. Here's an example of encoding the URL for a GET request:
https://somesite-api-endpoint/:record/get
And here's what the display looks like after you add path data. Any value you add in the path variables section will automagically update the URL with your data.

How can I convert Lua HMAC SHA256 digest to a hexadecimal string (creates Facebook appsecret_proof token)?

I've been spending time reading about the HTTPLuaModule for Nginx and find that there are some great ways developers have been able to SHA256 sign Amazon Web Services using a key and string. As a junior developer who is a Lua noob, I would like to use the HTTPLuaModule to generate Facebook appsecret_proof tokens. Currently I found that there is the LuaCrypto module for Lua to generate HMAC via SHA256 but it doesn't exactly match the implementation needed for Facebook's token:
digest = crypto.hmac.digest('sha256', user-access-token, app-secret, true) ## what next to convert digest into hexadecimal string?
Unlike in the Amazon example above, the token doesn't need to be Base64 encode but instead the HMAC needs to be turned into a string of double length using only hexadecimal digits (hence hexidecimal!).
In Python I can obtain the token with:
import hashlib
import hmac
token = hmac.new(app-secret, user-access-token, hashlib.sha256).hexadecimal()
Thoughts? Any better modules that have methods to convert digest's into hexadecimal strings?
Should be as simple as:
local secretProof = digest:final()
source: http://mkottman.github.io/luacrypto/manual.html#reference