Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Created March 14, 2019 02:26
Show Gist options
  • Save TravisMullen/d542ddad929bf898f35433f582f40830 to your computer and use it in GitHub Desktop.
Save TravisMullen/d542ddad929bf898f35433f582f40830 to your computer and use it in GitHub Desktop.
Unique Nonce Generator
const {
randomFill
} = require('crypto')
const dirtyNonce = {}
const _nonce = () => {
const buf = Buffer.alloc(16)
return new Promise((resolve, reject) => {
randomFill(buf, (err, buf) => {
if (err) { reject(err) }
console.log(buf.toString('hex'))
resolve(buf)
})
})
}
const nonceGenerator = async () => {
console.time(`nonce generator`)
let nonce = await _nonce()
while (isDirty(nonce)) {
nonce = await _nonce()
}
console.timeEnd(`nonce generator`)
return nonce
}
const isDirty = nonce => {
const iv = nonce.toString('hex')
if (dirtyNonce[iv]) {
return true
}
dirtyNonce[iv] = true
return false
}
const isClean = nonce => !(isDirty(nonce))
const dirty = () => (
Object.keys(dirtyNonce)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment