无法在Protractor中使用公钥加密字符串

时间:2016-04-30 04:45:11

标签: protractor jsencrypt

我正在尝试调用下面提到的加密函数:

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);
}

最初,我收到未定义的JSEncrypt的参考错误。 所以我下载了 jsencrypt.js 文件并在开头添加了var encryptor = require("./jsencrypt.js");

现在我收到了以下错误:

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)

尝试在jsencrypt.js中使用windows.navigator,但没有用。

4 个答案:

答案 0 :(得分:1)

量角器测试不是在浏览器环境中运行,而是在node.js中运行,因为导航器对象在那里不可用。 JSEncrypt依赖于它在不同浏览器和版本的客户端工作。

它在JSEncrypt代码的许多地方被引用,所以我最好的选择是切换到可以为你工作的服务器端加密库,或者如果不可能模拟具有所有预期属性/方法的全局导航器json对象,就好像它是一个Chrome浏览器 - node.js在chrome的js引擎上运行,所以应该可以正常工作。

答案 1 :(得分:1)

我的一位同事帮助我解决了这个问题。 所以我在这里有一个加密功能:

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...");
}

此功能由以下人员调用:

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);
  }

}

希望这有助于他人。

答案 2 :(得分:1)

在require('jsencrypt')之前,您可以先编写:

const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
global.window = window;
global.document = window.document;
global.navigator ={userAgent: 'node.js'};

const { JSEncrypt } = require('jsencrypt')

答案 3 :(得分:0)

您可以通过执行以下操作来模拟:

global.navigator = {appName:'量角器'};

global.window = {};

const JSEncrypt = require('JSEncrypt')。default;