Can we use process.hrtime() as universal unique id within the current process ?
var uuid = parseInt(process.hrtime().join(''));
You can use process.hrtime() to create identifiers with low chance of collision, but they are not unique, especially not across application restarts (which matters if you persist any of them to a database or similar), and not when several threads/processes/instances are involved.
From the documentation:
These times are relative to an arbitrary time in the past, and not related to the time of day
Also, by using parseInt(....join('')), you are introducing a second way for collisions to happen: e.g. [1, 23] and [12, 3] will lead to the same result.
If you want to build your own solution (a[0] * 1e9 + a[1] comes to mind as a naive approach), you should also be aware of the precision limits of JavaScript numbers -- there's a reason why hrtime() returns a tuple and not just a single number. When in doubt, when you need proper UUIDs, you should probably use proper UUIDs ;-)
This question is rather old, but I managed to figure out something that works like this (partially, on a single machine, and NOT completely validated yet). See Is this a viable, monotonically increasing timeId in javascript?. (Note, requires Node 10 or 11, and I've only validated on Mac OS Mojave so far)
That solution will not provide a UUID, but it should produce an ID that is always increasing in value. Some other machine/process ID would have to be appended to it to make it really unique.
Related
I will see people use this method to random seed init for Go to make random!
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
I am 100% sure this method is not safe,
guess time.Now().UTC().UnixNano() is 1000X> easy then find real generated random password
Does any one have an idea, also call windows api to generate random seed is good idea I think?
If security is important to begin with, then you should "drop" math/rand and use crypto/rand in the first place.
If security is "not" important, then seeding with time.Now().UnixNano() is perfectly fine. (Note that it is needless to call Time.UTC() because Time.UnixNano() returns the Unix time which is specified to be in UTC.)
Note that there are 2592000000000000 nanoseconds in 24 hours, so even if the day is known, theoretically there are 2.592*1015 different seed combinations, perfectly enough for non-secure scenarios.
rand.Seed() is to seed the global Rand of the math/rand package. You don't have to (you can't) seed the crypto/rand package.
See possible duplicate: Generate random string WITHOUT time?
See related questions:
Generating a random, fixed-length byte array in Go
How to get a sample of random numbers in golang?
My client side code generates UUIDs and sends them to the server.
For example, '6ea140caa83b485f9c98ebaacfb536ce' would be a valid uuid4 to send back.
Is there any way to detect or prevent a user sending back a valid but "user generated" uuid4 like 'babebabebabe4abebabebabebabebabe'?
For example, one way to prevent a certain class of these would be looking at the number of occurrences of 0's and 1's in the binary representation of the number. This could work for a string like '00000000000040000000000000000000' but not for all strings.
It depends a little ...
there is no way to be entirely sure, but depending on the UUID version/subtype you are using there MIGHT be a way to detect at least some irregular values:
https://www.rfc-editor.org/rfc/rfc4122#section-4.1 defines the original version 1 of UUIDs, and a layout for the uuid fields ...
you could for example check if the version and variant fields are valid...
if your UUID generation actually uses Version 1 you could, in addition to the first test of version and variant, test if the timestamp is in a valid range ... for example, it might be unlikely that the UUID in question was generated in the year 1600 ... or in the future
so tests like there could be applied to check if the value actually makes sense, or is complete gibberish ... it can not protect you against someone thinking: ok ... lets analyze this and provide a manually choosen value that satisfies all conditions
No there is no way to distinguish user generated UUID's from randomly generated UUID's.
To start with, a user generated UUID may as well be partially random. But lets assume that it is not.
In that case you want to detect a pattern. However, although you give an example of a pattern, a pattern can be almost anything. For instance, the following byte array looks completely random, right?
40 09 21 fb 54 44 2d 18
But actually it is a nothing-up-my-sleeve number usually used within the cryptographic community: it's simply the encoding of Pi (in this case as a 64 bit floating point, as I was somewhat lazy).
There are certainly randomness tests, for instance FIPS random number tests. Those require a very high number of input to see if something fails or succeeds. Even then: it only shows that certain statistical properties have indeed been attained by a random number generator. The encoding of Pi might very well succeed.
And annoyingly, a random number generator is perfectly possible to generate bit strings that do not look random at all, if just by chance. The smaller the bit string the more chance of the random number generator generating something that doesn't look random at all. And UUID's are not all that big.
So yes, of course you can do some tests, but you can never be sure: you will have both false positives as false negatives.
I would like to represent the timestamp coming from an HTMLMediaElement. Its defining characteristics are:
Its value is represented as a Double
It can be queried at any time using getCurrentTime :: IO Double (as partially applied on a given HTMLMediaElement)
It is potentially continuously changing (whenever the media player is playing)
My initial plan was to represent it as a Behavior t Double that re-runs the IO Double every time it is observed, but that hasn't worked out too well.
Things I've tried:
Using a Behavior that is prodded under the hood at a fixed frequency, as described in the workaround section of this question
Passing an Event t () representing the desired sampling frequency, and returning an Event t Double that holds the coinciding timestamps
I don't really like either -- the first one either couples the behaviour (sorry) too much to my specific use case (if I use the eventual sampling frequency I'll use in my app) or seems wasteful (if I use something like 1 kHz sampling when creating the Behavior just to then sample it at 60 Hz on the application end), and the second is quite inflexible if you want to do more than one thing with the timestamp at different sampling rates.
Right now, using an Event to explicitly sample the time (your second option) value is your best bet. We haven't yet created a way to write Behaviors that lazily poll outside resources, although that is something that I hope we'll be able to get done soon.
Keep in mind that, with your second option, you don't necessarily need to use a specific sampling rate; instead, you can sample on-demand, and even have multiple locations doing that sampling. It's not perfect, but I hope that'll let you get the job done!
I have a device and for each device I wish to generate a string of the following format: XXXXXXXX. Each X is either B, G, or R. An example is GRBRRBRB. This gives me roughly 7000 keys to work with which is enough as I doubt I'll have more devices.
I was thinking I could generate them all before hand, and dump them in a file or something, and just get the next key available from that, but I wonder if there is a better way to do this.
I know there are better ways to do it if I don't need guaranteed uniqueness but I definitely need that so I'm not sure what the best way to do it is.
Treat it as a ternary representation of a number, where R=0, B=1, G=2. So when you're writing the nth ID, the first digit is R if n % 3 == 0, B if n % 3 == 1, G otherwise. The second digit is the same, except you're looking at (n / 3) % 3; then for the third digit look at (n / 3^2) % 3; etc.
If your devices have any unique sequential ID available, I would implement a deterministic algorithm for that 'unique string' retrieval.
I mean something like
GetDeviceRgbString(deviceid) { // deterministic algorithm returning appropriate value using device id to choose it }
Otherwise consider storing it somewhere (depends on your environment, you gave little data about it, but that may be file, database, ... ) and marking them as used, preferably keep the data about assigned device, you may need it once.
I'm going to assume you want them unique to identify them for some type of network (internet) activity. That being the case, I would have a web service that can take care of making sure each device is unique by handing out IDs. The software on each device would see if it has an ID (stored locally), and if not, request one from the web service.
I am using:
CassandraUtil::uuid1();
This is what I get:
ämªðÏBà=0£Ï‰
I though it would output a int.
What is going on? Is it normal?
Also should I use uuid1 or 2 or 3 or 4 or ...?
Thanks in advance!
There are a few parts to UUIDs in phpcassa. First, how to generate one. The following functions are useful for this:
$my_uuid_string = phpcassa\UUID::uuid1();
$my_uuid_string = phpcassa\UUID::uuid4();
uuid1() generates a v1 UUID, which has a timestamp component, and is called TimeUUIDType in Cassandra. uuid4() generates a totally random UUID, and is called LexicalUUIDType in Cassandra. (The other uuidX() functions aren't generally that useful.) What this function gives you back is a byte array representation of the UUID -- basically a 16 byte string. This is what your "ämªðÏBà=0£Ï‰" string is. When you are trying to insert a UUID into Cassandra, this is what you want to use.
It's possible to make a UUID object which has useful methods and attributes from this byte array:
$my_uuid = phpcassa\UUID::import($my_uuid_string);
With $my_uuid, you can get a pretty string representation like 'd881bf7c-cf8f-11e0-85e5-00234d21610a' by getting $my_uuid->string. You can get back the byte representation by doing $my_uuid->bytes. Any uuid data that you get back from Cassandra will by in the byte array format, so you need to use UUID::import() on it if you want a UUID object.
Also, UUID::import() also works on the pretty string representation as well (the one that looks like ''d881bf7c-cf8f-11e0-85e5-00234d21610a').
Last, don't forget about the documentation for the UUID class.
EDIT: updated links and class names to match the latest phpcassa API
uuid1() generates a UUID based on the current time and the MAC address of the machine.
Pros: Useful if you want to be able to sort your UUIDs by creation time.
Cons: Potential privacy leakage since it reveals which computer it was generated on and at what time.
Collisions possible: If two UUIDs are generated at the exact same time (within 100 ns) on the same machine. (Or a few other unlikely marginal cases.)
uuid2() doesn't seem to be used anymore.
uuid3() generates a UUID by taking an MD5 hash of an arbitrary name that you choose within some namespace (e.g. URL, domain name, etc).
Pros: Provides a nice way of assigning blocks of UUIDs to different namespaces. Easy to reproduce the UUID from the name.
Cons: If you have a unique name already, why do you need a UUID?
Collisions possible: If you reuse a name within a namespace, or if there is a hash collision.
uuid4() generates a completely random UUID.
Pros: No privacy concerns. Don't have to generate unique names.
Cons: No structure to UUIDs.
Collisions possible: If you use a bad random number generator, reuse a random seed, or are very, very unlucky.
uuid5() is the same as uuid3(), except using a SHA-1 hash instead of MD5. Officially preferred over uuid3().