create-hash.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. var test = require('tape');
  3. var satisfies = require('semver').satisfies;
  4. var algorithms = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'];
  5. var encodings = ['hex', 'base64']; // FIXME: test binary
  6. var vectors = require('hash-test-vectors');
  7. function runTest(name, createHash, algorithm) {
  8. var isUnsupported = satisfies(process.version, '^17') && (
  9. algorithm === 'rmd160'
  10. || algorithm === 'hmac(rmd160)'
  11. );
  12. test(
  13. name + ' test ' + algorithm + ' against test vectors',
  14. { skip: isUnsupported && 'this node version does not support ' + algorithm },
  15. function (t) {
  16. vectors.forEach(function (obj, i) {
  17. var input = new Buffer(obj.input, 'base64');
  18. var node = obj[algorithm];
  19. var js = createHash(algorithm).update(input).digest('hex');
  20. t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node);
  21. encodings.forEach(function (encoding) {
  22. var eInput = new Buffer(obj.input, 'base64').toString(encoding);
  23. var eNode = obj[algorithm];
  24. var eJS = createHash(algorithm).update(eInput, encoding).digest('hex');
  25. t.equal(eJS, eNode, algorithm + '(testVector[' + i + '], ' + encoding + ') == ' + eNode);
  26. });
  27. input = new Buffer(obj.input, 'base64');
  28. node = obj[algorithm];
  29. var hash = createHash(algorithm);
  30. hash.end(input);
  31. js = hash.read().toString('hex');
  32. t.equal(js, node, algorithm + '(testVector[' + i + ']) == ' + node);
  33. });
  34. t.end();
  35. }
  36. );
  37. }
  38. function testLib(name, createHash) {
  39. algorithms.forEach(function (algorithm) {
  40. runTest(name, createHash, algorithm);
  41. });
  42. }
  43. testLib('createHash in crypto-browserify', require('../').createHash);
  44. testLib('create-hash/browser', require('create-hash/browser'));