Skip to content

Commit

Permalink
Merge pull request #316 from auth0/random-fallback
Browse files Browse the repository at this point in the history
Fallback to math.random if there is no crypto support
  • Loading branch information
glena authored Jan 17, 2017
2 parents 1e230ff + 3d9a913 commit 6a25a71
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
21 changes: 18 additions & 3 deletions src/helper/random.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
var windowHelper = require('./window');

const randomFallback = {
getRandomValues: function(buffer) {
for(var a = 0; a < buffer.length; a++) {
buffer[a] = Math.floor(Math.random() * 255);
}

return buffer;
}
}

function randomString(length) {
var bytes = new Uint8Array(length);
if (typeof(Uint8Array) !== "undefined") {
var bytes = new Uint8Array(length);
} else {
var bytes = new Array(length);
}

var result = [];
var charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._~';

var cryptoObj = windowHelper.getWindow().crypto || windowHelper.getWindow().msCrypto;
if (!cryptoObj) {
return null;
if (!cryptoObj || typeof(Uint8Array) === "undefined") {
cryptoObj = randomFallback;
}

var random = cryptoObj.getRandomValues(bytes);
Expand Down
2 changes: 1 addition & 1 deletion test/helper/object.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ describe('helpers', function () {
});
});

it('should not breack the string', function () {
it('should not break the string', function () {
var object = "some random string";

var newObject = objectHelper.toCamelCase(object);
Expand Down
3 changes: 2 additions & 1 deletion test/helper/random.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ describe('helpers random', function () {

it('return the a random string', function () {
var string = random.randomString(10);
expect(string).to.be(null);
expect(string).to.not.be(null);
expect(string).to.be.a('string');
});
});
});

0 comments on commit 6a25a71

Please sign in to comment.