0

I've written a client-side application. I am now creating a backend for it to persist data, but am curious about GUID implementations.

Client side, I generate a Song object with a unique ID using the following JavaScript. It is based off of this StackOverflow post.

//Based off of: https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
generateGuid: function () {
    var startStringFormat = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';

    var guid = startStringFormat.replace(/[xy]/g, function (c) {
        var r = Math.floor(Math.random() * 16);

        var v = c === 'x' ? r : (r & 0x3 | 0x8);

        return v.toString(16);
    });

    return guid;
},

Now, I'm defining a class in C# to represent my Song object:

public class Song
{
    public virtual Guid Id { get; set; }
    public virtual Guid PlaylistId { get; set; }
    public virtual int VideoId { get; set; }
    public virtual string Url { get; set; }
    public virtual string Title { get; set; }
    public virtual int Duration { get; set; }
}

Doing so got me wondering about the implications of the interacting Guid objects. Can I just take all of the Song objects I have in localStorage and do a direct translation of their Guids? Should I regenerate all of them?

Community
  • 1
  • 1
Sean Anderson
  • 27,963
  • 30
  • 126
  • 237

3 Answers3

2

As Guid are unique (if correctly generated) you can reuse existing IDs. Be careful, though, because a malicious client can send any ID of course, not just a random one. So a client can easily provoke a collision among his own Guids. If all benevolent clients generate their Guid randomly, a malicious client cannot cause a collision with them. In that sense, a Guid is like a 128-bit password, which is exceptionally strong.

On the other hand, the way you generate those Guids is not using a cryptographically secure random number generator. So I guess you should make the server provide a secure Guid to you by issuing an AJAX call to it.

The generation algorithm shown looks funky to me. You don't need to maintain any particular pattern. You can just generate a Guid consisting of 100% random components.

usr
  • 168,620
  • 35
  • 240
  • 369
2

Since your algorithm is based on pseudo-random numbers generated by Math.random, and since the random number generator is seeded from the current time, it does seem that there is a risk of collisions.

Joe
  • 122,218
  • 32
  • 205
  • 338
0

Seems that under certain circumstances, you actually may get a pretty high chance of collisions with this method. Check this question: Collisions when generating UUIDs in JavaScript?

Community
  • 1
  • 1
jeroenh
  • 26,362
  • 10
  • 73
  • 104