从NPM使用threads
库我尝试使用一个单独的线程,而不是主要的一个创造非阻塞方式的Diffie Hellman的:
const spawn = require('threads').spawn;
const thread = spawn(function(input, done) {
const cryptot = require('crypto');
const dh = cryptot.createDiffieHellman(2048);
done({dh});
});
thread.send({p:null, g:null}).on('message', (response) => {
console.log(response.dh.getPrime(), response.dh.getGenerator());
thread.kill();
}).on('error', (err)=>{
console.error(err);
}).on('exit', function() {
console.log('Worker has been terminated.');
});
但我得到以下错误:
/home/pcmagas/Kwdikas/master_thesis/custom_xmpp/dummy_src/thread_dh.js:10
console.log(response.dh.getPrime(), response.dh.getGenerator());
^
TypeError: response.dh.getPrime is not a function
at Worker.thread.send.on (/home/pcmagas/Kwdikas/master_thesis/custom_xmpp/dummy_src/thread_dh.js:10:27)
at Worker.emit (/home/pcmagas/Kwdikas/master_thesis/custom_xmpp/node_modules/eventemitter3/index.js:129:35)
at Worker.handleMessage (/home/pcmagas/Kwdikas/master_thesis/custom_xmpp/node_modules/threads/lib/worker.node/worker.js:148:17)
at ChildProcess.emit (events.js:182:13)
at emit (internal/child_process.js:812:12)
你知道为什么收到的dh
对象不包含方法getPrime
并通过假设的getGenerator
呢?
那么它是真的,没有proviting发电机和总理密钥生成是在node.js中提供的实现缓慢 但是,它使慢是正确的素数和产生,其中主要将是2048位的创建。
所以,你可以做到以下几点:
- 生成的线程内初次和发电机
- 通过完成回调传递素ABD发生器的
message
事件 - 重新创建的Diffie-Hellman对象有与生成素数和产生。
这些步骤将导致从这样的代码:
const spawn = require('threads').spawn;
const thread = spawn(function(input, done) {
const cryptot = require('crypto');
console.time('dh-thread');
const dh = cryptot.createDiffieHellman(2048);
console.timeEnd('dh-thread');
done({prime: dh.getPrime().toString('hex'), generator: dh.getGenerator().toString('hex')});
});
thread.send({p:null, g:null}).on('message', (response) => {
const cryptot = require('crypto');
const dh = cryptot.createDiffieHellman(response.prime, response.generator);
// Do whatever you want there
thread.kill();
}).on('error', (err)=>{
console.error(err);
}).on('exit', function() {
console.log('Worker has been terminated.');
});
也证明我上面让我使用计时器修改代码一点:
const spawn = require('threads').spawn;
const thread = spawn(function(input, done) {
const cryptot = require('crypto');
console.time('dh-thread');
const dh = cryptot.createDiffieHellman(2048);
console.timeEnd('dh-thread');
done({prime: dh.getPrime().toString('hex'), generator: dh.getGenerator().toString('hex')});
});
thread.send({p:null, g:null}).on('message', (response) => {
console.time('dh');
const cryptot = require('crypto');
const dh = cryptot.createDiffieHellman(response.prime, response.generator);
console.timeEnd('dh');
thread.kill();
}).on('error', (err)=>{
console.error(err);
}).on('exit', function() {
console.log('Worker has been terminated.');
});
上面的代码的执行将导致:
dh-thread: 12815.747ms
dh: 6.733ms
Worker has been terminated.
正如你可以看到的Diffie Hellman的生成程序,而素数和产生需要的时间太长 ,而不是提供素数和产生。
文章来源: Generate Diffie Hellman Object using npm `threads` module: getPrime is undefined