rsasha256cryptojsrunscope

How to sign request with private key in Runscope test?


I am trying to add Runscope test to verify signature of the request I am sending. In first step I want to sign this request, and then send it to the service which is going to verify it.

I know I can add script in Runscope and that I can use CryptoJS for signing the request. However documentation for CryptoJS is not very helpful and I fail to sign my request;

I have something similar done in Postman using Crypto Postman lib, and the code is:

function encryptSignature(signingMetadata) {
            eval(pm.globals.get('pmlib_code'));
            var encryptedSignature = new pmlib.rs.KJUR.crypto.Signature({ "alg": "SHA256withRSA" });
            encryptedSignature.init(config.privateKey)
            var hash2 = encryptedSignature.signString(signingMetadata)
            const signedEncoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(hash2));
            return signedEncoded;
        }

trying to do something similar in Runscope I came up with this code:

function encryptSignature(signingMetadata) {
    var hash = CryptoJS.SHA256withRSA(signingMetadata, config.privateKey);
    var signedEncoded = hash.toString(CryptoJS.enc.Base64);
        return signedEncoded;
    }

but got error for undefined which I assume is CryptoJS;

I used some online JS compilers and when I import

import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';

and refactor code to:

var signedEncoded = Base64.stringify(sha256(signingMetadata, config.privateKey));

it compiles and does some kind of signing, but signature does not look right (it is way too short)

Anyone done this successfully before in Runscope? I would appreciate some advice;

Thank you,


Solution

  • As @Topaco mentioned, CryptoJS doesn't support RSA cryptography.

    You can generate signature using jsrsasign and CryptoJS library however it's tricky to get this working due to Runscope limitations. The following code snippet is generating signature:

    var signature = new KJUR.crypto.Signature({ "alg": "SHA256withRSA" });
    signature.init(privateKey); // just key as a string
    var hash = signature.signString("string to sign");
    const encodedSignature = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(hash));
    return encodedSignature;
    

    but in order to get this working do the following:

    1. from the jsrsasign repo, import jsrsasign-rsa-min.js and keyutil-1.0.js as a Runscope script library / code snippet (optionally merge these files together)
    2. get rid of arrow functions (Runscope limitation).
    3. get rid of all window references (Runscope limitation). jsrsasign uses this to detect older browsers - not necessary in this case as we run this script only in the Runscope environment.
    4. (optionally) get rid of CryptoJS from the jsrsasign-rsa-min.js file as it's already available in the Runscope environment.
    5. Import the above library to the test