Guidline How to Using External Lib JSENScrypt in postman

  1. URL to get jsEncrypt lib: https://raw.githubusercontent.com/travist/jsencrypt/master/bin/jsencrypt.js

  2. save URL at step 1 in global Varaible with name “jsEncrypt”;

  3. In Pre-request Script, write script as below:

    navigator  = {};
    window = {};
    pm.sendRequest(pm.globals.get("jsEncrypt"), (err, res) => {
    var text = res.text();
    (new Function(text))();
    var jsencrypt = new JSEncrypt.JSEncrypt({
            default_key_size: 4096
    });
    jsencrypt.setKey( "// here is public key" );
    var result = jsencrypt.encrypt("// here is you clear value before you want to encrypt");
    console.log(CryptoJS.enc.Base64.parse(result).toString());

Hope can help you all.

Hi Hoc.Tran,

Could you please help me to execute your code?
I tried to execute your code in the Postmans Pre-request script but it is not working.
It is having a syntax error and when the syntax error is resolved, JSEncrypt is not defined error is coming.

Below is the working code…
window = {};
pm.sendRequest(pm.globals.get(“jsEncrypt”), (err, res) => {
var text = res.text();
(new Function(text))();
var jsencrypt = new window.JSEncrypt;
jsencrypt.setPublicKey("//here is public key");
var result = jsencrypt.encrypt("//here is you clear value before you want to encrypt");
});

1 Like

hi ravi, I’m getting error “window.JSEncrypt is not a constructor”

it is working for me like this:

navigator= {};
window = {};
var a=eval(pm.environment.get(“jsencrypt”));
var encrypt = new window.JSEncrypt();
var base64publicKey = postman.getEnvironmentVariable(“publicKeyBase64”);
var publicKey = atob(base64publicKey); //get public key by decode Base64
publicKey = publicKey.replace(“-----BEGIN PUBLIC KEY-----”, “”);
publicKey = publicKey.replace(“-----END PUBLIC KEY-----”, “”);
publicKey = publicKey.replace(/\n/g, “”);
encrypt.setPublicKey(publicKey);
pm.environment.set(“usernameEncrypted”, encrypt.encrypt(pm.environment.get(“username”)));
pm.environment.set(“passwordEncrypted”, encrypt.encrypt(pm.environment.get(“password”)));