protractorjsencrypt

Not able to encrypt a string with a public key in Protractor


I am trying call the encrypt function mentioned below:

var encryptor = require("./jsencrypt.js");
this.encrypt = function () {
  var key="LxVtiqZV6g2D493gDBfG0BfV6sAhteG6hOCAu48qO00Z99OpiaIG5vZxVtiqZV8C7bpwIDAQAB";
  encryptor = new JSEncrypt();
  encryptor.setPublicKey(key);
  var newString = encryptor.encrypt('Password');
  console.log("Encrypted password =",newString);
}

Initially I was getting Reference Error for undefined JSEncrypt. So I downoaded jsencrypt.js file and added var encryptor = require("./jsencrypt.js");at the begining.

Now I am getting following error:

Message:
ReferenceError: navigator is not defined
Stacktrace:
ReferenceError: navigator is not defined
at e:\Praveen Data\Projects\ECP\CentralRegistryUI\TestScripts\Utils\jsencrypt.js:73:13
at Object.<anonymous> (e:\Praveen Data\Projects\ECP\CentralRegistryUI\TestScripts\Utils\jsencrypt.js:4342:3)
at require (module.js:385:17)

Tried using windows.navigator in jsencrypt.js, but didn't work.


Solution

  • One of my colleague helped me with the solution. So here I have a function for encryption:

    this.initializeEncryptedPassword = () => {
        //console.log("before calling encrypt... ");
        browser.executeScript(() => {
          //console.log("Starting to return encryptor...");
          return window.loginEncryptor.encrypt(window.loginPassword);
        }).then((encryptedPassword) => {
          this.encryptedPassword = encryptedPassword;
        });
        //console.log("after calling encrypt...");
    }
    

    This function is being called by:

    export default class Encryptor {
    
      constructor($window, $http) {
        'ngInject';
        this.encryptor = new $window.JSEncrypt();
        //Need to use HTTP here instead of resource since the resource does not return plain text.
        //Getting Public Key by hitting a rest uri.
        $http({method: "GET", url: "/xyz/authenticate"}).success((item) => {
            this.encryptor.setPublicKey(item);
            //set the current encryptor on the window so that testing can use it
            $window.loginEncryptor = this.encryptor;
        });
      }
    
      encryptPassword(credentials) {
        credentials.password = this.encryptor.encrypt(credentials.password);
      }
    
    }
    

    Hope this help others.