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?
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.