电子在单独的线程上运行加密Diffie Hellman密钥

时间:2019-01-03 21:28:11

标签: node.js cryptography electron diffie-hellman

在电子应用程序中,我通过以下方法创建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;

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

2 个答案:

答案 0 :(得分:2)

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

Electron基本上具有DOM和node.js的所有内容以及更多内容,因此您有一些选择。通常,它们是:

  1. Web worker(仅渲染器进程)。如果在渲染器过程中执行此操作,则只能使用纯DOM Web工作器。它们在单独的进程或线程中运行(不确定哪个是铬实现的细节,但绝对不会阻止您的UI)。
  2. Electron中似乎还提供了node.js worker_threads(仅适用于渲染器进程?)。也许也可以,永远不要亲自使用它们。
  3. 您始终可以创建另一个渲染器进程,并将其用作单独的“线程”,并通过IPC与之通信。工作完成后,您只需将其关闭即可。您可以通过创建一个新的隐藏的BrowserWindow来实现。
  4. 使用node.js的cluster / child_process模块​​启动一个新的节点进程,并使用其内置的IPC(而非Electron的)与之通信。

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

答案 1 :(得分:0)

针对您的问题,我尝试的最佳解决方案是基于answer的以下代码:

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库将为您提供所需的内容。这种方法的唯一缺点是,您无法将线程内生成的对象传递到线程范围之外。同样,执行线程的函数内部的代码是某种隔离的代码,因此您可能需要重新包含所需的任何库,如上所示。