I'm writing a node.js application that involves handling clients based on their ID without any real way of confirming that the ID a client says it has is its actual ID. That is, it's possible for a client to tell the server it has an ID of foo
even though it was assigned an ID of bar
, thus being able to send and receive information from the server as though it was the existing client foo
. This is obviously a significant security risk, so I want to ensure it's more or less effectively impossible to guess another client's ID.
I have a clients
object, with keys corresponding to the ID of each client. I'm using the crypto
library for PRNG and hashing; hashFct
returns a SHA256 digest of the input. The following code is run when a client sends its initial creation request.
//Generate random string, hash, and truncate to 8 characters
rand = crypto.randomBytes(32).toString("base64");
id = hashFct(rand).substr(0, 8);
//Loop until unique
for(var i = 0; !!clients[id]; i++) {
rand = crypto.randomBytes(32).toString("base64");
id = hashFct(rand).substr(0, 8);
}
...
clients[id] = {
id: id,
...
}
The idea behind the "loop until unique" section is to check if the clients
object already has a value in it with the pseudo-random id as a key, and to regenerate the ID and try again until it's unique. Then the ID is put into the clients
object as a new client, and the code moves on.
Is there anything glaringly stupid about this approach that I'm overlooking? Is there a better way to ensure an ID is unique, or perhaps a better way of generating the IDs?