postmansha256postman-pre-request-script

errore with messageSignature sha256 in postman (base64 is notdefined.)


I'm testing an api that i have to send in body those data acording to documentation:

studentId,
apiKey,
timeStamp (current iso time as a string),
messageSignature: apikey+studentId+timeStamp encrypted using sha256,

i wrote a script to generate message signature using sha256 in Pre-request Script. Pre-request Script:


    var dateIso = new Date().toISOString();
    pm.globals.set("isoDateTostring", dateIso);
    console.log('timestamp var is:', pm.globals.get("isoDateTostring"));
    
    let msg = "apiKeyvalue" + "studentId" + pm.globals.get("isoDateTostring");+ JSON.stringify(msg)
    
    const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, "secretKey");
    hmac.update(msg);
    const messageSignature = hmac.finalize().toString();

Details (like screenshots): in body i wrote:

{
"studentId":"********",
"apiKey":"************",
"timeStamp":{{$isoDateTostring}},
"messageSignature": {{$messageSignature}}
}

when i send the request i get base64 is notdefined.

enter image description here


Solution

  • Code would be like:

    In Tab Body:

    {{$isoDateTostring}} --> "{{isoDateTostring}}"

    {{$messageSignature}} --> "{{messageSignature}}"

    {
        "studentId": "123",
        "apiKey": "123abc",
        "timeStamp": "{{isoDateTostring}}",
        "messageSignature": "{{messageSignature}}"
    }
    

    In tab Pre-request: I fake studentId and apiKey

    const dateIso = new Date().toISOString();
    pm.globals.set("isoDateTostring", dateIso);
    
    const studentId = "123";
    const apiKeyvalue = "123abc"
    let msg = apiKeyvalue + studentId + pm.globals.get("isoDateTostring");
    
    const messageSignature = CryptoJS.SHA256(msg).toString();
    pm.globals.set("messageSignature", messageSignature);
    

    Result:

    {
        "studentId": "123",
        "apiKey": "123abc",
        "timeStamp": "2021-10-26T13:20:09.068Z",
        "messageSignature": "783e65ff1cfb2374fb5f84daa35c01d18b8a1898b3a1837e84934e91a3c0720d"
    }