davalapar / crypto

/dev/urandom, HOTP, TOTP, Scrypt
1 stars 0 forks source link

/dev/urandom #2

Closed davalapar closed 5 years ago

davalapar commented 5 years ago
const fs = require('fs');

const urandom = (length) => new Promise((resolve) => {
  const stream = fs.createReadStream('/dev/urandom');
  stream.on('data', (data) => { // emits 65536-length buffer
    stream.destroy();
    resolve(data.slice(0, length));
  });
});

urandom(32).then(console.log).catch(console.error);
davalapar commented 5 years ago

async

const filehandle = fsPromises.open('/dev/urandom');
const urandom = async (length) => {
  const buffer = Buffer.alloc(length);
  await filehandle.read(buffer, 0, length, 0);
  return buffer;
};
const close = () => filehandle.close();

sync

const fd = fs.openSync('/dev/urandom');
const urandom = (length) => {
  const buffer = Buffer.alloc(length);
  fs.readSync(fd, buffer, 0, 32, 0);
  return buffer;
};
const close = () => fs.closeSync(fd);
urandom(32);
davalapar commented 5 years ago

https://www.namecheap.com/security/2fa-two-factor-authentication/

davalapar commented 5 years ago

https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html#crypto_crypto_randombytes_size_callback