diff --git a/interface/core.crypto.json b/interface/core.crypto.json new file mode 100644 index 0000000..7bf9f47 --- /dev/null +++ b/interface/core.crypto.json @@ -0,0 +1,6 @@ +{ + "name": "core.crypto", + "api": { + "getRandomBytes": {"type": "method", "value": ["number"], "ret": "buffer"} + } +} diff --git a/providers/core/core.crypto.js b/providers/core/core.crypto.js new file mode 100644 index 0000000..ea0dcc7 --- /dev/null +++ b/providers/core/core.crypto.js @@ -0,0 +1,31 @@ +/*globals console */ +/*jslint indent:2, node:true */ +var util = require('../../src/util'); + +/** + * A Core provider for getting cryptographically random buffers. This + * functionality may not exist in all unpriviledged contexts - namely at this + * point, firefox addon workers. + * @Class Core_crypto + * @constructor + * @param {module:Module} cap The module creating this provider. + */ +var Core_crypto = function(cap, dispatchEvent) { + this.dispatchEvent = dispatchEvent; + util.handleEvents(this); +}; + +/** + * Get a random buffer of some number of bytes. + * @param {String} str The string to send. + * @param {Function} continuation Function to call when sending is complete. + * @method send + */ + Core_crypto.prototype.getRandomBytes = function(number, continuation) { + var buffer = new Uint8Array(number); + crypto.getRandomValues(buffer); + continuation(buffer.buffer); +}; + +exports.provider = Core_crypto; +exports.name = "core.crypto"; diff --git a/spec/providers/core/core.crypto.unit.spec.js b/spec/providers/core/core.crypto.unit.spec.js new file mode 100644 index 0000000..902ee03 --- /dev/null +++ b/spec/providers/core/core.crypto.unit.spec.js @@ -0,0 +1,25 @@ +var Crypt = require('../../../providers/core/core.crypto'); + +describe("providers/core/Core_crypto", function() { + var crypt; + + beforeEach(function() { + crypt = new Crypt.provider(); + }); + + it("Generates random buffers!", function(done) { + crypt.getRandomBytes(50, function(buffer) { + expect(buffer).toBeDefined(); + var view = new Uint8Array(buffer); + expect(view.length).toEqual(50); + var max = 0; + for (var i = 0; i < view.length; i += 1) { + if (view[i] > max) { + max = view[i]; + } + } + expect(max).toBeGreaterThan(0); + done(); + }); + }); +});