2009-08-24 11 views
14

Necesito generar identificadores únicos en el navegador. Actualmente, estoy usando esto:La mejor manera de generar identificadores únicos del lado del cliente (con Javascript)

Math.floor(Math.random() * 10000000000000001) 

me gustaría usar el tiempo UNIX actual ((new Date).getTime()), pero me preocupa que si dos clientes a generar los identificadores en el exacta mismo tiempo, wouldn no ser único

¿Puedo utilizar la hora actual de UNIX (me gustaría porque de esa forma los ID almacenarían más información)? Si no es así, ¿cuál es la mejor manera de hacer esto

Respuesta

16

puede crear un GUID utilizando los siguientes enlaces (tal vez el tiempo UNIX + 2 dígitos al azar?):

http://softwareas.com/guid0-a-javascript-guid-generator

Create GUID/UUID in JavaScript?

Esta voluntad maximiza tus posibilidades de "singularidad".

Como alternativa, si se trata de una página segura, puede concatenar la fecha/hora con el nombre de usuario para evitar múltiples valores generados simultáneamente.

+2

Me gustaría ir con la última sugerencia, Concatene con FECHA/HORA con nombre de usuario. – kayteen

+1

+1 para "concatenar la fecha/hora con el nombre de usuario para evitar múltiples valores generados simultáneamente". – Imagist

8

https://github.com/broofa/node-uuid proporciona UUID compatibles con RFC según la marca de tiempo o los números aleatorios. Un archivo único sin dependencias, compatible con marcas de tiempo o UUID aleatorios #, utiliza API nativas para números aleatorios de calidad criptográfica, si están disponibles, además de otros objetos valiosos.

1
var c = 1; 
function cuniq() { 
    var d = new Date(), 
     m = d.getMilliseconds() + "", 
     u = ++d + m + (++c === 10000 ? (c = 1) : c); 

    return u; 
} 
+1

buen trozo de código pero c no está definido – lolol

+0

disculpas @ololol –

+0

¿por qué 'c' está fuera de la declaración de variables en' cuniq() '? Además, ¿podría explicar la lógica detrás de este algoritmo? – vsync

1

Aquí está mi código de JavaScript para generar guid. Lo hace mapeo rápido hexagonal y muy eficiente:

AuthenticationContext.prototype._guid = function() { 
    // RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or 
    // pseudo-random numbers. 
    // The algorithm is as follows: 
    //  Set the two most significant bits (bits 6 and 7) of the 
    //  clock_seq_hi_and_reserved to zero and one, respectively. 
    //  Set the four most significant bits (bits 12 through 15) of the 
    //  time_hi_and_version field to the 4-bit version number from 
    //  Section 4.1.3. Version4 
    //  Set all the other bits to randomly (or pseudo-randomly) chosen 
    //  values. 
    // UUID     = time-low "-" time-mid "-"time-high-and-version "-"clock-seq-reserved and low(2hexOctet)"-" node 
    // time-low    = 4hexOctet 
    // time-mid    = 2hexOctet 
    // time-high-and-version = 2hexOctet 
    // clock-seq-and-reserved = hexOctet: 
    // clock-seq-low   = hexOctet 
    // node     = 6hexOctet 
    // Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx 
    // y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10 
    // y values are 8, 9, A, B 
    var guidHolder = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'; 
    var hex = 'abcdef'; 
    var r = 0; 
    var guidResponse = ""; 
    for (var i = 0; i < 36; i++) { 
     if (guidHolder[i] !== '-' && guidHolder[i] !== '4') { 
      // each x and y needs to be random 
      r = Math.random() * 16 | 0; 
     } 

     if (guidHolder[i] === 'x') { 
      guidResponse += hex[r]; 
     } else if (guidHolder[i] === 'y') { 
      // clock-seq-and-reserved first hex is filtered and remaining hex values are random 
      r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0?? 
      r |= 0x8; // set pos 3 to 1 as 1??? 
      guidResponse += hex[r]; 
     } else { 
      guidResponse += guidHolder[i]; 
     } 
    } 

    return guidResponse; 
}; 
2

En navegador moderno puede utilizar crypto:

var array = new Uint32Array(1); 
window.crypto.getRandomValues(array); 
console.log(array); 
+0

Genial, ya que esto utiliza la entropía del sistema, que es mucho más alta que la que se puede obtener dentro de un navegador. –

Cuestiones relacionadas