I need to generate a random hex string of some specified length (say 32 digits long). In python its a 2 liner where I can just do this:
import os, binascii
binascii.hexlify(os.urandom(32))
Out[16]:
'8085b10e59dee0f122e0de1f27813852168f1db9cabeb1e769463accfbe34796'
I need to do the same in JS. I looked at other questions on SO but did not come across exactly what I need. So I did the following loop in JS which works but it might be overkill and looks a bit clumsy. What is a shorter way to do it? Ideally I am looking for something as concise as the python snippet above.
var a = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f'];
var secret = function(n) {
sec = "";
for (var i = 0; i < n; i++) {
var idx = Math.floor(Math.random() * a.length);
sec = sec + a[idx];
}
return sec;
};
console.log(secret(32)); // Outputs adebe66ed8e716e5406d20e304c1553b
Aucun commentaire:
Enregistrer un commentaire