Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use CSPRNG to generate objectIds #73

Merged
merged 1 commit into from
Feb 1, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 8 additions & 4 deletions RestWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// that writes to the database.
// This could be either a "create" or an "update".

var crypto = require('crypto');
var deepcopy = require('deepcopy');
var rack = require('hat').rack();

Expand Down Expand Up @@ -702,15 +703,18 @@ RestWrite.prototype.objectId = function() {
return this.data.objectId || this.query.objectId;
};

// Returns a string that's usable as an object id.
// Probably unique. Good enough? Probably!
// Returns a unique string that's usable as an object id.
function newObjectId() {
var chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789');
var objectId = '';
for (var i = 0; i < 10; ++i) {
objectId += chars[Math.floor(Math.random() * chars.length)];
var bytes = crypto.randomBytes(10);
for (var i = 0; i < bytes.length; ++i) {
// Note: there is a slight modulo bias, because chars length
// of 62 doesn't divide the number of all bytes (256) evenly.
// It is acceptable for our purposes.
objectId += chars[bytes.readUInt8(i) % chars.length];
}
return objectId;
}
Expand Down