node.js (2561B)
1 var test = require('tape'); 2 3 var crypto = require('crypto'); 4 var cryptoB = require('../'); 5 var fs = require('fs'); 6 7 function assertSame(name, fn) { 8 test(name, function (t) { 9 t.plan(1); 10 fn(crypto, function (err, expected) { 11 fn(cryptoB, function (err, actual) { 12 t.equal(actual, expected); 13 t.end(); 14 }); 15 }); 16 }); 17 } 18 19 var algorithms = ['sha1', 'sha256', 'md5']; 20 var encodings = ['binary', 'hex', 'base64']; 21 22 23 algorithms.forEach(function (algorithm) { 24 encodings.forEach(function (encoding) { 25 assertSame(algorithm + ' hash using ' + encoding, function (crypto, cb) { 26 cb(null, crypto.createHash(algorithm).update('hellø', 'utf-8').digest(encoding)); 27 }) 28 29 assertSame(algorithm + ' hmac using ' + encoding, function (crypto, cb) { 30 cb(null, crypto.createHmac(algorithm, 'secret').update('hellø', 'utf-8').digest(encoding)) 31 }) 32 }); 33 34 assertSame(algorithm + ' with raw binary', function (crypto, cb) { 35 var seed = 'hellø'; 36 for (var i = 0; i < 1000; i++) { 37 seed = crypto.createHash(algorithm).update(new Buffer(seed)).digest('binary'); 38 } 39 cb(null, crypto.createHash(algorithm).update(new Buffer(seed)).digest('hex')); 40 }); 41 42 assertSame(algorithm + ' empty string', function (crypto, cb) { 43 cb(null, crypto.createHash(algorithm).update('').digest('hex')); 44 }); 45 }); 46 47 function pad(n, w) { 48 n = n + ''; return new Array(w - n.length + 1).join('0') + n; 49 } 50 51 var vectors = fs.readdirSync(__dirname + '/vectors').sort(). 52 filter(function (t) { return t.match(/\.dat$/); }). 53 map(function (t) { return fs.readFileSync(__dirname + '/vectors/' + t); }); 54 55 ['md5', 'sha1', 'sha256'].forEach(function (algorithm) { 56 test(algorithm, function (t) { 57 function hash(data) { return cryptoB.createHash(algorithm).update(data).digest('hex'); } 58 59 var hashes = fs.readFileSync(__dirname + '/vectors/byte-hashes.' + algorithm).toString().split(/\r?\n/); 60 t.plan(vectors.length); 61 for (var i = 0; i < vectors.length; i++) { 62 t.equal(hash(vectors[i]), hashes[i], 'byte' + pad(i, 4) + '.dat'); 63 } 64 }); 65 }); 66 67 test('randomBytes', function (t) { 68 t.plan(5); 69 t.equal(cryptoB.randomBytes(10).length, 10); 70 t.ok(cryptoB.randomBytes(10) instanceof Buffer); 71 cryptoB.randomBytes(10, function(ex, bytes) { 72 t.error(ex); 73 t.equal(bytes.length, 10); 74 t.ok(bytes instanceof Buffer); 75 t.end(); 76 }); 77 });