1'use strict'; 2const common = require('../common.js'); 3 4const bench = common.createBenchmark(main, { 5 writes: [500], 6 cipher: ['AES192', 'AES256'], 7 type: ['asc', 'utf', 'buf'], 8 len: [2, 1024, 102400, 1024 * 1024], 9 api: ['legacy', 'stream'], 10}, { 11 flags: ['--no-warnings'], 12}); 13 14function main({ api, cipher, type, len, writes }) { 15 if (api === 'stream' && /^v0\.[0-8]\./.test(process.version)) { 16 console.error('Crypto streams not available until v0.10'); 17 // Use the legacy, just so that we can compare them. 18 api = 'legacy'; 19 } 20 21 const crypto = require('crypto'); 22 const assert = require('assert'); 23 const alice = crypto.getDiffieHellman('modp5'); 24 const bob = crypto.getDiffieHellman('modp5'); 25 26 alice.generateKeys(); 27 bob.generateKeys(); 28 29 const pubEnc = /^v0\.[0-8]/.test(process.version) ? 'binary' : null; 30 const alice_secret = alice.computeSecret(bob.getPublicKey(), pubEnc, 'hex'); 31 const bob_secret = bob.computeSecret(alice.getPublicKey(), pubEnc, 'hex'); 32 33 // alice_secret and bob_secret should be the same 34 assert(alice_secret === bob_secret); 35 36 const alice_cipher = crypto.createCipher(cipher, alice_secret); 37 const bob_cipher = crypto.createDecipher(cipher, bob_secret); 38 39 let message; 40 let encoding; 41 switch (type) { 42 case 'asc': 43 message = 'a'.repeat(len); 44 encoding = 'ascii'; 45 break; 46 case 'utf': 47 message = 'ü'.repeat(len / 2); 48 encoding = 'utf8'; 49 break; 50 case 'buf': 51 message = Buffer.alloc(len, 'b'); 52 break; 53 default: 54 throw new Error(`unknown message type: ${type}`); 55 } 56 57 const fn = api === 'stream' ? streamWrite : legacyWrite; 58 59 // Write data as fast as possible to alice, and have bob decrypt. 60 // use old API for comparison to v0.8 61 bench.start(); 62 fn(alice_cipher, bob_cipher, message, encoding, writes); 63} 64 65function streamWrite(alice, bob, message, encoding, writes) { 66 let written = 0; 67 bob.on('data', (c) => { 68 written += c.length; 69 }); 70 71 bob.on('end', () => { 72 // Gbits 73 const bits = written * 8; 74 const gbits = bits / (1024 * 1024 * 1024); 75 bench.end(gbits); 76 }); 77 78 alice.pipe(bob); 79 80 while (writes-- > 0) 81 alice.write(message, encoding); 82 83 alice.end(); 84} 85 86function legacyWrite(alice, bob, message, encoding, writes) { 87 let written = 0; 88 let enc, dec; 89 for (let i = 0; i < writes; i++) { 90 enc = alice.update(message, encoding); 91 dec = bob.update(enc); 92 written += dec.length; 93 } 94 enc = alice.final(); 95 dec = bob.update(enc); 96 written += dec.length; 97 dec = bob.final(); 98 written += dec.length; 99 const gbits = written / (1024 * 1024 * 1024); 100 bench.end(gbits); 101} 102