Is Date epoch a secure unique identifier?

时间:2015-06-25 18:59:30

标签: javascript node.js mongodb token

I'm writing a Node API and got a model for which I gotta generate a random number of 15 digits. This must be unique and should not look trivial (I can't get an autoincrement). I really don't want to generate a number and query against Mongo database for existance checking. I would have to generate some kind of while loop based on promises that way. I thought about simply using new Date().epoch but, is this going to be unique? could I ever get a duplicate? Then I also thought on appending something like: function privateKey (howMany, chars) { chars = chars || "0123456789"; var rnd = crypto.randomBytes(howMany) , value = new Array(howMany) , len = chars.length; for (var i = 0; i < howMany; i++) { value[i] = chars[rnd[i] % len] }; return parseInt(value.join('')); } To include a duplicity avoiding. How should I implement this? Edit, this should be a number. I know there's uuid and Mongo ObjectId but they're not only numbers.

3 个答案:

答案 0 :(得分:3)

I don't think it's a good idea. One of the reasons is system time skew. Upon synchronizing time with some benchmark server you would get duplicates. In fact this can happen on the runtime every couple of hours. Some servers have serious time drift and they sync time every one in a while. Any time this happens you can get duplicates.

答案 1 :(得分:1)

Why not use ObjectId? According to the MongoDB documentation, ObjectId is a 12-byte BSON type, constructed using: a 4-byte value representing the seconds since the Unix epoch, a 3-byte machine identifier, a 2-byte process id, and a 3-byte counter, starting with a random value. ObjectIds are small and fast to generate. MongoDB clients should add an _id field with a unique ObjectId. However, if a client does not add an _id field, mongod will add an _id field that holds an ObjectId. Edit : You can convert ObjectId to a number of length of your choice using the below code. var idNum = parseInt(ObjectId.valueOf(), 15);

答案 2 :(得分:1)

Using time for generating unique IDs is not safe. As ak. suggested it you could get duplicates due to bad synchro. If not having a number is not critical, you should use node-uuid which is based on RFC4122 for unique ID generation.