Last active
November 18, 2025 20:45
-
-
Save aozen/5c930f2ef288a46c6cd7910ffbc515e4 to your computer and use it in GitHub Desktop.
generate random password with given length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env node | |
| const crypto = require('crypto') | |
| const defaultOpts = { | |
| length: 20, | |
| includeLower: true, | |
| includeUpper: true, | |
| includeNumbers: true, | |
| includeSymbols: true, | |
| excludeSimilar: true, // avoid 0, O, l, 1 | |
| excludeAmbiguous: true, // punctuation like {}[]()/\ | |
| prefix: '', | |
| customChars: '', // override allowed chars entirely | |
| } | |
| const generate = (opts = {}) => { | |
| const o = { ...defaultOpts, ...opts } | |
| let pool = o.customChars || '' | |
| if (!o.customChars) { | |
| if (o.includeLower) pool += 'abcdefghijklmnopqrstuvwxyz' | |
| if (o.includeUpper) pool += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' | |
| if (o.includeNumbers) pool += '0123456789' | |
| if (o.includeSymbols) pool += '!@#$%^&*()_+[]{}|;:,.<>?' | |
| } | |
| if (o.excludeSimilar) pool = pool.replace(/[0OIl1]/g, '') | |
| if (o.excludeAmbiguous) pool = pool.replace(/[\{\}\[\]\(\)\/\\'"`,.;:~]/g, '') | |
| if (!pool) throw new Error('Character pool is empty. enable/change some options or specify customChars') | |
| const bytes = crypto.randomBytes(o.length) | |
| let pwd = '' | |
| for (let i = 0; i < o.length; i++) { | |
| const idx = bytes[i] % pool.length | |
| pwd += pool[idx] | |
| } | |
| return o.prefix + pwd | |
| } | |
| const length = Number(process.argv[2]) || 20 | |
| console.log(generate({ length })) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SETUP
or export into /usr/local/bin and you probably wont need to export PATH.
Then use with or without param: