Skip to content

Commit c13b61f

Browse files
committed
Use CSPRNG to generate objectIds
1 parent 774de7b commit c13b61f

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

RestWrite.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// that writes to the database.
33
// This could be either a "create" or an "update".
44

5+
var crypto = require('crypto');
56
var deepcopy = require('deepcopy');
67
var rack = require('hat').rack();
78

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

705-
// Returns a string that's usable as an object id.
706-
// Probably unique. Good enough? Probably!
706+
// Returns a unique string that's usable as an object id.
707707
function newObjectId() {
708708
var chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
709709
'abcdefghijklmnopqrstuvwxyz' +
710710
'0123456789');
711711
var objectId = '';
712-
for (var i = 0; i < 10; ++i) {
713-
objectId += chars[Math.floor(Math.random() * chars.length)];
712+
var bytes = crypto.randomBytes(10);
713+
for (var i = 0; i < bytes.length; ++i) {
714+
// Note: there is a slight modulo bias, because chars length
715+
// of 62 doesn't divide the number of all bytes (256) evenly.
716+
// It is acceptable for our purposes.
717+
objectId += chars[bytes.readUInt8(i) % chars.length];
714718
}
715719
return objectId;
716720
}

0 commit comments

Comments
 (0)