Skip to content

Instantly share code, notes, and snippets.

@felquis
Created March 11, 2016 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felquis/1261abef589af89f1114 to your computer and use it in GitHub Desktop.
Save felquis/1261abef589af89f1114 to your computer and use it in GitHub Desktop.
Truly Global Unique Identifier generator for Web Apps using Crypto API, with fallback to pseudo random numbers Math.random
/*
Cria um Globally Unique Identifier randomico
para uso junto ao Google Measurement Protocol
A discussão sobre isso é grande e eu cansei de ler
o lance é o seguinte, usamos `window.crypto` quando disponível
quando não disponível (browsers antigos) usamos o Math.random
que não é la grandes coisas, mas mesmo assim já é TOP!
Resposta no Stackoverflow http://stackoverflow.com/a/8472700/2588556
+ minhas adaptações
*/
// Verifica o sopporte de crypto e crypto.getRandomValues usando vendors
function cryptoGetRandomValues(buffer) {
// support table http://caniuse.com/#feat=getrandomvalues
var crypto = window.crypto || window.msCrypto
function checkMethod() {
// Verifica suporte aos métodos necessários
var hasCrypto = typeof crypto !== 'undefined'
var hasGetRandomValues = typeof crypto.getRandomValues !== 'undefined'
return hasCrypto && hasGetRandomValues
}
if (buffer && checkMethod()) {
return crypto.getRandomValues(buffer)
}
return checkMethod()
}
// Gera um Trully Globally Unique Identifier
// Trully, pois usa a crypto API
function generateTGUID() {
// If we have a cryptographically secure PRNG, use that
// http://stackoverflow.com/questions/6906916/collisions-when-generating-uuids-in-javascript
var buffer = new Uint16Array(8)
// Estranho, mas a função altera o array buffer
cryptoGetRandomValues(buffer)
var S4 = function(num) {
var ret = num.toString(16)
while(ret.length < 4){
ret = '0' + ret
}
return ret
}
return (S4(buffer[0])+S4(buffer[1])+'-'+S4(buffer[2])+'-'+S4(buffer[3])+'-'+S4(buffer[4])+'-'+S4(buffer[5])+S4(buffer[6])+S4(buffer[7]))
}
// Retorna uma Aproximação de um Globally Unique Identifier
// Deve ser usado apenas quando window.crypto não estiver disponível
function generateAGUID() {
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8)
return v.toString(16)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment