Use CSPRNG to generate objectIds
This commit is contained in:
12
RestWrite.js
12
RestWrite.js
@@ -2,6 +2,7 @@
|
|||||||
// that writes to the database.
|
// that writes to the database.
|
||||||
// This could be either a "create" or an "update".
|
// This could be either a "create" or an "update".
|
||||||
|
|
||||||
|
var crypto = require('crypto');
|
||||||
var deepcopy = require('deepcopy');
|
var deepcopy = require('deepcopy');
|
||||||
var rack = require('hat').rack();
|
var rack = require('hat').rack();
|
||||||
|
|
||||||
@@ -702,15 +703,18 @@ RestWrite.prototype.objectId = function() {
|
|||||||
return this.data.objectId || this.query.objectId;
|
return this.data.objectId || this.query.objectId;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Returns a string that's usable as an object id.
|
// Returns a unique string that's usable as an object id.
|
||||||
// Probably unique. Good enough? Probably!
|
|
||||||
function newObjectId() {
|
function newObjectId() {
|
||||||
var chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
|
var chars = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
|
||||||
'abcdefghijklmnopqrstuvwxyz' +
|
'abcdefghijklmnopqrstuvwxyz' +
|
||||||
'0123456789');
|
'0123456789');
|
||||||
var objectId = '';
|
var objectId = '';
|
||||||
for (var i = 0; i < 10; ++i) {
|
var bytes = crypto.randomBytes(10);
|
||||||
objectId += chars[Math.floor(Math.random() * chars.length)];
|
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;
|
return objectId;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user