Skip to content

Commit

Permalink
expose core randomness
Browse files Browse the repository at this point in the history
```javascript
freedom['core.crypto']().getRandomBytes(n).then(function (buffer) {
  ...
});
```
address freedomjs/freedom-for-firefox#33
  • Loading branch information
willscott committed Apr 23, 2015
1 parent d58e662 commit a576761
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions interface/core.crypto.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "core.crypto",
"api": {
"getRandomBytes": {"type": "method", "value": ["number"], "ret": "buffer"}
}
}
31 changes: 31 additions & 0 deletions providers/core/core.crypto.js
Original file line number Diff line number Diff line change
@@ -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";
25 changes: 25 additions & 0 deletions spec/providers/core/core.crypto.unit.spec.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
});

0 comments on commit a576761

Please sign in to comment.