Electron 运行 在单独的线程上生成加密 Diffie Hellman 密钥

Electron run cryptographic Diffie Hellman Key generation on a seperate thread

在我的电子应用程序中,我通过以下方法创建 Diffie-Hellman 密钥:

const crypto = require('crypto');

/**
 * Generate the keys and the diffie hellman key agreement object.
 * @param {Integer} p The prime for Diffie Hellman Key Generation
 * @param {Integer} g The generator for Diffie Hellman Key Exchange
 */
async function createSelfKey(p, g, callback) {
  let returnVal = null;
  if (p && g) {
    returnVal = { dh: await crypto.createDiffieHellman(p, g) };
  } else {
    returnVal = { dh: await crypto.createDiffieHellman(2048) };
  }
  returnVal.keys = await returnVal.dh.generateKeys();
  return callback(returnVal);
};

但是密钥生成是一个计算量稍大的过程,因此它使我的应用程序冻结。一个用法示例是当我尝试从以下函数实现此方法 generateCreatorKeys 时:

function ChatRoomStatus() {
  /**
   * @var {Object}
   */
  const chatrooms = {};

  // Some other logic
    /**
   * This Method fetched the creator of the Chatroom and executes a callback on it.
   * @param {String} chatroom The chatroom to fetch the creator
   * @param {Function} callback The callback of the chatroom.
   */
  this.processCreator = (chatroom, callback) => {
    const index = _.findIndex(chatrooms[chatroom].friends, (friend) => friend.creator);
    return callback(chatrooms[chatroom].friends[index], index , chatrooms[chatroom] );
  };


  /**
   * Generate keys for the Chatroom Creator:
   * @param {String} chatroom The chatroom to fetch the creator
   * @param {Function} callback The callback of the chatroom.
   */
  this.generateCreatorKeys =  (chatroom, callback) => {
    return this.processCreator(chatroom, (friend, index, chatroom) => {
       return createSelfKey(null, null, (cryptoValues) => {
        friend.encryption = cryptoValues;
        return callback(friend, index, chatroom);
       });
    });
  };
};

调用此方法的示例是:

const { xml, jid } = require('@xmpp/client');

/**
 * Handling the message Exchange for group Key agreement 
 * @param {Function} sendMessageCallback 
 * @param {ChatRoomStatus} ChatroomWithParticipants 
 */
function GroupKeyAgreement(sendMessageCallback, ChatroomWithParticipants) {
  const self = this;
  /**
   * Send the Owner participant Keys into the Chatroom
   */
  self.sendSelfKeys = (chatroomJid, chatroomName) => {
    ChatroomWithParticipants.generateCreatorKeys(chatroomName, (creator) => {
      const message = xml('message', { to: jid(chatroomJid).bare().toString()+"/"+creator.nick });
      const extention = xml('x', { xmlns: 'http://pcmagas.tk/gkePlusp#intiator_key' });
      extention.append(xml('p', {}, creator.encryption.dh.getPrime().toString('hex')));
      extention.append(xml('g', {}, creator.encryption.dh.getGenerator().toString('hex')));
      extention.append(xml('pubKey', {}, creator.encryption.keys.toString('hex')));
      message.append(extention);
      sendMessageCallback(message);
    });
  };
};

module.exports = GroupKeyAgreement;

您知道我如何在 parallel/seperate 线程中 "run" 函数 createSelfKey 并通过回调提供其内容吗?此外,上面的代码在 Electron 的主进程上运行,因此它的冻结会导致整个应用程序停止一段时间。

我会看看 https://electronjs.org/docs/tutorial/multithreading

Electron 基本上包含了 DOM 和 node.js 的所有内容以及更多内容,因此您有一些选择。一般来说,它们是:

  1. 网络工作者(仅限渲染器进程)。如果您在渲染器进程中执行此操作,则可以只使用普通的 DOM 网络工作者。这些 运行 在一个单独的进程或线程中(不确定是哪个,这是一个 chromium 实现细节,但它绝对不会阻止你的 UI)。
  2. 看起来 node.js worker_threads(仅限渲染器进程?)现在也可以在 Electron 中使用。这可能也有用,我从来没有亲自使用过这些。
  3. 您始终可以创建另一个渲染器进程并将其用作单独的 "thread" 并通过 IPC 与其通信。工作完成后,您只需关闭它即可。您可以通过创建一个新的、隐藏的 BrowserWindow 来做到这一点。
  4. 使用 node.js' cluster/child_process 模块启动一个新的节点进程,并使用它的内置 IPC(不是 Electron 的)与其通信。

因为您 运行 在主进程中使用此代码并假设您无法将其移出,所以您唯一的选择(据我所知)是#3。如果您不介意添加一个库,electron-remote (https://github.com/electron-userland/electron-remote#the-renderer-taskpool) 有一些很酷的功能,可以让您在后台启动一个渲染器进程(或多个),得到结果作为承诺,然后关闭他们给你。

我尝试解决您的问题的最佳解决方案是以下基于 :

的代码
const crypto = require('crypto');
const spawn = require('threads').spawn;

/**
 * Generate the keys and the diffie hellman key agreement object.
 * @param {Integer} p The prime for Diffie Hellman Key Generation
 * @param {Integer} g The generator for Diffie Hellman Key Exchange
 * @param {Function} callback The callback in order to provide the keys and the diffie-hellman Object.
 */
const createSelfKey = (p, g, callback) => {

  const thread = spawn(function(input, done) {
    const cryptot = require('crypto');
    console.log(input);
    const pVal = input.p;
    const gVal = input.g;
    let dh = null;

    if (pVal && gVal) {
      dh = cryptot.createDiffieHellman(pVal, gVal);
    } else {
      dh = cryptot.createDiffieHellman(2048);
    }

    const pubKey = dh.generateKeys();
    const signaturePubKey = dh.generateKeys();
    done({ prime: dh.getPrime().toString('hex'), generator: dh.getGenerator().toString('hex'), pubKey, signaturePubKey});
  });

  return thread.send({p,g}).on('message', (response) => {
    callback( crypto.createDiffieHellman(response.prime, response.generator), response.pubKey, response.signaturePubKey);
    thread.kill();
  }).on('error', (err)=>{
    console.error(err);
  }).on('exit', function() {
    console.log('Worker has been terminated.');
  });
};

如您所见,使用 npm 中的 threads 库将为您提供所需的东西。这种方法的唯一缺点是您不能将线程内生成的对象传递到线程范围之外。此外,执行线程的函数内部的代码是某种孤立的代码,因此您可能需要重新包含所需的任何库,如上所示。