Skip to content

Instantly share code, notes, and snippets.

@maxfischer2781
Created February 6, 2019 12:05
Show Gist options
  • Save maxfischer2781/694534b5d56b089c34fa389d0814043a to your computer and use it in GitHub Desktop.
Save maxfischer2781/694534b5d56b089c34fa389d0814043a to your computer and use it in GitHub Desktop.
Create a random string/password
#!/usr/bin/env python3
from __future__ import print_function
import random
import math
import sys
import argparse
#: alphabet of 2**6 letters
ALPHABET_64 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ+="
def make_pw(length=32, alphabet=ALPHABET_64, rng=None):
rng = rng or random.SystemRandom()
bits = math.log(len(alphabet), 2)
if int(bits) != bits:
print('Length of alphabet is not a power of 2, may bias selection', file=sys.stderr)
bits = int(bits)
letters = []
while len(letters) < length:
index = rng.getrandbits(bits)
try:
letters.append(alphabet[index])
except IndexError:
continue
return ''.join(letters)
if __name__ == "__main__":
CLI = argparse.ArgumentParser('Random Password generator')
CLI.add_argument(
'-l',
'--length',
help='number of characters is password',
default=128,
type=int,
)
CLI.add_argument(
'-a',
'--alphabet',
help='sequence of characters to draw from',
default=ALPHABET_64,
)
options = CLI.parse_args()
print(make_pw(length=options.length, alphabet=options.alphabet))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment