jjzjj

javascript - 基准测试 WebCrypto 比第三方库慢得多?

coder 2024-12-13 原文

我正在评估 WebCrypto 性能与第三方加密库的比较 SJCLForge .我希望 WebCrypto 快得多,因为它是 native 浏览器实现。这也是benchmarked before并且已经证明了这一点。

我已经使用 Benchmark.js 实现了以下测试测试 key 派生 (PBKDF2-SHA256)、加密 (AES-CBC) 和解密 (AES-CBC)。这些测试表明网络加密在加密/解密方面比 SJCL 和 Forge 慢得多。

基准代码

在这里查看 fiddle :https://jsfiddle.net/kspearrin/1Lzvpzkz/

var iterations = 5000;
var keySize = 256;

sjcl.beware['CBC mode is dangerous because it doesn\'t protect message integrity.']();

// =========================================================
// Precomputed enc values for decrypt benchmarks
// =========================================================

var encIv = 'FX7Y3pYmcLIQt6WrKc62jA==';
var encCt = 'EDlxtzpEOfGIAIa8PkCQmA==';

// =========================================================
// Precomputed keys for benchmarks
// =========================================================

function sjclMakeKey() {
  return sjcl.misc.pbkdf2('mypassword', 'a salt', iterations, keySize, null);
}

var sjclKey = sjclMakeKey();

function forgeMakeKey() {
  return forge.pbkdf2('mypassword', 'a salt', iterations, keySize / 8, 'sha256');
}

var forgeKey = forgeMakeKey();

var webcryptoKey = null;
window.crypto.subtle.importKey(
  'raw', fromUtf8('mypassword'), {
    name: 'PBKDF2'
  },
  false, ['deriveKey', 'deriveBits']
).then(function(importedKey) {
  window.crypto.subtle.deriveKey({
      'name': 'PBKDF2',
      salt: fromUtf8('a salt'),
      iterations: iterations,
      hash: {
        name: 'SHA-256'
      }
    },
    importedKey, {
      name: 'AES-CBC',
      length: keySize
    },
    true, ['encrypt', 'decrypt']
  ).then(function(derivedKey) {
    webcryptoKey = derivedKey;
  });
});

// =========================================================
// IV helpers for encrypt benchmarks so all are using same PRNG methods
// =========================================================

function getRandomSjclBytes() {
  var bytes = new Uint32Array(4);
  return window.crypto.getRandomValues(bytes);
}

function getRandomForgeBytes() {
  var bytes = new Uint8Array(16);
  window.crypto.getRandomValues(bytes);
  return String.fromCharCode.apply(null, bytes);
}

// =========================================================
// Serialization helpers for web crypto
// =========================================================

function fromUtf8(str) {
  var strUtf8 = unescape(encodeURIComponent(str));
  var ab = new Uint8Array(strUtf8.length);
  for (var i = 0; i < strUtf8.length; i++) {
    ab[i] = strUtf8.charCodeAt(i);
  }
  return ab;
}

function toUtf8(buf, inputType) {
  inputType = inputType || 'ab';

  var bytes = new Uint8Array(buf);
  var encodedString = String.fromCharCode.apply(null, bytes),
    decodedString = decodeURIComponent(escape(encodedString));
  return decodedString;
}

function fromB64(str) {
  var binary_string = window.atob(str);
  var len = binary_string.length;
  var bytes = new Uint8Array(len);
  for (var i = 0; i < len; i++) {
    bytes[i] = binary_string.charCodeAt(i);
  }
  return bytes.buffer;
}

function toB64(buf) {
  var binary = '';
  var bytes = new Uint8Array(buf);
  var len = bytes.byteLength;
  for (var i = 0; i < len; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return window.btoa(binary);
}

// =========================================================
// The benchmarks
// =========================================================

$("#makekey").click(function() {
  console.log('Starting test: Make Key (PBKDF2)');

  var suite = new Benchmark.Suite;

  suite
    .add('SJCL', function() {
      sjclMakeKey();
    })
    .add('Forge', function() {
      forgeMakeKey();
    })
    .add('WebCrypto', {
      defer: true,
      fn(deferred) {
        window.crypto.subtle.importKey(
          'raw', fromUtf8('mypassword'), {
            name: 'PBKDF2'
          },
          false, ['deriveKey', 'deriveBits']
        ).then(function(importedKey) {
          window.crypto.subtle.deriveKey({
              'name': 'PBKDF2',
              salt: fromUtf8('a salt'),
              iterations: iterations,
              hash: {
                name: 'SHA-256'
              }
            },
            importedKey, {
              name: 'AES-CBC',
              length: keySize
            },
            true, ['encrypt', 'decrypt']
          ).then(function(derivedKey) {
            window.crypto.subtle.exportKey('raw', derivedKey)
              .then(function(exportedKey) {
                deferred.resolve();
              });
          });
        });
      }
    })
    .on('cycle', function(event) {
      console.log(String(event.target));
    })
    .on('complete', function() {
      console.log('Fastest is ' + this.filter('fastest').map('name'));
    })
    .run({
      'async': true
    });
});

// =========================================================
// =========================================================

$("#encrypt").click(function() {
  console.log('Starting test: Encrypt');

  var suite = new Benchmark.Suite;

  suite
    .add('SJCL', function() {
      var response = {};
      var params = {
        mode: 'cbc',
        iv: getRandomSjclBytes()
      };
      var ctJson = sjcl.encrypt(sjclKey, 'some message', params, response);

      var result = {
        ct: ctJson.match(/"ct":"([^"]*)"/)[1],
        iv: sjcl.codec.base64.fromBits(response.iv)
      };
    })
    .add('Forge', function() {
      var buffer = forge.util.createBuffer('some message', 'utf8');
      var cipher = forge.cipher.createCipher('AES-CBC', forgeKey);
      var ivBytes = getRandomForgeBytes();
      cipher.start({
        iv: ivBytes
      });
      cipher.update(buffer);
      cipher.finish();
      var encryptedBytes = cipher.output.getBytes();

      var result = {
        iv: forge.util.encode64(ivBytes),
        ct: forge.util.encode64(encryptedBytes)
      };
    })
    .add('WebCrypto', {
      defer: true,
      fn(deferred) {
        var ivBytes = window.crypto.getRandomValues(new Uint8Array(16));
        window.crypto.subtle.encrypt({
          name: 'AES-CBC',
          iv: ivBytes
        }, webcryptoKey, fromUtf8('some message')).then(function(encrypted) {
          var ivResult = toB64(ivBytes);
          var ctResult = toB64(encrypted);
          deferred.resolve();
        });
      }
    })
    .on('cycle', function(event) {
      console.log(String(event.target));
    })
    .on('complete', function() {
      console.log('Fastest is ' + this.filter('fastest').map('name'));
    })
    .run({
      'async': true
    });
});

// =========================================================
// =========================================================

$("#decrypt").click(function() {
  console.log('Starting test: Decrypt');

  var suite = new Benchmark.Suite;

  suite
    .add('SJCL', function() {
      var ivBits = sjcl.codec.base64.toBits(encIv);
      var ctBits = sjcl.codec.base64.toBits(encCt);
      var aes = new sjcl.cipher.aes(sjclKey);

      var messageBits = sjcl.mode.cbc.decrypt(aes, ctBits, ivBits, null);
      var result = sjcl.codec.utf8String.fromBits(messageBits);
    })
    .add('Forge', function() {
      var decIvBytes = forge.util.decode64(encIv);
      var ctBytes = forge.util.decode64(encCt);
      var ctBuffer = forge.util.createBuffer(ctBytes);

      var decipher = forge.cipher.createDecipher('AES-CBC', forgeKey);
      decipher.start({
        iv: decIvBytes
      });
      decipher.update(ctBuffer);
      decipher.finish();

      var result = decipher.output.toString('utf8');
    })
    .add('WebCrypto', {
      defer: true,
      fn(deferred) {
        var ivBytes = fromB64(encIv);
        var ctBytes = fromB64(encCt);

        window.crypto.subtle.decrypt({
          name: 'AES-CBC',
          iv: ivBytes
        }, webcryptoKey, ctBytes).then(function(decrypted) {
          var result = toUtf8(decrypted);
          deferred.resolve();
        });
      }
    })
    .on('cycle', function(event) {
      console.log(String(event.target));
    })
    .on('complete', function() {
      console.log('Fastest is ' + this.filter('fastest').map('name'));
    })
    .run({
      'async': true
    });
});

基准测试结果(Chrome)

Starting test: Make Key (PBKDF2)
SJCL x 26.31 ops/sec ±1.11% (37 runs sampled)
Forge x 13.55 ops/sec ±1.46% (26 runs sampled)
WebCrypto x 172 ops/sec ±2.71% (58 runs sampled)
Fastest is WebCrypto

Starting test: Encrypt
SJCL x 42,618 ops/sec ±1.43% (60 runs sampled)
Forge x 76,653 ops/sec ±1.76% (60 runs sampled)
WebCrypto x 18,011 ops/sec ±5.16% (47 runs sampled)
Fastest is Forge

Starting test: Decrypt
SJCL x 79,352 ops/sec ±2.51% (50 runs sampled)
Forge x 154,463 ops/sec ±2.12% (61 runs sampled)
WebCrypto x 22,368 ops/sec ±4.08% (53 runs sampled)
Fastest is Forge

基准测试结果(Firefox)

Starting test: Make Key (PBKDF2)
SJCL x 20.21 ops/sec ±1.18% (34 runs sampled)
Forge x 11.63 ops/sec ±6.35% (30 runs sampled)
WebCrypto x 101 ops/sec ±9.68% (46 runs sampled)
Fastest is WebCrypto

Starting test: Encrypt
SJCL x 32,135 ops/sec ±4.37% (51 runs sampled)
Forge x 99,216 ops/sec ±7.50% (47 runs sampled)
WebCrypto x 11,458 ops/sec ±2.79% (52 runs sampled)
Fastest is Forge

Starting test: Decrypt
SJCL x 87,290 ops/sec ±4.35% (45 runs sampled)
Forge x 114,086 ops/sec ±6.76% (46 runs sampled)
WebCrypto x 10,170 ops/sec ±3.69% (42 runs sampled)
Fastest is Forge

这是怎么回事?为什么 WebCrypto 的加密/解密功能要慢得多?我是否错误地使用了 Benchmark.js?

最佳答案

我有一种预感,对于如此短的消息长度,您主要是在测量调用开销。凭借其基于异步 promise 的接口(interface),WebCrypto 可能会在这方面有所损失。

我修改了您的加密基准以使用 1.5 kib 明文,结果看起来非常不同:

Starting test: Encrypt
SJCL x 3,632 ops/sec ±2.20% (61 runs sampled)
Forge x 2,968 ops/sec ±3.02% (60 runs sampled)
WebCrypto x 5,522 ops/sec ±6.94% (42 runs sampled)
Fastest is WebCrypto

对于 96 kb 的明文,差异更大:

Starting test: Encrypt
SJCL x 56.77 ops/sec ±5.43% (49 runs sampled)
Forge x 48.17 ops/sec ±1.12% (41 runs sampled)
WebCrypto x 162 ops/sec ±4.53% (45 runs sampled)
Fastest is WebCrypto

关于javascript - 基准测试 WebCrypto 比第三方库慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42772569/

有关javascript - 基准测试 WebCrypto 比第三方库慢得多?的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  3. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  4. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  5. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  6. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  7. ruby - 即使失败也继续进行多主机测试 - 2

    我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r

  8. ruby-on-rails - 如何使辅助方法在 Rails 集成测试中可用? - 2

    我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel

  9. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  10. ruby-on-rails - 如何调试 cucumber 测试? - 2

    我有:When/^(?:|I)follow"([^"]*)"(?:within"([^"]*)")?$/do|link,selector|with_scope(selector)doclick_link(link)endend我打电话的地方:Background:GivenIamanexistingadminuserWhenIfollow"CLIENTS"我的HTML是这样的:CLIENTS我一直收到这个错误:.F-.F--U-----U(::)failedsteps(::)nolinkwithtitle,idortext'CLIENTS'found(Capybara::Element

随机推荐