pwgen_true_random_seed/true_random_seed_pw_gen.py

64 lines
2.4 KiB
Python

import json
import random
from jsonrpcclient import Request
from jsonrpcclient.http_client import HTTPClient
from contextlib import contextmanager
import sys, os
import argparse
#argparse
parser = argparse.ArgumentParser(prog='True Random Password Generator', description='Uses the random.org basic API with a free subscription to initialize a true random seed for the python random function to create -c passwords of -l length')
parser.add_argument('-a', '--apikey', default=os.environ['HOME']+'/.bin/.apikey' , type=str, help='path to a file which contains only a random.org api key')
parser.add_argument('-c', '--count', default='50', type=int, help='the number of passwords to generate')
parser.add_argument('-l', '--length', default='20', type=int, help='the length the generated passwords should have')
args = parser.parse_args()
#Loading the .apikey file
try:
with open (args.apikey, 'r') as f:
apikey=f.readline()
except:
print("Please provide a file that contains only your apikey with the -a option, if no option is provided the script assumes that the apikey file has this path: " + args.apikey)
exit(1)
#Prevent program segments from blabbering to stdout/stderr
@contextmanager
def suppress_std_err_out():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
old_stderr = sys.stderr
sys.stderr = devnull
try:
yield
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
#Blabbering program segment
with suppress_std_err_out():
client = HTTPClient("https://api.random.org/json-rpc/2/invoke")
response = client.send(Request("generateIntegers", apiKey=apikey,n="1",min='1',max="1000000000"))
seed=response["random"]["data"]
#Filling the seed with a (true) random number
characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789#_@!?+"
char_lst = [x for x in characters]
random.seed(int(seed[0]))
#Building password
for _ in range(0,args.count):
pw_string=""
for _ in range(0,args.length):
pw_string += char_lst[random.randint(0, 67)]
print(pw_string)
print("-------------------------------------------")
bit_uses_left=response["bitsLeft"] // response["bitsUsed"]
uses_left = bit_uses_left if bit_uses_left < response["requestsLeft"] else response["requestsLeft"]
print("This apikey (with free api subscription) has another " + str(uses_left) + " uses left today")