Skip to content

Commit 251ec4d

Browse files
committed
Merge pull request #73 from dchest/csprng
Use CSPRNG to generate objectIds
2 parents bce6244 + c13b61f commit 251ec4d

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

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

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

0 commit comments

Comments
 (0)